crossroads

Git mirror of https://crossroads.e-tunity.com/
git clone git://git.finwo.net/app/crossroads
Log | Files | Refs | LICENSE

commit f08b10bd9e28e4610f6306569b07b40a5349d629
parent 830934bef1a21448ed59896145c566594bf6980d
Author: finwo <finwo@pm.me>
Date:   Sat,  3 Jan 2026 19:38:41 +0100

2.68

Diffstat:
MChangeLog | 17+++++++++++++++++
ALICENSE | 607+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MMakefile | 2+-
Mxr/DispatchAlgorithms/external/target.cc | 10++++++----
Mxr/DispatchAlgorithms/hashedip/target.cc | 12+++++-------
Mxr/DispatchAlgorithms/leastconn/target.cc | 18++++++++++--------
Mxr/DispatchAlgorithms/roundrobin/target.cc | 9++++-----
Mxr/DispatchAlgorithms/storedip/target.cc | 16+++++++++-------
Mxr/DispatchAlgorithms/weightedload/target.cc | 5++---
Mxr/Dispatchers/dispatcher/checkdos.cc | 65++++++++++++++++++++++++++++++++++++-----------------------------
Mxr/Dispatchers/dispatcher/clientipstr.cc | 7++-----
Mxr/Dispatchers/httpdispatcher/handle.cc | 16++++++++--------
Mxr/Dispatchers/httpdispatcher/senderrorpage.cc | 4++--
Mxr/Dispatchers/tcpdispatcher/dispatch.cc | 15+++++++--------
Mxr/Dispatchers/tcpdispatcher/execute.cc | 28+++++++++++++---------------
Mxr/Dispatchers/tcpdispatcher/handle.cc | 9++++-----
Mxr/ThreadsAndMutexes/mutex/lock.cc | 12++++--------
Mxr/ThreadsAndMutexes/mutex/mutex | 15+++++++--------
Axr/ThreadsAndMutexes/mutex/mutex1.cc | 6++++++
Dxr/ThreadsAndMutexes/mutex/plock.cc | 17-----------------
Axr/ThreadsAndMutexes/mutex/trylock.cc | 10++++++++++
Mxr/ThreadsAndMutexes/mutex/unlock.cc | 9+++------
Axr/ThreadsAndMutexes/mutexnode/balance.cc | 7+++++++
Axr/ThreadsAndMutexes/mutexnode/copy.cc | 8++++++++
Axr/ThreadsAndMutexes/mutexnode/destroy.cc | 6++++++
Axr/ThreadsAndMutexes/mutexnode/mutexnode | 42++++++++++++++++++++++++++++++++++++++++++
Axr/ThreadsAndMutexes/mutexnode/mutexnode1.cc | 5+++++
Axr/ThreadsAndMutexes/mutexnode/mutexnode2.cc | 5+++++
Axr/ThreadsAndMutexes/mutexnode/mutexnode3.cc | 5+++++
Axr/ThreadsAndMutexes/mutexnode/opis.cc | 9+++++++++
Axr/ThreadsAndMutexes/mutexnode/weight.cc | 10++++++++++
Axr/ThreadsAndMutexes/mutextable/balance.cc | 5+++++
Axr/ThreadsAndMutexes/mutextable/copy.cc | 8++++++++
Axr/ThreadsAndMutexes/mutextable/destroy.cc | 7+++++++
Axr/ThreadsAndMutexes/mutextable/hash.cc | 5+++++
Axr/ThreadsAndMutexes/mutextable/lock.cc | 5+++++
Axr/ThreadsAndMutexes/mutextable/mutextable | 30++++++++++++++++++++++++++++++
Axr/ThreadsAndMutexes/mutextable/mutextable1.cc | 8++++++++
Axr/ThreadsAndMutexes/mutextable/mutextable2.cc | 5+++++
Axr/ThreadsAndMutexes/mutextable/mutextable3.cc | 5+++++
Axr/ThreadsAndMutexes/mutextable/opis.cc | 9+++++++++
Axr/ThreadsAndMutexes/mutextable/unlock.cc | 5+++++
Axr/ThreadsAndMutexes/mutextable/weight.cc | 5+++++
Axr/ThreadsAndMutexes/mutextree/balance.cc | 5+++++
Axr/ThreadsAndMutexes/mutextree/copy.cc | 6++++++
Axr/ThreadsAndMutexes/mutextree/destroy.cc | 5+++++
Axr/ThreadsAndMutexes/mutextree/lock.cc | 7+++++++
Axr/ThreadsAndMutexes/mutextree/mutextree | 33+++++++++++++++++++++++++++++++++
Axr/ThreadsAndMutexes/mutextree/mutextree1.cc | 4++++
Axr/ThreadsAndMutexes/mutextree/mutextree2.cc | 5+++++
Axr/ThreadsAndMutexes/mutextree/mutextree3.cc | 5+++++
Axr/ThreadsAndMutexes/mutextree/nodelock.cc | 24++++++++++++++++++++++++
Axr/ThreadsAndMutexes/mutextree/nodeunlock.cc | 13+++++++++++++
Axr/ThreadsAndMutexes/mutextree/opis.cc | 9+++++++++
Axr/ThreadsAndMutexes/mutextree/unlock.cc | 5+++++
Axr/ThreadsAndMutexes/mutextree/weight.cc | 5+++++
Mxr/ThreadsAndMutexes/thread/run.cc | 8++++----
Mxr/ThreadsAndMutexes/thread/start.cc | 4++--
Mxr/ThreadsAndMutexes/thread/thread | 4++--
Mxr/ThreadsAndMutexes/threadlist/deregister1.cc | 4++--
Mxr/ThreadsAndMutexes/threadlist/enregister.cc | 4++--
Mxr/backend/addbytes.cc | 4++--
Mxr/backend/available.cc | 16+++++++---------
Mxr/backend/backend | 1-
Mxr/backend/check.cc | 33++++++++++++++++-----------------
Mxr/backend/connect.cc | 13++++++-------
Mxr/backend/endconnection.cc | 4++--
Mxr/backend/live.cc | 4++--
Mxr/backend/markconnecterror.cc | 4++--
Mxr/backend/startconnection.cc | 8++++----
Mxr/backend/up.cc | 4++--
Mxr/backenddef/weight.cc | 4++--
Mxr/balancer/addbackend2.cc | 10+++++-----
Mxr/balancer/deletebackend.cc | 4++--
Mxr/balancer/init.cc | 12+++++-------
Mxr/balancer/serve.cc | 64+++++++++++++++++++++++++++++++---------------------------------
Mxr/config/addserverheader.cc | 4++--
Mxr/config/addxforwardedfor.cc | 4++--
Mxr/config/addxrversion.cc | 4++--
Mxr/config/buffersize.cc | 4++--
Mxr/config/changeserverheader.cc | 4++--
Mxr/config/fastclose.cc | 4++--
Mxr/config/ipstoretimeout.cc | 4++--
Mxr/config/maxconn.cc | 4++--
Mxr/config/pidfile.cc | 4++--
Mxr/config/prefixtimestamp.cc | 4++--
Mxr/config/removeserverheader.cc | 4++--
Mxr/config/stickyhttp.cc | 4++--
Mxr/dnsentry/resolve.cc | 6+++---
Mxr/etc/Makefile.class | 2+-
Mxr/etc/c-conf | 2+-
Mxr/etc/usage.txt | 5+++--
Mxr/fdset/wait.cc | 12++++++------
Mxr/httpbuffer/cookievalue.cc | 2+-
Mxr/httpbuffer/findheader.cc | 13++++++++++---
Mxr/httpbuffer/firstline.cc | 39++++++++++++++++++++++++++++++++++-----
Mxr/httpbuffer/paramvalue.cc | 2+-
Mxr/httpbuffer/replaceheader2.cc | 5++++-
Mxr/ipstore/activity.cc | 8++++----
Mxr/ipstore/anticipated.cc | 8++++----
Mxr/ipstore/clear.cc | 7+++----
Mxr/ipstore/clearoldest.cc | 10+++++-----
Mxr/ipstore/dump.cc | 6+++---
Mxr/ipstore/target.cc | 8++++----
Mxr/ipstore/weed.cc | 9++++-----
Mxr/memory/memdisplay.cc | 8++++----
Mxr/memory/memfree.cc | 12++++++------
Mxr/memory/memmalloc.cc | 8++++----
Mxr/memory/memmark.cc | 4++--
Mxr/memory/memrealloc.cc | 8++++----
Dxr/mstr/mstr | 57---------------------------------------------------------
Mxr/netbuffer/checkspace.cc | 8++++----
Mxr/netbuffer/destroy.cc | 3+--
Mxr/netbuffer/insertat.cc | 9+++++++--
Mxr/netbuffer/netbuffer | 4++--
Mxr/netbuffer/netbuffer1.cc | 2+-
Mxr/netbuffer/netread.cc | 9++++-----
Mxr/netbuffer/netwrite.cc | 17++++++++---------
Mxr/netbuffer/opassign.cc | 2+-
Mxr/netbuffer/setstring.cc | 2+-
Dxr/sys/anymsg.cc | 17-----------------
Dxr/sys/debugmsg.cc | 11-----------
Axr/sys/inet2string.cc | 12++++++++++++
Mxr/sys/ipmatch.cc | 6+++---
Mxr/sys/main.cc | 4++--
Dxr/sys/msg.cc | 11-----------
Mxr/sys/mtrand.cc | 22+++++++++++++---------
Axr/sys/mutexlock.cc | 28++++++++++++++++++++++++++++
Dxr/sys/reportmsg.cc | 9---------
Mxr/sys/socketclose.cc | 2+-
Mxr/sys/sys | 63+++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mxr/sys/sysrun.cc | 15+++++++--------
Dxr/sys/warnmsg.cc | 9---------
Mxr/webinterface/answer.cc | 6+++---
Mxr/webinterface/answerstatus.cc | 6+++---
Mxr/webinterface/execute.cc | 15+++++++--------
Mxr/webinterface/serve.cc | 4++--
Mxr/webinterface/webinterface1.cc | 2+-
Mxrctl/xrctl | 5+++++
139 files changed, 1485 insertions(+), 545 deletions(-)

diff --git a/ChangeLog b/ChangeLog @@ -1,3 +1,20 @@ +2.68 [KK 2010-09-22] +- All sources checked by cppcheck (static code analysis). +- License file added. +- Bugfix in xrctl.xml parsing, logger and other binaries can be + now specified as absolutes. +- Mutex handling rewritten, new code is faster than the older one and + hopefully more thread-safe in rare conditions (fingers crossed ;-) +- Macros for verbose/debug output rewritten for type-safeness. Locking + of cout/cerr is in try-out mode only, so that mutex locks due to + messages won't happen. +- All occurrences of inet_ntoa() changed to inet2string() (see + sys/inet2string.cc) for thread-safeness. +- Double header-processing in HTTP mode fixed. Thanks for reporting, + Maxim P. and Chin F. +- Optimisation / consistency fix in Httpbuffer::findheader(), thanks + Maxim P. for finding this and reporting. + 2.67 [KK 2010-06-11] - Further bugfix in xrctl to shell-escape all XR parameters where necessary (including e.g. url matching regexps etc.). diff --git a/LICENSE b/LICENSE @@ -0,0 +1,606 @@ +GNU GENERAL PUBLIC LICENSE + +Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +Preamble + +The GNU General Public License is a free, copyleft license for +software and other kinds of works. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom +to share and change all versions of a program--to make sure it remains +free software for all its users. We, the Free Software Foundation, use +the GNU General Public License for most of our software; it applies +also to any other work released this way by its authors. You can apply +it to your programs, too. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you +have certain responsibilities if you distribute copies of the +software, or if you modify it: responsibilities to respect the freedom +of others. + +For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + +Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + +Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the +manufacturer can do so. This is fundamentally incompatible with the +aim of protecting users' freedom to change the software. The +systematic pattern of such abuse occurs in the area of products for +individuals to use, which is precisely where it is most unacceptable. +Therefore, we have designed this version of the GPL to prohibit the +practice for those products. If such problems arise substantially in +other domains, we stand ready to extend this provision to those +domains in future versions of the GPL, as needed to protect the +freedom of users. + +Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish +to avoid the special danger that patents applied to a free program +could make it effectively proprietary. To prevent this, the GPL +assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and +modification follow. + +TERMS AND CONDITIONS + +0. Definitions. + +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds +of works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this +License. Each licensee is addressed as “you”. “Licensees” and +“recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of +an exact copy. The resulting work is called a “modified version” of +the earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based +on the Program. + +To “propagate” a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user +through a computer network, with no transfer of a copy, is not +conveying. + +An interactive user interface displays “Appropriate Legal Notices” to +the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +1. Source Code. + +The “source code” for a work means the preferred form of the work for +making modifications to it. “Object code” means any non-source form of +a work. + +A “Standard Interface” means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +“Major Component”, in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can +regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same +work. + +2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, +without conditions so long as your license otherwise remains in force. +You may convey covered works to others for the sole purpose of having +them make modifications exclusively for you, or provide you with +facilities for running those works, provided that you comply with the +terms of this License in conveying all material for which you do not +control copyright. Those thus making or running the covered works for +you must do so exclusively on your behalf, under your direction and +control, on terms that prohibit them from making any copies of your +copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes +it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such +circumvention is effected by exercising rights under this License with +respect to the covered work, and you disclaim any intention to limit +operation or modification of the work as a means of enforcing, against +the work's users, your or third parties' legal rights to forbid +circumvention of technological measures. + +4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these +conditions: + +a) The work must carry prominent notices stating that you modified it, +and giving a relevant date. b) The work must carry prominent notices +stating that it is released under this License and any conditions +added under section 7. This requirement modifies the requirement in +section 4 to “keep intact all notices”. c) You must license the entire +work, as a whole, under this License to anyone who comes into +possession of a copy. This License will therefore apply, along with +any applicable section 7 additional terms, to the whole of the work, +and all its parts, regardless of how they are packaged. This License +gives no permission to license the work in any other way, but it does +not invalidate such permission if you have separately received it. d) +If the work has interactive user interfaces, each must display +Appropriate Legal Notices; however, if the Program has interactive +interfaces that do not display Appropriate Legal Notices, your work +need not make them do so. A compilation of a covered work with other +separate and independent works, which are not by their nature +extensions of the covered work, and which are not combined with it +such as to form a larger program, in or on a volume of a storage or +distribution medium, is called an “aggregate” if the compilation and +its resulting copyright are not used to limit the access or legal +rights of the compilation's users beyond what the individual works +permit. Inclusion of a covered work in an aggregate does not cause +this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of +sections 4 and 5, provided that you also convey the machine-readable +Corresponding Source under the terms of this License, in one of these +ways: + +a) Convey the object code in, or embodied in, a physical product +(including a physical distribution medium), accompanied by the +Corresponding Source fixed on a durable physical medium customarily +used for software interchange. b) Convey the object code in, or +embodied in, a physical product (including a physical distribution +medium), accompanied by a written offer, valid for at least three +years and valid for as long as you offer spare parts or customer +support for that product model, to give anyone who possesses the +object code either (1) a copy of the Corresponding Source for all the +software in the product that is covered by this License, on a durable +physical medium customarily used for software interchange, for a price +no more than your reasonable cost of physically performing this +conveying of source, or (2) access to copy the Corresponding Source +from a network server at no charge. c) Convey individual copies of the +object code with a copy of the written offer to provide the +Corresponding Source. This alternative is allowed only occasionally +and noncommercially, and only if you received the object code with +such an offer, in accord with subsection 6b. d) Convey the object code +by offering access from a designated place (gratis or for a charge), +and offer equivalent access to the Corresponding Source in the same +way through the same place at no further charge. You need not require +recipients to copy the Corresponding Source along with the object +code. If the place to copy the object code is a network server, the +Corresponding Source may be on a different server (operated by you or +a third party) that supports equivalent copying facilities, provided +you maintain clear directions next to the object code saying where to +find the Corresponding Source. Regardless of what server hosts the +Corresponding Source, you remain obligated to ensure that it is +available for as long as needed to satisfy these requirements. e) +Convey the object code using peer-to-peer transmission, provided you +inform other peers where the object code and Corresponding Source of +the work are being offered to the general public at no charge under +subsection 6d. A separable portion of the object code, whose source +code is excluded from the Corresponding Source as a System Library, +need not be included in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any +tangible personal property which is normally used for personal, +family, or household purposes, or (2) anything designed or sold for +incorporation into a dwelling. In determining whether a product is a +consumer product, doubtful cases shall be resolved in favor of +coverage. For a particular product received by a particular user, +“normally used” refers to a typical or common use of that class of +product, regardless of the status of the particular user or of the way +in which the particular user actually uses, or expects or is expected +to use, the product. A product is a consumer product regardless of +whether the product has substantial commercial, industrial or +non-consumer uses, unless such uses represent the only significant +mode of use of the product. + +“Installation Information” for a User Product means any methods, +procedures, authorization keys, or other information required to +install and execute modified versions of a covered work in that User +Product from a modified version of its Corresponding Source. The +information must suffice to ensure that the continued functioning of +the modified object code is in no case prevented or interfered with +solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or +updates for a work that has been modified or installed by the +recipient, or for the User Product in which it has been modified or +installed. Access to a network may be denied when the modification +itself materially and adversely affects the operation of the network +or violates the rules and protocols for communication across the +network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +7. Additional Terms. + +“Additional permissions” are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders +of that material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the +terms of sections 15 and 16 of this License; or b) Requiring +preservation of specified reasonable legal notices or author +attributions in that material or in the Appropriate Legal Notices +displayed by works containing it; or c) Prohibiting misrepresentation +of the origin of that material, or requiring that modified versions of +such material be marked in reasonable ways as different from the +original version; or d) Limiting the use for publicity purposes of +names of licensors or authors of the material; or e) Declining to +grant rights under trademark law for use of some trade names, +trademarks, or service marks; or f) Requiring indemnification of +licensors and authors of that material by anyone who conveys the +material (or modified versions of it) with contractual assumptions of +liability to the recipient, for any liability that these contractual +assumptions directly impose on those licensors and authors. All other +non-permissive additional terms are considered “further restrictions” +within the meaning of section 10. If the Program as you received it, +or any part of it, contains a notice stating that it is governed by +this License along with a term that is a further restriction, you may +remove that term. If a license document contains a further restriction +but permits relicensing or conveying under this License, you may add +to a covered work material governed by the terms of that license +document, provided that the further restriction does not survive such +relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; the +above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your license +from a particular copyright holder is reinstated (a) provisionally, +unless and until the copyright holder explicitly and finally +terminates your license, and (b) permanently, if the copyright holder +fails to notify you of the violation by some reasonable means prior to +60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run +a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +11. Patents. + +A “contributor” is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned +or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, “control” includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To “grant” such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. “Knowingly relying” means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is “discriminatory” if it does not include within the +scope of its coverage, prohibits the exercise of, or is conditioned on +the non-exercise of one or more of the rights that are specifically +granted under this License. You may not convey a covered work if you +are a party to an arrangement with a third party that is in the +business of distributing software, under which you make payment to the +third party based on the extent of your activity of conveying the +work, and under which the third party grants, to any of the parties +who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by +you (or copies made from those copies), or (b) primarily for and in +connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under +this License and any other pertinent obligations, then as a +consequence you may not convey it at all. For example, if you agree to +terms that obligate you to collect a royalty for further conveying +from those to whom you convey the Program, the only way you could +satisfy both those terms and this License would be to refrain entirely +from conveying the Program. + +13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions +of the GNU General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in +detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies that a certain numbered version of the GNU General Public +License “or any later version” applies to it, you have the option of +following the terms and conditions either of that numbered version or +of any later version published by the Free Software Foundation. If the +Program does not specify a version number of the GNU General Public +License, you may choose any version ever published by the Free +Software Foundation. + +If the Program specifies that a proxy can decide which future versions +of the GNU General Public License can be used, that proxy's public +statement of acceptance of a version permanently authorizes you to +choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT +WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND +PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR +CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT +NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR +LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM +TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER +PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS +\ No newline at end of file diff --git a/Makefile b/Makefile @@ -1,7 +1,7 @@ # Top-level Makefile for XR # ------------------------- -VER = 2.67 +VER = 2.68 PREFIX = $(DESTDIR)/usr BINDIR = $(PREFIX)/sbin MANDIR = $(PREFIX)/share/man diff --git a/xr/DispatchAlgorithms/external/target.cc b/xr/DispatchAlgorithms/external/target.cc @@ -10,19 +10,21 @@ unsigned External::target(struct in_addr clientip, o << ' ' << balancer.backend(i).description() << ' ' << balancer.backend(i).availablestr() << ' ' << balancer.backend(i).connections(); - msg ("External algorithm: invoking '" + o.str() + "'\n"); + msg("External algorithm: invoking '" << o.str() << '\n'); FILE *f; if (! (f = popen (o.str().c_str(), "r")) ) throw Error("Cannot start '" + o.str() + ": " + strerror(errno)); unsigned i; - if (fscanf (f, "%u", &i) < 1) + if (fscanf (f, "%u", &i) < 1) { + pclose(f); throw Error("External algorithm '" + o.str() + "' did not reply with a number"); - - msg ((Mstr("External algorithm says:) ") + i) + "\n"); + } + msg("External algorithm says: " << i << '\n'); if (i >= balancer.nbackends()) { + pclose(f); ostringstream o; o << "External algorithm '" << o.str() << "': answer " << i << " out of bounds"; diff --git a/xr/DispatchAlgorithms/hashedip/target.cc b/xr/DispatchAlgorithms/hashedip/target.cc @@ -17,10 +17,8 @@ unsigned HashedIp::target(struct in_addr clientip, } unsigned index = targetlist[h]; - msg ((Mstr("Client IP ") + static_cast<string>(inet_ntoa(clientip))) + - (Mstr(" hashes to ") + index) + - ", back end " + balancer.backend(index).description() + - "\n"); + msg("Client IP "<< inet2string(clientip) << " hashes to " << index << + ", back end " << balancer.backend(index).description() << '\n'); // In strict mode, back end must be available, or don't proceed // In lax mode, fall back to least-connections dispatching @@ -30,9 +28,9 @@ unsigned HashedIp::target(struct in_addr clientip, balancer.backend(index).description() + " unavailable"); else { - msg ("Hashed-IP algorithm: target back end " + - balancer.backend(index).description() + " unavailable, " - "falling back to least-connections\n"); + msg("Hashed-IP algorithm: target back end " << + balancer.backend(index).description() << " unavailable, " + << "falling back to least-connections\n"); Leastconn l; index = l.target(clientip, targetlist); } diff --git a/xr/DispatchAlgorithms/leastconn/target.cc b/xr/DispatchAlgorithms/leastconn/target.cc @@ -4,7 +4,7 @@ unsigned Leastconn::target(struct in_addr clientip, BackendVector const &targetlist) { PROFILE("Leastconn::target"); - msg (Mstr("Starting least-connections dispatcher\n")); + msg("Starting least-connections dispatcher\n"); if (config.debug()) { ostringstream o; @@ -12,7 +12,7 @@ unsigned Leastconn::target(struct in_addr clientip, for (unsigned i = 0; i < targetlist.size(); i++) o << ' ' << targetlist[i]; o << '\n'; - _debugmsg(o.str()); + debugmsg(o.str()); } bool found = false; @@ -20,8 +20,8 @@ unsigned Leastconn::target(struct in_addr clientip, for (unsigned i = 0; i < targetlist.size(); i++) { if (! balancer.backend(targetlist[i]).available()) { - debugmsg(Mstr("Back end ") + - Mstr(balancer.backend(targetlist[i]).description()) + + debugmsg("Back end " << + balancer.backend(targetlist[i]).description() << " is NOT available\n"); continue; } @@ -33,16 +33,18 @@ unsigned Leastconn::target(struct in_addr clientip, if (config.debug()) o << "Back end " << balancer.backend(targetlist[i]).description() - << ": connections=" << connections << ", anticipated=" << anticipated - << ", adjweight=" << adjweight << ", thisweight=" << this_weight; + << ": connections=" << connections + << ", anticipated=" << anticipated + << ", adjweight=" << adjweight + << ", thisweight=" << this_weight; if (!found || this_weight < best_weighted) { t = targetlist[i]; best_weighted = this_weight; found = true; - debugmsg(Mstr(o.str()) + Mstr(" is best so far\n")); + debugmsg(o.str() << " is best so far\n"); } else - debugmsg(Mstr(o.str()) + Mstr(" skipped, got a better one\n")); + debugmsg(o.str() << " skipped, got a better one\n"); } if (!found) diff --git a/xr/DispatchAlgorithms/roundrobin/target.cc b/xr/DispatchAlgorithms/roundrobin/target.cc @@ -9,9 +9,8 @@ unsigned Roundrobin::target(struct in_addr clientip, if (config.debug()) for (unsigned i = 0; i < targetlist.size(); i++) { unsigned backend_index = targetlist[i]; - _debugmsg(Mstr("Round robin dispatcher: target ") + - Mstr(i) + Mstr(" is ") + - balancer.backend(backend_index).description() + "\n"); + debugmsg("Round robin dispatcher: target " << i << " is " << + balancer.backend(backend_index).description() << '\n'); } if (targetlist.size() == 1) @@ -39,9 +38,9 @@ unsigned Roundrobin::target(struct in_addr clientip, } // Store for next time 'round - lock (&prev_run_index); + mutex_lock(&prev_run_index); prev_run_index = cur_val; - unlock (&prev_run_index); + mutex_unlock(&prev_run_index); if (! balancer.backend(targetlist[cur_val]).available()) continue; diff --git a/xr/DispatchAlgorithms/storedip/target.cc b/xr/DispatchAlgorithms/storedip/target.cc @@ -5,7 +5,7 @@ unsigned StoredIp::target(struct in_addr clientip, PROFILE("StoredIP::target"); IPStore::on(); - msg(Mstr("Starting stored-ip dispatcher\n")); + msg("Starting stored-ip dispatcher\n"); int tb; if ( (tb = IPStore::target(clientip)) >= 0 ) { @@ -13,12 +13,12 @@ unsigned StoredIp::target(struct in_addr clientip, IPStore::clear(clientip); if (balancer.backend(target).available()) { // Historical target is up, go there! - msg(Mstr("Sending ") + Mstr(inet_ntoa(clientip)) + " to " + - balancer.backend(target).description() + "\n"); + msg("Sending " << inet2string(clientip) << " to " << + balancer.backend(target).description() << '\n'); return target; } - msg (Mstr("Historical target ") + - balancer.backend(target).description() + " unavailable\n"); + msg ("Historical target " << + balancer.backend(target).description() << " unavailable\n"); if (config.dispatchmode() == Dispatchmode::m_strict_stored_ip) throw Error("Stored-IP algorithm: target back end " + balancer.backend(target).description() + @@ -38,10 +38,12 @@ unsigned StoredIp::target(struct in_addr clientip, try { return l.target(clientip, tlist); } catch (...) { - // We're out of back ends and need to clear up the IP store to retry. + // We're out of back ends and need to clear up the IP store + // to retry. // We give it a sec, remove the oldest entry, and rebuild the // target list for the least-connections dispatch algorithm. - warnmsg("Out of back ends, releasing oldest client entry and retrying\n"); + warnmsg("Out of back ends, releasing oldest client entry " + "and retrying\n"); IPStore::clearoldest(); sleep(1); BackendVector newlist; diff --git a/xr/DispatchAlgorithms/weightedload/target.cc b/xr/DispatchAlgorithms/weightedload/target.cc @@ -15,9 +15,8 @@ unsigned Weightedload::target(struct in_addr clientip, // 4294967295 = 2^32 - 1 double pick_load = total_load * mt_rand() * (1.0 / 4294967295.0); - msg ((Mstr("Weighted by Load Average; load-range is ") + total_load) + - (Mstr(", and the selected load-range is ") + pick_load) + - "\n"); + msg ("Weighted by Load Average; load-range is " << total_load << + ", and the selected load-range is " << pick_load << '\n'); // Now see which server that means! total_load = 0; diff --git a/xr/Dispatchers/dispatcher/checkdos.cc b/xr/Dispatchers/dispatcher/checkdos.cc @@ -8,17 +8,17 @@ static time_t accesslog_lastclean = 0; static void run_excess(string const &prog, char const *ip) { ostringstream o; o << prog << ' ' << ip; - msg ((Mstr("Max connection rate exceeded, invoking '") + o.str()) + - "'\n"); + msg("Max connection rate exceeded, invoking '" << o.str() << '\n'); int ret = sysrun(o.str()); - if (ret == -1) + if (ret == -1) { throw Error(string("Failed to start system call: ") + strerror(errno)); - else if (ret) - warnmsg((Mstr("Program '") + o.str()) + - (Mstr("' exited with exit status ") + ret) + "\n"); - else - msg((Mstr("Program '") + o.str()) + "' finished.\n"); + } else if (ret) { + warnmsg("Program '" << o.str() << + "' exited with exit status " << ret << '\n'); + } else { + msg("Program '" << o.str() << "' finished.\n"); + } } bool Dispatcher::check_dos() { @@ -38,43 +38,50 @@ bool Dispatcher::check_dos() { unsigned max_conns = max(config.hardmaxconnrate(), config.softmaxconnrate()); - Mutex::lock (&accesslog[clientip().s_addr]); + mutex_lock (&accesslog[clientip().s_addr]); accesslog[clientip().s_addr].push(now); - Mutex::unlock (&accesslog[clientip().s_addr]); + mutex_unlock (&accesslog[clientip().s_addr]); if (accesslog_lastclean < min_ts) { // Clean the entire access log, it's been a while... - Mutex::lock(&accesslog_lastclean); + mutex_lock(&accesslog_lastclean); accesslog_lastclean = now; - Mutex::unlock(&accesslog_lastclean); + mutex_unlock(&accesslog_lastclean); - for (AccessMap::iterator i = accesslog.begin(); - i != accesslog.end(); - i++ ) { - if (accesslog[i->first].back() < min_ts) { - // This IP hasn't made ANY connections in a while -- erase! - accesslog.erase(i); - } else { - // Keep popping off this IP's oldest connection until we - // have only "recent" connections left. - Mutex::lock(&accesslog[i->first]); - while ( accesslog[i->first].front() < min_ts - || accesslog[i->first].size() > max_conns ) { - accesslog[i->first].pop(); + bool done = false; + while (!done) { + done = true; + for (AccessMap::iterator i = accesslog.begin(); + i != accesslog.end(); + i++ ) { + if (accesslog[i->first].back() < min_ts) { + // This IP hasn't made ANY connections in a while + // -- erase! Also restart loop, i++ won't be valid + // after erase(i) + accesslog.erase(i); + done = false; + break; + } else { + // Keep popping off this IP's oldest connection + // until we have only "recent" connections left. + mutex_lock(&accesslog[i->first]); + while ( accesslog[i->first].front() < min_ts + || accesslog[i->first].size() > max_conns ) + accesslog[i->first].pop(); + mutex_unlock(&accesslog[i->first]); } - Mutex::unlock(&accesslog[i->first]); - } + } } } else { // The "big log" doesn't need to be fully cleaned, // but this particular IP should be! - Mutex::lock(&accesslog[clientip().s_addr]); + mutex_lock(&accesslog[clientip().s_addr]); while ( accesslog[clientip().s_addr].front() < min_ts || accesslog[clientip().s_addr].size() > max_conns ) { accesslog[clientip().s_addr].pop(); } - Mutex::unlock(&accesslog[clientip().s_addr]); + mutex_unlock(&accesslog[clientip().s_addr]); } if (config.hardmaxconnrate() && diff --git a/xr/Dispatchers/dispatcher/clientipstr.cc b/xr/Dispatchers/dispatcher/clientipstr.cc @@ -1,10 +1,7 @@ #include "dispatcher" string const &Dispatcher::clientipstr() { - if (clientip_str == "") { - Mutex::lock( (void*)inet_ntoa ); - clientip_str = inet_ntoa(clientip()); - Mutex::unlock( (void*)inet_ntoa ); - } + if (clientip_str == "") + clientip_str = inet2string(clientip()); return clientip_str; } diff --git a/xr/Dispatchers/httpdispatcher/handle.cc b/xr/Dispatchers/httpdispatcher/handle.cc @@ -15,7 +15,7 @@ void HttpDispatcher::handle() { // Patch up the Host: header if requested so. if (config.replacehostheader()) buf().replaceheader("Host:", - balancer.backend(targetbackend()).server()); + balancer.backend(targetbackend()).server()); // Flush client info received so far to the back end. debugmsg("Sending client request to back end\n"); @@ -74,9 +74,9 @@ void HttpDispatcher::handle() { sock == backendfd() && buf().headersreceived()) { string respcode = buf().stringat(9, 3); if (respcode[0] == '4' || respcode[0] == '5') - warnmsg("HTTP back end indicates fault: '" + - buf().firstline() + "' as response to '" + - client_request + "'\n"); + warnmsg("HTTP back end indicates fault: '" << + buf().firstline() << "' as response to '" << + client_request << "'\n"); backend_response_checked = true; } @@ -87,15 +87,15 @@ void HttpDispatcher::handle() { timeout = config.backend_read_timeout(); // Re-patch Host header if requested if (config.replacehostheader()) - buf().replaceheader("Host:", - balancer.backend(targetbackend()).server()); + buf().replaceheader("Host:", + balancer.backend(targetbackend()).server()); } else { othersock = clientfd(); timeout = config.client_read_timeout(); } - debugmsg (Mstr("Had data on ") + sock + - (Mstr(", sending to ") + othersock) + "\n"); + debugmsg ("Had data on " << sock << ", sending to " << othersock + << '\n'); buf().netwrite(othersock, timeout); if (sock == backendfd()) diff --git a/xr/Dispatchers/httpdispatcher/senderrorpage.cc b/xr/Dispatchers/httpdispatcher/senderrorpage.cc @@ -3,7 +3,7 @@ void HttpDispatcher::senderrorpage(string const &reason) { PROFILE("HttpDispatcher::senderrorpage"); - msg ("Sending error page to client: '" + reason + "'\n"); + msg("Sending error page to client: '" << reason << "'\n"); try { string txt = "<html>\n" @@ -27,6 +27,6 @@ void HttpDispatcher::senderrorpage(string const &reason) { } catch (Error const &e) { // Silently discard, we are not interested in errors // that ocur when an error page is being sent - msg (Mstr(e.what()) + Mstr(" (while sending error page)\n")); + msg (e.what() << " (while sending error page)\n"); } } diff --git a/xr/Dispatchers/tcpdispatcher/dispatch.cc b/xr/Dispatchers/tcpdispatcher/dispatch.cc @@ -12,13 +12,13 @@ void TcpDispatcher::dispatch() { // might've created it already for host-based matching (in which case // we won't bother here). if (! targetlist().isdefined()) { - msg ("Creating target list for the TCP dispatcher\n"); + msg("Creating target list for the TCP dispatcher\n"); for (unsigned i = 0; i < balancer.nbackends(); i++) if (balancer.backend(i).available()) { targetlist().add(i); if (config.verbose()) - msg (" Candidate target: " + - balancer.backend(i).description() + "\n"); + msg(" Candidate target: " << + balancer.backend(i).description() << '\n'); } } @@ -30,14 +30,13 @@ void TcpDispatcher::dispatch() { if (!tb.connect()) { balancer.backend(targetbackend()).live(false); if (config.verbose()) - msg ("Failed to connect to back end " + tb.description() + - ", trying to dispatch to other\n"); + msg("Failed to connect to back end " << tb.description() << + ", trying to dispatch to other\n"); } else { connected = true; backendfd(tb.sock()); - msg ((Mstr("Will dispatch client to back end ") + - tb.description()) + - (Mstr(" on fd ") + tb.sock()) + "\n"); + msg ("Will dispatch client to back end " << tb.description() << + " on fd " << tb.sock() << '\n'); break; } } diff --git a/xr/Dispatchers/tcpdispatcher/execute.cc b/xr/Dispatchers/tcpdispatcher/execute.cc @@ -8,16 +8,16 @@ void TcpDispatcher::execute() { !check_acl()) return; - msg ((Mstr("Dispatch request for client fd ") + clientfd()) + "\n"); + msg("Dispatch request for client fd " << clientfd() << '\n'); // Try to determine the back end. try { Threadlist::desc("Dispatching"); dispatch(); } catch (Error const &e) { - Mutex::lock(&cerr); + mutex_lock(&cerr); cerr << e.what() << "\n"; - Mutex::unlock(&cerr); + mutex_unlock(&cerr); socketclose(clientfd()); socketclose(backendfd()); return; @@ -33,10 +33,9 @@ void TcpDispatcher::execute() { } // Dispatch! - msg ((Mstr("Dispatching client fd ") + clientfd()) + - (Mstr(" to ") + balancer.backend(targetbackend()).description()) + - (Mstr(", fd ") + backendfd()) + "\n"); - + msg ("Dispatching client fd " << clientfd() << " to " << + balancer.backend(targetbackend()).description() << ", fd " << + backendfd() << '\n'); Threadlist::desc("Serving"); Threadlist::backend(targetbackend()); @@ -48,7 +47,7 @@ void TcpDispatcher::execute() { o << config.onstart() << ' ' << clientipstr() << ' ' << balancer.backend(targetbackend()).description() << ' ' << balancer.backend(targetbackend()).connections(); - msg (Mstr("Running onstart script: ") + o.str() + "\n"); + msg("Running onstart script: " << o.str() << '\n'); sysrun(o.str()); } @@ -56,16 +55,16 @@ void TcpDispatcher::execute() { try { handle(); } catch (Error const &e) { - Mutex::lock(&cerr); + mutex_lock(&cerr); cerr << e.what() << "\n"; - Mutex::unlock(&cerr); + mutex_unlock(&cerr); failed = true; if (config.onfail().length()) { ostringstream o; o << config.onfail() << ' ' << clientipstr() << ' ' << balancer.backend(targetbackend()).description() << ' ' << balancer.backend(targetbackend()).connections(); - msg(Mstr("Running onfail script: ") + o.str() + "\n"); + msg("Running onfail script: " << o.str() << '\n'); sysrun(o.str()); } } @@ -79,11 +78,10 @@ void TcpDispatcher::execute() { o << config.onend() << ' ' << clientipstr() << ' ' << balancer.backend(targetbackend()).description() << ' ' << balancer.backend(targetbackend()).connections(); - msg (Mstr("Running onend script: ") + o.str() + "\n"); + msg("Running onend script: " << o.str() << '\n'); sysrun(o.str()); } - msg ((Mstr("Done dispatching to back end fd ") + backendfd()) + - (Mstr(" at ") + balancer.backend(targetbackend()).description()) + - "\n"); + msg ("Done dispatching to back end fd " << backendfd() << " at " << + balancer.backend(targetbackend()).description() << '\n'); } diff --git a/xr/Dispatchers/tcpdispatcher/handle.cc b/xr/Dispatchers/tcpdispatcher/handle.cc @@ -2,9 +2,8 @@ void TcpDispatcher::handle() { - debugmsg (Mstr("TCP dispatcher: About to shuttle between client fd ") + - clientfd() + - (Mstr(" and backend fd ") + backendfd()) + "\n"); + debugmsg("TCP dispatcher: About to shuttle between client fd " << + clientfd() << " and backend fd " << backendfd() << '\n'); while (1) { Fdset readset(maxtimeout(config.client_read_timeout(), @@ -27,8 +26,8 @@ void TcpDispatcher::handle() { if (!netbuffer.netread(sock)) break; - debugmsg (Mstr("Had data on ") + sock + - (Mstr(", sending to ") + othersock) + "\n"); + debugmsg("Had data on " << sock << ", sending to " << othersock << + '\n'); netbuffer.netwrite (othersock, timeout); if (sock == backendfd()) balancer.backend(targetbackend()).addbytes(netbuffer.bufsz()); diff --git a/xr/ThreadsAndMutexes/mutex/lock.cc b/xr/ThreadsAndMutexes/mutex/lock.cc @@ -1,12 +1,8 @@ #include "mutex" #include "profiler/profiler" -std::map<void *, pthread_mutex_t> Mutex::s_lock; - -void Mutex::lock (void *target) { - PROFILE("Mutex::lock"); - - plock(&s_lock); - plock(target); - unlock(&s_lock); +void Mutex::lock() { + if (pthread_mutex_lock(&_mutex)) + throw Error("Failed to lock mutex"); } + diff --git a/xr/ThreadsAndMutexes/mutex/mutex b/xr/ThreadsAndMutexes/mutex/mutex @@ -2,18 +2,17 @@ #define _MUTEX_ #include "sys/sys" +#include "error/error" class Mutex { public: - static void lock (void *target); - static void unlock (void *target); - + Mutex(); + void lock(); + void unlock(); + bool trylock(); + pthread_mutex_t mutex() const { return _mutex; } private: - static void plock (void *target); - static std::map<void *, pthread_mutex_t> s_lock; - typedef std::map<void *, pthread_mutex_t>::iterator mapIterator; + pthread_mutex_t _mutex; }; - - #endif diff --git a/xr/ThreadsAndMutexes/mutex/mutex1.cc b/xr/ThreadsAndMutexes/mutex/mutex1.cc @@ -0,0 +1,6 @@ +#include "mutex" + +Mutex::Mutex() { + if (pthread_mutex_init(&_mutex, 0)) + throw Error("Failed to initialize mutex"); +} diff --git a/xr/ThreadsAndMutexes/mutex/plock.cc b/xr/ThreadsAndMutexes/mutex/plock.cc @@ -1,17 +0,0 @@ -#include "mutex" -#include "error/error" - -void Mutex::plock(void *target) { - mapIterator iter = s_lock.find(target); - if (iter == s_lock.end()) { - // No such lock yet, create the mutex - if (int res = pthread_mutex_init(&s_lock[target], 0)) - throw Error(string("Failed to initialize static mutex: ") + - strerror(res)); - } - - if (int res = pthread_mutex_lock(&s_lock[target])) - throw Error(string("Failed to obtain mutex lock: ") + - strerror(res)); -} - diff --git a/xr/ThreadsAndMutexes/mutex/trylock.cc b/xr/ThreadsAndMutexes/mutex/trylock.cc @@ -0,0 +1,10 @@ +#include "mutex" +#include "profiler/profiler" + +bool Mutex::trylock() { + int res = pthread_mutex_trylock(&_mutex); + if (res && res != EBUSY) + throw Error("Failed to try to lock mutex"); + return res == 0; +} + diff --git a/xr/ThreadsAndMutexes/mutex/unlock.cc b/xr/ThreadsAndMutexes/mutex/unlock.cc @@ -2,10 +2,7 @@ #include "error/error" #include "profiler/profiler" -void Mutex::unlock(void *target) { - PROFILE("Mutex::unlock"); - - if (int res = pthread_mutex_unlock(&s_lock[target])) - throw Error(string("Failed to release mutex lock: ") + - strerror(res)); +void Mutex::unlock() { + if (pthread_mutex_unlock(&_mutex)) + throw Error("Failed to unlock mutex"); } diff --git a/xr/ThreadsAndMutexes/mutexnode/balance.cc b/xr/ThreadsAndMutexes/mutexnode/balance.cc @@ -0,0 +1,7 @@ +#include "mutexnode" + +int MutexNode::balance() const { + int lw = left() ? left()->weight() : 0; + int rw = right() ? right()->weight() : 0; + return lw - rw; +} diff --git a/xr/ThreadsAndMutexes/mutexnode/copy.cc b/xr/ThreadsAndMutexes/mutexnode/copy.cc @@ -0,0 +1,8 @@ +#include "mutexnode" + +void MutexNode::copy(MutexNode const &other) { + mutex(other.mutex()); + obj(other.obj()); + left(other.left() ? new MutexNode(*(other.left())) : 0); + right(other.right() ? new MutexNode(*(other.right())) : 0); +} diff --git a/xr/ThreadsAndMutexes/mutexnode/destroy.cc b/xr/ThreadsAndMutexes/mutexnode/destroy.cc @@ -0,0 +1,6 @@ +#include "mutexnode" + +void MutexNode::destroy() { + delete _left; + delete _right; +} diff --git a/xr/ThreadsAndMutexes/mutexnode/mutexnode b/xr/ThreadsAndMutexes/mutexnode/mutexnode @@ -0,0 +1,42 @@ +#ifndef _MUTEXNODE_ +#define _MUTEXNODE_ + +#include "ThreadsAndMutexes/mutex/mutex" +#include "error/error" + +class MutexNode { +public: + MutexNode(void *o); + MutexNode(MutexNode const &other); + ~MutexNode(); + + MutexNode const &operator=(MutexNode const &other); + + void obj(void *o) { _obj = o; } + void *obj() const { return _obj; } + + MutexNode *left(MutexNode *l) { _left = l; return _left;} + MutexNode *left() const { return _left; } + + MutexNode *right(MutexNode *r) { _right = r; return _right; } + MutexNode *right() const { return _right; } + + void lock() { _mutex.lock(); } + void unlock() { _mutex.unlock(); } + + Mutex mutex() const { return _mutex; } + void mutex(Mutex m) { _mutex = m; } + + int weight() const; + int balance() const; + +private: + void copy(MutexNode const &other); + void destroy(); + + Mutex _mutex; + void *_obj; + MutexNode *_left, *_right; +}; + +#endif diff --git a/xr/ThreadsAndMutexes/mutexnode/mutexnode1.cc b/xr/ThreadsAndMutexes/mutexnode/mutexnode1.cc @@ -0,0 +1,5 @@ +#include "mutexnode" + +MutexNode::MutexNode(void *o): _mutex(), _obj(o), _left(0), _right(0) { +} + diff --git a/xr/ThreadsAndMutexes/mutexnode/mutexnode2.cc b/xr/ThreadsAndMutexes/mutexnode/mutexnode2.cc @@ -0,0 +1,5 @@ +#include "mutexnode" + +MutexNode::MutexNode(MutexNode const &other) { + copy(other); +} diff --git a/xr/ThreadsAndMutexes/mutexnode/mutexnode3.cc b/xr/ThreadsAndMutexes/mutexnode/mutexnode3.cc @@ -0,0 +1,5 @@ +#include "mutexnode" + +MutexNode::~MutexNode() { + destroy(); +} diff --git a/xr/ThreadsAndMutexes/mutexnode/opis.cc b/xr/ThreadsAndMutexes/mutexnode/opis.cc @@ -0,0 +1,9 @@ +#include "mutexnode" + +MutexNode const &MutexNode::operator=(MutexNode const &other) { + if (this != &other) { + destroy(); + copy(other); + } + return *this; +} diff --git a/xr/ThreadsAndMutexes/mutexnode/weight.cc b/xr/ThreadsAndMutexes/mutexnode/weight.cc @@ -0,0 +1,10 @@ +#include "mutexnode" + +int MutexNode::weight() const { + int w = 1; + if (left()) + w += left()->weight(); + if (right()) + w += right()->weight(); + return w; +} diff --git a/xr/ThreadsAndMutexes/mutextable/balance.cc b/xr/ThreadsAndMutexes/mutextable/balance.cc @@ -0,0 +1,5 @@ +#include "mutextable" + +int MutexTable::balance(unsigned i) const { + return i < size() ? _table[i]->weight() : 0; +} diff --git a/xr/ThreadsAndMutexes/mutextable/copy.cc b/xr/ThreadsAndMutexes/mutextable/copy.cc @@ -0,0 +1,8 @@ +#include "mutextable" + +void MutexTable::copy(MutexTable const &other) { + _size = other.size(); + _table = new MutexTree* [_size]; + for (unsigned i = 0; i < _size; i++) + _table[i] = new MutexTree(*(other._table[i])); +} diff --git a/xr/ThreadsAndMutexes/mutextable/destroy.cc b/xr/ThreadsAndMutexes/mutextable/destroy.cc @@ -0,0 +1,7 @@ +#include "mutextable" + +void MutexTable::destroy() { + for (unsigned i = 0; i < _size; i++) + delete _table[i]; + delete _table; +} diff --git a/xr/ThreadsAndMutexes/mutextable/hash.cc b/xr/ThreadsAndMutexes/mutextable/hash.cc @@ -0,0 +1,5 @@ +#include "mutextable" + +unsigned MutexTable::hash(void *obj) { + return (unsigned) ( (long)obj % (long)_size ); +} diff --git a/xr/ThreadsAndMutexes/mutextable/lock.cc b/xr/ThreadsAndMutexes/mutextable/lock.cc @@ -0,0 +1,5 @@ +#include "mutextable" + +void MutexTable::lock(void *obj) { + _table[hash(obj)]->lock(obj); +} diff --git a/xr/ThreadsAndMutexes/mutextable/mutextable b/xr/ThreadsAndMutexes/mutextable/mutextable @@ -0,0 +1,30 @@ +#ifndef _MUTEXTABLE_ +#define _MUTEXTABLE_ + +#include "ThreadsAndMutexes/mutextree/mutextree" + +class MutexTable { +public: + MutexTable(unsigned sz); + MutexTable(MutexTable const &other); + ~MutexTable(); + + MutexTable const &operator=(MutexTable const &other); + + void lock(void *o); + void unlock(void *o); + + unsigned size() const { return _size; } + int weight(unsigned i) const; + int balance(unsigned i) const; + +private: + void copy(MutexTable const &other); + void destroy(); + unsigned hash(void *o); + + MutexTree **_table; + unsigned _size; +}; + +#endif diff --git a/xr/ThreadsAndMutexes/mutextable/mutextable1.cc b/xr/ThreadsAndMutexes/mutextable/mutextable1.cc @@ -0,0 +1,8 @@ +#include "mutextable" + +MutexTable::MutexTable(unsigned sz): _size(sz) { + _table = new MutexTree* [sz]; + for (unsigned i = 0; i < sz; i++) + _table[i] = new MutexTree; +} + diff --git a/xr/ThreadsAndMutexes/mutextable/mutextable2.cc b/xr/ThreadsAndMutexes/mutextable/mutextable2.cc @@ -0,0 +1,5 @@ +#include "mutextable" + +MutexTable::MutexTable(MutexTable const &other) { + copy(other); +} diff --git a/xr/ThreadsAndMutexes/mutextable/mutextable3.cc b/xr/ThreadsAndMutexes/mutextable/mutextable3.cc @@ -0,0 +1,5 @@ +#include "mutextable" + +MutexTable::~MutexTable() { + destroy(); +} diff --git a/xr/ThreadsAndMutexes/mutextable/opis.cc b/xr/ThreadsAndMutexes/mutextable/opis.cc @@ -0,0 +1,9 @@ +#include "mutextable" + +MutexTable const &MutexTable::operator=(MutexTable const &other) { + if (this != &other) { + destroy(); + copy(other); + } + return *this; +} diff --git a/xr/ThreadsAndMutexes/mutextable/unlock.cc b/xr/ThreadsAndMutexes/mutextable/unlock.cc @@ -0,0 +1,5 @@ +#include "mutextable" + +void MutexTable::unlock(void *obj) { + _table[hash(obj)]->unlock(obj); +} diff --git a/xr/ThreadsAndMutexes/mutextable/weight.cc b/xr/ThreadsAndMutexes/mutextable/weight.cc @@ -0,0 +1,5 @@ +#include "mutextable" + +int MutexTable::weight(unsigned i) const { + return i < size() ? _table[i]->weight() : 0; +} diff --git a/xr/ThreadsAndMutexes/mutextree/balance.cc b/xr/ThreadsAndMutexes/mutextree/balance.cc @@ -0,0 +1,5 @@ +#include "mutextree" + +int MutexTree::balance() const { + return _root ? _root->balance() : 0; +} diff --git a/xr/ThreadsAndMutexes/mutextree/copy.cc b/xr/ThreadsAndMutexes/mutextree/copy.cc @@ -0,0 +1,6 @@ +#include "mutextree" + +void MutexTree::copy(MutexTree const &other) { + _treelock = other._treelock; + _root = new MutexNode(other._root); +} diff --git a/xr/ThreadsAndMutexes/mutextree/destroy.cc b/xr/ThreadsAndMutexes/mutextree/destroy.cc @@ -0,0 +1,5 @@ +#include "mutextree" + +void MutexTree::destroy() { + delete _root; +} diff --git a/xr/ThreadsAndMutexes/mutextree/lock.cc b/xr/ThreadsAndMutexes/mutextree/lock.cc @@ -0,0 +1,7 @@ +#include "mutextree" + +void MutexTree::lock(void *o) { + locktree(); + _root = nodelock(o, _root); + unlocktree(); +} diff --git a/xr/ThreadsAndMutexes/mutextree/mutextree b/xr/ThreadsAndMutexes/mutextree/mutextree @@ -0,0 +1,33 @@ +#ifndef _MUTEXTREE_ +#define _MUTEXTREE_ + +#include "ThreadsAndMutexes/mutexnode/mutexnode" + +class MutexTree { +public: + MutexTree(); + MutexTree(MutexTree const &other); + ~MutexTree(); + + MutexTree const &operator=(MutexTree const &other); + + void lock(void *o); + void unlock(void *o); + + int weight() const; + int balance() const; + +private: + void locktree() { _treelock.lock(); }; + void unlocktree() { _treelock.unlock(); } + MutexNode *nodelock(void *o, MutexNode *start); + void nodeunlock(void *o, MutexNode *start); + + void copy(MutexTree const &other); + void destroy(); + + MutexNode *_root; + Mutex _treelock; +}; + +#endif diff --git a/xr/ThreadsAndMutexes/mutextree/mutextree1.cc b/xr/ThreadsAndMutexes/mutextree/mutextree1.cc @@ -0,0 +1,4 @@ +#include "mutextree" + +MutexTree::MutexTree(): _root(0), _treelock() { +} diff --git a/xr/ThreadsAndMutexes/mutextree/mutextree2.cc b/xr/ThreadsAndMutexes/mutextree/mutextree2.cc @@ -0,0 +1,5 @@ +#include "mutextree" + +MutexTree::MutexTree(MutexTree const &other) { + copy(other); +} diff --git a/xr/ThreadsAndMutexes/mutextree/mutextree3.cc b/xr/ThreadsAndMutexes/mutextree/mutextree3.cc @@ -0,0 +1,5 @@ +#include "mutextree" + +MutexTree::~MutexTree() { + destroy(); +} diff --git a/xr/ThreadsAndMutexes/mutextree/nodelock.cc b/xr/ThreadsAndMutexes/mutextree/nodelock.cc @@ -0,0 +1,24 @@ +#include "mutextree" + +MutexNode *MutexTree::nodelock(void *o, MutexNode *start) { + + // No tree start yet? Create one. + if (!start) { + start = new MutexNode(o); + start->lock(); + return start; + } + + // At object? Dive into the Mutexnode. + if (start->obj() == o) { + start->lock(); + return start; + } + + // Decide whether to recurse left or right. + if (start->obj() < o) + start->left(nodelock(o, start->left())); + else + start->right(nodelock(o, start->right())); + return start; +} diff --git a/xr/ThreadsAndMutexes/mutextree/nodeunlock.cc b/xr/ThreadsAndMutexes/mutextree/nodeunlock.cc @@ -0,0 +1,13 @@ +#include "mutextree" + +void MutexTree::nodeunlock(void *o, MutexNode *start) { + if (!start) + return; + + if (start->obj() == o) + start->unlock(); + else if (start->obj() < o) + nodeunlock(o, start->left()); + else + nodeunlock(o, start->right()); +} diff --git a/xr/ThreadsAndMutexes/mutextree/opis.cc b/xr/ThreadsAndMutexes/mutextree/opis.cc @@ -0,0 +1,9 @@ +#include "mutextree" + +MutexTree const &MutexTree::operator=(MutexTree const &other) { + if (this != &other) { + destroy(); + copy(other); + } + return *this; +} diff --git a/xr/ThreadsAndMutexes/mutextree/unlock.cc b/xr/ThreadsAndMutexes/mutextree/unlock.cc @@ -0,0 +1,5 @@ +#include "mutextree" + +void MutexTree::unlock(void *o) { + nodeunlock(o, _root); +} diff --git a/xr/ThreadsAndMutexes/mutextree/weight.cc b/xr/ThreadsAndMutexes/mutextree/weight.cc @@ -0,0 +1,5 @@ +#include "mutextree" + +int MutexTree::weight() const { + return _root ? _root->weight() : 0; +} diff --git a/xr/ThreadsAndMutexes/thread/run.cc b/xr/ThreadsAndMutexes/thread/run.cc @@ -4,17 +4,17 @@ void *Thread::_run (void *data) { Thread *t = (Thread*) data; - debugmsg(Mstr("Thread: starting run\n")); + debugmsg("Thread: starting run\n"); Threadlist::enregister(); try { t->execute(); } catch (Error const &e) { - lock(&cerr); + mutex_lock(&cerr); cerr << e.what() << "\n"; - unlock(&cerr); + mutex_unlock(&cerr); } Threadlist::deregister(); - debugmsg(Mstr("Thread: ending run\n")); + debugmsg("Thread: ending run\n"); // Cleanups delete (t); diff --git a/xr/ThreadsAndMutexes/thread/start.cc b/xr/ThreadsAndMutexes/thread/start.cc @@ -17,11 +17,11 @@ void Thread::start() { throw Error("Cannot set thread state as detached"); for (int i = 0; i < 3; i++) { # ifdef MISTRUST_THREAD_CREATE_THREADSAFE - lock((void*)_run); + mutex_lock((void*)_run); # endif res = pthread_create (&th, &attr, _run, (void*) this); # ifdef MISTRUST_THREAD_CREATE_THREADSAFE - unlock((void*)_run); + mutex_unlock((void*)_run); # endif if (!res) { pthread_attr_destroy (&attr); diff --git a/xr/ThreadsAndMutexes/thread/thread b/xr/ThreadsAndMutexes/thread/thread @@ -12,9 +12,9 @@ using namespace std; #ifdef MEMDEBUG -class Thread: public Mutex, public Memory +class Thread: public Memory #else -class Thread: public Mutex +class Thread #endif { public: diff --git a/xr/ThreadsAndMutexes/threadlist/deregister1.cc b/xr/ThreadsAndMutexes/threadlist/deregister1.cc @@ -1,7 +1,7 @@ #include "threadlist" void Threadlist::deregister(pthread_t id) { - Mutex::lock(&th_map); + mutex_lock(&th_map); th_map.erase(id); - Mutex::unlock(&th_map); + mutex_unlock(&th_map); } diff --git a/xr/ThreadsAndMutexes/threadlist/enregister.cc b/xr/ThreadsAndMutexes/threadlist/enregister.cc @@ -4,7 +4,7 @@ Threadmap Threadlist::th_map; void Threadlist::enregister() { Threadinfo n; - Mutex::lock(&th_map); + mutex_lock(&th_map); th_map[pthread_self()] = n; - Mutex::unlock(&th_map); + mutex_unlock(&th_map); } diff --git a/xr/backend/addbytes.cc b/xr/backend/addbytes.cc @@ -1,7 +1,7 @@ #include "backend" void Backend::addbytes (unsigned n) { - Mutex::lock (&bytes_served); + mutex_lock(&bytes_served); bytes_served += n; - Mutex::unlock (&bytes_served); + mutex_unlock (&bytes_served); } diff --git a/xr/backend/available.cc b/xr/backend/available.cc @@ -5,15 +5,13 @@ bool Backend::available() const { PROFILE("Backend::available"); - if (config.debug()) { - ostringstream o; - o << "Back end " << description() << ": " - << livestr() << ", " << upstr() << ", " - << connections() << " connections, " - << IPStore::anticipated(balancerindex()) << " anticipated, " - << maxconn() << " max\n"; - _debugmsg(o.str()); - } + /* + debugmsg("Back end " << description() << ": " + << livestr() << ", " << upstr() << ", " + << connections() << " connections, " + << IPStore::anticipated(balancerindex()) << " anticipated, " + << maxconn() << " max\n"); + */ if (!maxconn()) return (islive && isup); return (islive && diff --git a/xr/backend/backend b/xr/backend/backend @@ -5,7 +5,6 @@ #include "backenddef/backenddef" #include "fdset/fdset" #include "error/error" -#include "ThreadsAndMutexes/mutex/mutex" #include "profiler/profiler" #include "backendcheck/backendcheck" #include "httpbuffer/httpbuffer" diff --git a/xr/backend/check.cc b/xr/backend/check.cc @@ -1,8 +1,8 @@ #include "backend" void Backend::check() { - debugmsg(Mstr("About to check back end ") + description() + ". " + - Mstr(backendcheck().description()) + "\n"); + debugmsg("About to check back end " << description() << ". " << + backendcheck().description() << '\n'); ostringstream o; Backend tester; @@ -26,8 +26,8 @@ void Backend::check() { tester.connect(); socketclose (tester.sock()); live(tester.live()); - msg (Mstr("Alternative back end for testing ") + - tester.description() + " is " + livestr() + "\n"); + msg ("Alternative back end for testing " << + tester.description() << " is " << livestr() << '\n'); } break; @@ -37,10 +37,9 @@ void Backend::check() { tester.port(backendcheck().port()); tester.connect(); if (! tester.live()) { - warnmsg((Mstr("HTTP GET checker: host ") + - backendcheck().server()) + - (Mstr(", port ") + backendcheck().port()) + - " not responding\n"); + warnmsg("HTTP GET checker: host " << backendcheck().server() + << ", port " << backendcheck().port() << + "not responding\n"); live(false); } else { o << "GET " << backendcheck().uri() << " HTTP/1.0\r\n" @@ -53,8 +52,8 @@ void Backend::check() { while (!httpbuffer.headersreceived()) httpbuffer.netread(tester.sock(), config.backend_read_timeout()); - msg((Mstr("HTTP GET checker got answer: '") + - httpbuffer.firstline()) + "'\n"); + msg("HTTP GET checker got answer: '" << + httpbuffer.firstline() << '\n'); if (httpbuffer.stringat(9, 3) == "200") live(true); else @@ -72,20 +71,20 @@ void Backend::check() { int result; if (! (f = popen(o.str().c_str(), "r")) ) { live(false); - warnmsg(Mstr("Failed to start external checker '") + o.str() + - "': " + strerror(errno) + "\n"); + warnmsg("Failed to start external checker '" << o.str() << + ": " << strerror(errno) << '\n'); } else { if (fscanf(f, "%d", &result) < 1) { live(false); - warnmsg(Mstr("External checker '") + o.str() + - Mstr("' did not reply with a number\n")); + warnmsg("External checker '" << o.str() << + "' did not reply with a number\n"); } else { - msg((Mstr("External checker '") + o.str()) + - (Mstr("' replied: ") + result) + '\n'); + msg("External checker '" << o.str() << "' replied: " << + result << '\n'); live(result == 0); } if (pclose(f)) { - warnmsg((Mstr("External checker '") + o.str()) + + warnmsg("External checker '" << o.str() << "' terminated with error\n"); live(false); } diff --git a/xr/backend/connect.cc b/xr/backend/connect.cc @@ -6,7 +6,7 @@ bool Backend::connect() { // Assume the backend is dead islive = false; - debugmsg ("About to connect to back end " + description() + "\n"); + debugmsg("About to connect to back end " << description() << '\n'); // Create client socket if ( (clsocket = socket (PF_INET, SOCK_STREAM, 0)) < 0 ) @@ -37,8 +37,8 @@ bool Backend::connect() { int conres = ::connect (clsocket, (struct sockaddr *)&backendaddr, sizeof(backendaddr)); int conerrno = errno; - debugmsg((Mstr("Connect result: ") + conres) + - (Mstr(", errno: ") + conerrno) + "\n"); + debugmsg("Connect result: " << conres << + ", errno: " << conerrno << '\n'); // Put socket again in blocking mode. if (fcntl (clsocket, F_SETFL, flags) == -1) { @@ -54,7 +54,7 @@ bool Backend::connect() { fdset.add (clsocket); fdset.wait_rw(); - debugmsg(Mstr("Connecting to ") + description() + "\n"); + debugmsg("Connecting to " << description() << '\n'); # ifdef CONNECTCHECK_ONLY_WRITABLE if (fdset.writeable(clsocket)) @@ -73,9 +73,8 @@ bool Backend::connect() { # endif } - debugmsg ((Mstr("Back end ") + description()) + - (Mstr(" is ") + livestr()) + - (Mstr(" (socket ") + clsocket) + ")\n"); + debugmsg("Back end " << description() << " is " << livestr() << + " (socket " << clsocket << ")\n"); return (islive); } diff --git a/xr/backend/endconnection.cc b/xr/backend/endconnection.cc @@ -1,7 +1,7 @@ #include "backend" void Backend::endconnection() { - Mutex::lock (&nconn); + mutex_lock (&nconn); nconn--; - Mutex::unlock (&nconn); + mutex_unlock (&nconn); } diff --git a/xr/backend/live.cc b/xr/backend/live.cc @@ -3,10 +3,10 @@ void Backend::live (bool state) { PROFILE("Backend::live"); - Mutex::lock (&islive); + mutex_lock(&islive); bool oldstate = islive; islive = state; - Mutex::unlock (&islive); + mutex_unlock(&islive); if (oldstate != state) msg ("Marking back end " + description() + " as " + livestr() + "\n"); diff --git a/xr/backend/markconnecterror.cc b/xr/backend/markconnecterror.cc @@ -1,8 +1,8 @@ #include "backend" void Backend::markconnecterror() { - Mutex::lock(&nconnerr); + mutex_lock(&nconnerr); nconnerr++; - Mutex::unlock(&nconnerr); + mutex_unlock(&nconnerr); } diff --git a/xr/backend/startconnection.cc b/xr/backend/startconnection.cc @@ -1,11 +1,11 @@ #include "backend" void Backend::startconnection() { - Mutex::lock (&nconn); + mutex_lock (&nconn); nconn++; - Mutex::unlock (&nconn); + mutex_unlock (&nconn); - Mutex::lock (&totconn); + mutex_lock (&totconn); totconn++; - Mutex::unlock (&totconn); + mutex_unlock (&totconn); } diff --git a/xr/backend/up.cc b/xr/backend/up.cc @@ -3,10 +3,10 @@ void Backend::up (bool state) { PROFILE("Backend::up"); - Mutex::lock (&isup); + mutex_lock (&isup); bool oldstate = isup; isup = state; - Mutex::unlock (&isup); + mutex_unlock (&isup); if (oldstate != state) msg ("Marking back end " + description() + " as " + upstr() + "\n"); diff --git a/xr/backenddef/weight.cc b/xr/backenddef/weight.cc @@ -3,7 +3,7 @@ void BackendDef::weight(unsigned w) { wt = w; - Mutex::lock(&minmax_wt_set); + mutex_lock(&minmax_wt_set); if (!minmax_wt_set) { min_wt = w; max_wt = w; @@ -14,5 +14,5 @@ void BackendDef::weight(unsigned w) { if (max_wt > w) max_wt = w; } - Mutex::unlock(&minmax_wt_set); + mutex_unlock(&minmax_wt_set); } diff --git a/xr/balancer/addbackend2.cc b/xr/balancer/addbackend2.cc @@ -2,19 +2,19 @@ void Balancer::addbackend (Backend const &b, bool is_up, bool is_live, bool do_check) { - debugmsg(Mstr("Adding back end ") + b.description() + " to list\n"); + debugmsg("Adding back end " << b.description() << " to list\n"); - Mutex::lock(&backends); + mutex_lock(&backends); backends.push_back (b); backends[backends.size() - 1].up(is_up); backends[backends.size() - 1].live(is_live); backends[backends.size() - 1].balancerindex(backends.size() - 1); - Mutex::unlock(&backends); + mutex_unlock(&backends); if (do_check) { - debugmsg(Mstr("Verifying configured back end\n")); + debugmsg("Verifying configured back end\n"); backends[backends.size() - 1].check(); } - debugmsg(Mstr("Back end ") + b.description() + " added to list\n"); + debugmsg("Back end " << b.description() << " added to list\n"); } diff --git a/xr/balancer/deletebackend.cc b/xr/balancer/deletebackend.cc @@ -10,8 +10,8 @@ void Balancer::deletebackend(unsigned i) { throw Error(o.str()); } - Mutex::lock(&backends); + mutex_lock(&backends); backends.erase(backends.begin() + i, backends.begin() + i + 1); - Mutex::unlock(&backends); + mutex_unlock(&backends); } diff --git a/xr/balancer/init.cc b/xr/balancer/init.cc @@ -22,12 +22,10 @@ void Balancer::init() { } // Add workable back ends, display initial states. - for (int i = 0; i < config.backends(); i++) + for (int i = 0; i < config.backends(); i++) addbackend (config.backend(i)); - - if (config.verbose()) { - for (unsigned i = 0; i < nbackends(); i++) - _msg ("Initial backend state: " + backend(i).description() + - " is " + backend(i).availablestr() + "\n"); - } + msg("Back end start states of " << nbackends() << " backends:\n"); + for (unsigned i = 0; i < nbackends(); i++) + msg(' ' << backend(i).description() << " is " << + backend(i).availablestr() << '\n'); } diff --git a/xr/balancer/serve.cc b/xr/balancer/serve.cc @@ -37,7 +37,7 @@ void Balancer::serve() { } // Wait for activity, serve it. - msg ((Mstr("Awaiting activity on fd ") + server_fd) + "\n"); + msg ("Awaiting activity on fd " << server_fd << '\n'); MEM(Memory::mem_mark("Balancer start")); MEM(Memory::mem_follow(true)); while (true) { @@ -57,16 +57,15 @@ void Balancer::serve() { msg ("Report requested\n"); reportmsg ("*** XR STATUS REPORT STARTS ***\n"); for (unsigned i = 0; i < nbackends(); i++) { - reportmsg("Back end " + backend(i).description() + "\n"); - reportmsg((Mstr(" Status: ") + - backend(i).availablestr()) + - (Mstr(", ") + backend(i).livestr()) + "\n"); - reportmsg((Mstr(" Connections: ") + - backend(i).connections()) - + - (Mstr(" (max ") + backend(i).maxconn()) + "\n"); - reportmsg((Mstr(" Served:") + backend(i).bytesserved()) + - (Mstr(" bytes, ") + backend(i).clientsserved()) + + reportmsg("Back end " << backend(i).description() << '\n'); + reportmsg(" Status: " << + backend(i).availablestr() << ", " << + backend(i).livestr() << '\n'); + reportmsg(" Connections: " << + backend(i).connections() << + " (max " << backend(i).maxconn() << ")\n"); + reportmsg(" Served:" << backend(i).bytesserved() << + " bytes, " << backend(i).clientsserved() << " clients\n"); } report (false); @@ -82,11 +81,11 @@ void Balancer::serve() { } // Got activity! Check total # of connections. - msg ((Mstr("Got activity on fd ") + server_fd) + "\n"); + msg ("Got activity on fd " << server_fd << '\n'); request_nr++; if (config.maxconn() && connections() >= config.maxconn()) { - msg ((Mstr("Not serving connection: already ") + connections()) + - (Mstr(" connection(s) (max ") + config.maxconn()) + ")\n"); + msg ("Not serving connection: already " << connections() << + " connection(s) (max " << config.maxconn() << ")\n"); continue; } @@ -99,28 +98,27 @@ void Balancer::serve() { if (config.stype() != Servertype::t_udp) { if ( (clsock = accept (server_fd, (struct sockaddr *) &clname, (socklen_t*) &size)) < 0 ) { - warnmsg(Mstr("Failed to accept network connection: ") + - Mstr(strerror(errno)) + "\n"); + warnmsg("Failed to accept network connection: " << + strerror(errno) << '\n'); continue; } - string clientip = inet_ntoa(clname.sin_addr); - msg ((Mstr("Accepted connection from ") + clientip) + - (Mstr(" as client fd ") + clsock) + "\n"); + msg ("Accepted connection from " << + inet2string(clname.sin_addr) << " as client fd " << + clsock << '\n'); } // Show how we look if (config.verbose()) { ostringstream o; - msg ((Mstr("Balancer is serving ") + connections()) + - " clients\n"); + msg ("Balancer is serving " << connections() << " clients\n"); msg ("Current back end states:\n"); - for (unsigned i = 0; i < nbackends(); i++) - msg((Mstr(" Back end ") + backend(i).description()) + - (Mstr(": ") + backend(i).connections()) + - (Mstr(" connections, max ") + backend(i).maxconn()) + - (Mstr(", status ") + backend(i).availablestr()) + - (Mstr(", anticipated ") + IPStore::anticipated(i)) + - "\n"); + for (unsigned i = 0; i < nbackends(); i++) { + msg(" Back end " << backend(i).description() << ": " << + backend(i).connections() << " connections, max " << + backend(i).maxconn() << ", status " << + backend(i).availablestr() << ", anticipated " << + IPStore::anticipated(i) << '\n'); + } } Dispatcher *d; @@ -145,8 +143,8 @@ void Balancer::serve() { if (config.debug()) { void *mem = malloc(16); free (mem); - _debugmsg (Mstr("Allocation boundary at dispatcher start: ") + - mem + "\n"); + debugmsg("Allocation boundary at dispatcher start: " << + mem << '\n'); } #ifdef SHOWDEBUG void *mem = malloc(16); @@ -183,8 +181,8 @@ void Balancer::serve() { // If we exceed the max # of requests, stop.. if (config.quitafter()) { - msg ((Mstr("Request ") + requestnr()) + - (Mstr(" underway of max ") + config.quitafter()) + "\n"); + msg ("Request " << requestnr() << " underway of max " << + config.quitafter() << '\n'); if (requestnr() >= (long)config.quitafter()) { msg ("Max requests served, will stop.\n"); break; @@ -205,7 +203,7 @@ void Balancer::serve() { if (!curr_conn) break; if (curr_conn != prev_conn) { - msg ((Mstr("There are still ") + curr_conn) + " connections\n"); + msg ("There are still " << curr_conn << " connections\n"); prev_conn = curr_conn; } sleep (1); diff --git a/xr/config/addserverheader.cc b/xr/config/addserverheader.cc @@ -1,7 +1,7 @@ #include "config" void Config::addserverheader (string const &s) { - Mutex::lock (&serverheaders); + mutex_lock (&serverheaders); serverheaders.push_back (s); - Mutex::unlock (&serverheaders); + mutex_unlock (&serverheaders); } diff --git a/xr/config/addxforwardedfor.cc b/xr/config/addxforwardedfor.cc @@ -1,7 +1,7 @@ #include "config" void Config::addxforwardedfor(bool b) { - Mutex::lock (&add_x_forwarded_for); + mutex_lock (&add_x_forwarded_for); add_x_forwarded_for = b; - Mutex::unlock (&add_x_forwarded_for); + mutex_unlock (&add_x_forwarded_for); } diff --git a/xr/config/addxrversion.cc b/xr/config/addxrversion.cc @@ -1,7 +1,7 @@ #include "config" void Config::addxrversion(bool b) { - Mutex::lock (&add_xr_version); + mutex_lock (&add_xr_version); add_xr_version = b; - Mutex::unlock (&add_xr_version); + mutex_unlock (&add_xr_version); } diff --git a/xr/config/buffersize.cc b/xr/config/buffersize.cc @@ -1,7 +1,7 @@ #include "config" void Config::buffersize(unsigned b) { - Mutex::lock (&bufsize); + mutex_lock (&bufsize); bufsize = b; - Mutex::unlock (&bufsize); + mutex_unlock (&bufsize); } diff --git a/xr/config/changeserverheader.cc b/xr/config/changeserverheader.cc @@ -1,7 +1,7 @@ #include "config" void Config::changeserverheader (unsigned i, string const &s) { - Mutex::lock (&serverheaders); + mutex_lock (&serverheaders); serverheaders[i] = s; - Mutex::unlock (&serverheaders); + mutex_unlock (&serverheaders); } diff --git a/xr/config/fastclose.cc b/xr/config/fastclose.cc @@ -1,7 +1,7 @@ #include "config" void Config::fastclose(bool b) { - Mutex::lock (&fast_close); + mutex_lock (&fast_close); fast_close = b; - Mutex::unlock (&fast_close); + mutex_unlock (&fast_close); } diff --git a/xr/config/ipstoretimeout.cc b/xr/config/ipstoretimeout.cc @@ -1,7 +1,7 @@ #include "config" void Config::ipstoretimeout (int t) { - Mutex::lock (&ipstore_timeout); + mutex_lock (&ipstore_timeout); ipstore_timeout = t; - Mutex::unlock (&ipstore_timeout); + mutex_unlock (&ipstore_timeout); } diff --git a/xr/config/maxconn.cc b/xr/config/maxconn.cc @@ -1,7 +1,7 @@ #include "config" void Config::maxconn (unsigned m) { - Mutex::lock (&max_conn); + mutex_lock (&max_conn); max_conn = m; - Mutex::unlock (&max_conn); + mutex_unlock (&max_conn); } diff --git a/xr/config/pidfile.cc b/xr/config/pidfile.cc @@ -1,7 +1,7 @@ #include "config" void Config::pidfile (string const &p) { - Mutex::lock (&pid_file); + mutex_lock (&pid_file); pid_file = p; - Mutex::unlock (&pid_file); + mutex_unlock (&pid_file); } diff --git a/xr/config/prefixtimestamp.cc b/xr/config/prefixtimestamp.cc @@ -1,7 +1,7 @@ #include "config" void Config::prefixtimestamp(bool b) { - Mutex::lock (&prefix_timestamp); + mutex_lock (&prefix_timestamp); prefix_timestamp = b; - Mutex::unlock (&prefix_timestamp); + mutex_unlock (&prefix_timestamp); } diff --git a/xr/config/removeserverheader.cc b/xr/config/removeserverheader.cc @@ -1,8 +1,8 @@ #include "config" void Config::removeserverheader (unsigned i) { - Mutex::lock (&serverheaders); + mutex_lock (&serverheaders); serverheaders.erase (serverheaders.begin() + i, serverheaders.begin() + i + 1); - Mutex::unlock (&serverheaders); + mutex_unlock (&serverheaders); } diff --git a/xr/config/stickyhttp.cc b/xr/config/stickyhttp.cc @@ -1,7 +1,7 @@ #include "config" void Config::stickyhttp (bool b) { - Mutex::lock (&sticky_http); + mutex_lock (&sticky_http); sticky_http = b; - Mutex::unlock (&sticky_http); + mutex_unlock (&sticky_http); } diff --git a/xr/dnsentry/resolve.cc b/xr/dnsentry/resolve.cc @@ -7,14 +7,14 @@ in_addr_t &DNSEntry::resolve (string const &h) { // Resolve now. struct hostent *hostaddr; - Mutex::lock((void*)gethostbyname); + mutex_lock((void*)gethostbyname); if ( (hostaddr = gethostbyname(h.c_str())) ) memcpy (&result, hostaddr->h_addr_list[0], hostaddr->h_length); - Mutex::unlock((void*)gethostbyname); + mutex_unlock((void*)gethostbyname); if (!hostaddr) throw Error("Failed to resolve host '" + h + "'"); - debugmsg(Mstr("Host ") + h + " resolved\n"); + debugmsg("Host " << h << " resolved\n"); return result; } diff --git a/xr/etc/Makefile.class b/xr/etc/Makefile.class @@ -12,7 +12,7 @@ endif class-compile: $(OBJ) $(BASE)/xr/$(BUILDDIR)/$(DIR)_%.o: %.cc - @echo "Compiling: " `pwd` $< + @echo "Compiling: " `pwd`$< $(CONF_CC) $(PROF) $(PROFILER) $(CONF_OPTFLAGS) \ -DVER='"$(VER)"' -DAUTHOR='"$(AUTHOR)"' -DHST='"$(HST)"' \ -DMAINTAINER='"$(MAINTAINER)"' -DDISTSITE='"$(DISTSITE)"' \ diff --git a/xr/etc/c-conf b/xr/etc/c-conf @@ -1,4 +1,4 @@ -#!/usr/bin/perl +#!/usr/bin/env perl use strict; use Getopt::Std; diff --git a/xr/etc/usage.txt b/xr/etc/usage.txt @@ -133,7 +133,7 @@ may not exist on your platform): --remove-reservations, -G In stored-ip algorithms, outstanding reservations for expected clients are removed when no more back ends are available. - --replace-host-header HDR, -I HDR + --replace-host-header, -I Inserts "Host: <backend>" into back end bound HTTP messages. Pre-existing Host headers are overwritten. The value of <backend> is the server name as in the setting of --backend (-b). @@ -176,6 +176,7 @@ may not exist on your platform): Defines wakeup period (rechecking) in seconds, of unavailable back ends. Default is 5. Use -w0 to suppress. -XR's messages are sent to stderr. Invoke XR daemons using something like +XR's errors and warnings are sent to stderr, debugging and verbose +messages go to stdout. Invoke XR daemons using something like "xr --backend ... [other flags] 2>&1 | logger &", or use xrctl. diff --git a/xr/fdset/wait.cc b/xr/fdset/wait.cc @@ -17,7 +17,7 @@ void Fdset::wait(bool wait_read, bool wait_write) { FD_SET (set[i], &readset); FD_SET (set[i], &writeset); FD_SET (set[i], &exceptset); - debugmsg(Mstr("About to wait for fd ") + Mstr(set[i]) + "\n"); + debugmsg("About to wait for fd "<< set[i] << '\n'); } // Prepare timout specifier. @@ -25,10 +25,10 @@ void Fdset::wait(bool wait_read, bool wait_write) { tv.tv_sec = tsec; tv.tv_usec = 0; tvp = &tv; - debugmsg(Mstr("Waiting limitation: ") + Mstr(tsec) + "\n"); + debugmsg("Waiting limitation: " << tsec << '\n'); } else { tvp = 0; - debugmsg(Mstr("No waiting limitation\n")); + debugmsg("No waiting limitation\n"); } // Run the select. @@ -59,11 +59,11 @@ void Fdset::wait(bool wait_read, bool wait_write) { bool statechanged = false; for (unsigned int i = 0; i < FD_SETSIZE; i++) { if (FD_ISSET(i, &readset)) { - _debugmsg(Mstr("Fd ") + Mstr(i) + " is readable\n"); + debugmsg("Fd " << i << " is readable\n"); statechanged = true; } if (FD_ISSET(i, &writeset)) { - _debugmsg(Mstr("Fd ") + Mstr(i) + " is writeable\n"); + debugmsg("Fd " << i << " is writeable\n"); statechanged = true; } } @@ -73,7 +73,7 @@ void Fdset::wait(bool wait_read, bool wait_write) { for (unsigned int i = 0; i < set.size(); i++) o << set[i] << ' '; o << "has shown activity in " << tsec << " sec\n"; - _debugmsg(o.str()); + debugmsg(o.str()); } } } diff --git a/xr/httpbuffer/cookievalue.cc b/xr/httpbuffer/cookievalue.cc @@ -17,6 +17,6 @@ string Httpbuffer::cookievalue (string c) { ret += ch; } } - msg(Mstr("Cookie value '") + c + Mstr("' : '") + ret + "'\n"); + msg("Cookie value '" << c << "' : '" << ret << "'\n"); return (ret); } diff --git a/xr/httpbuffer/findheader.cc b/xr/httpbuffer/findheader.cc @@ -2,11 +2,18 @@ unsigned Httpbuffer::findheader(string h) { PROFILE("Httpbuffer::findheader"); - + + // No headers in here yet? Don't process. if (!headersreceived()) - return (0); + return 0; + + // We must have a first HTTP line, else we don't have headers + if (!firstline().length()) + return 0; - for (unsigned int i = 1; i < bufsz(); /* incremented below */) { + // Scan until bodystart (which is set in headersreceived()). + // Used to scan until bufsz() but that's not right, thanks Maxim P. + for (unsigned int i = 1; i < bodystart; /* incremented below */) { // At header? if (!strncmp(bufdata() + i, h.c_str(), h.size())) return i; diff --git a/xr/httpbuffer/firstline.cc b/xr/httpbuffer/firstline.cc @@ -2,15 +2,44 @@ string &Httpbuffer::firstline() { PROFILE("Httpbuffer::firstline"); - - if (first_line.size()) - return (first_line); - + + // Already determined? Re-return. + if (first_line.size()) { + debugmsg("Previously determined first buffer line: " << first_line << + '\n'); + return first_line; + } + + // Extract the first line for (unsigned i = 0; i < bufsz(); i++) { char ch = charat(i); if (ch == '\n' || ch == '\r') break; first_line += ch; } - return (first_line); + + // Buffer must start with a known HTTP label, else we're in a TCP + // transmission + static string http_label[] = { + // Request labels + "OPTIONS ", "GET ", "HEAD ", "POST ", "PUT ", "DELETE ", "TRACE ", + "CONNECT ", + // Response labels + "HTTP/", + // Stopper + "" + }; + + bool is_label = false; + for (unsigned int i = 0; http_label[i] != ""; i++) + if (!strncmp(first_line.c_str(), http_label[i].c_str(), + http_label[i].length())) { + is_label = true; + break; + } + if (!is_label) + first_line = ""; + + debugmsg("First line determined as: [" << first_line << "]\n"); + return first_line; } diff --git a/xr/httpbuffer/paramvalue.cc b/xr/httpbuffer/paramvalue.cc @@ -16,6 +16,6 @@ string Httpbuffer::paramvalue (string c) { ch = uri[++pos]) ret += ch; } - msg(Mstr("Param value '") + c + Mstr("' : '") + ret + "'\n"); + msg("Param value '" << c << "' : '" << ret << "'\n"); return ret; } diff --git a/xr/httpbuffer/replaceheader2.cc b/xr/httpbuffer/replaceheader2.cc @@ -6,11 +6,14 @@ void Httpbuffer::replaceheader(string const &var, string const &val) { if (!headersreceived()) return; + debugmsg("Attempting to replace header " << var << " with " << val << '\n'); + unsigned off = findheader(var); + debugmsg("Header [" << var << "] occurs at position " << off << '\n'); if (off) { unsigned nl = charfind('\n', off); if (nl) removeat(off, nl - off + 1); + setheader(var, val); } - setheader(var, val); } diff --git a/xr/ipstore/activity.cc b/xr/ipstore/activity.cc @@ -4,12 +4,12 @@ void IPStore::activity(struct in_addr clientip, unsigned curbackend) { if (!onoff) return; - msg(Mstr("Logging activity for back end ") + Mstr(curbackend) + - Mstr(" from ") + inet_ntoa(clientip) + "\n"); + msg("Logging activity for back end " << curbackend << + " from " << inet2string(clientip) << '\n'); - Mutex::lock(&store); + mutex_lock(&store); store[clientip].targetbackend = (int)curbackend; store[clientip].lastaccess = time(0); - Mutex::unlock(&store); + mutex_unlock(&store); } diff --git a/xr/ipstore/anticipated.cc b/xr/ipstore/anticipated.cc @@ -10,16 +10,16 @@ unsigned IPStore::anticipated(unsigned b) { // Get number of anticipated clients for given back end unsigned ret = 0; - Mutex::lock(&store); + mutex_lock(&store); for (StoreMap::iterator iter = store.begin(); iter != store.end(); iter++) if ((*iter).second.targetbackend == (int)b) ret++; - Mutex::unlock(&store); + mutex_unlock(&store); - debugmsg(Mstr("Anticipated connections for back end ") + Mstr(b) + ": " + - Mstr(ret) + "\n"); + debugmsg("Anticipated connections for back end " << b << ": " << + ret << '\n'); return ret; } diff --git a/xr/ipstore/clear.cc b/xr/ipstore/clear.cc @@ -1,9 +1,8 @@ #include "ipstore" void IPStore::clear(struct in_addr clientip) { - debugmsg(Mstr("Erasing IP entry of ") + - Mstr(inet_ntoa(clientip)) + "\n"); - Mutex::lock(&store); + debugmsg("Erasing IP entry of " << inet2string(clientip) << '\n'); + mutex_lock(&store); store.erase(clientip); - Mutex::unlock(&store); + mutex_unlock(&store); } diff --git a/xr/ipstore/clearoldest.cc b/xr/ipstore/clearoldest.cc @@ -5,7 +5,7 @@ void IPStore::clearoldest() { StoreMap::iterator oldest_entry; bool found = false; - Mutex::lock(&store); + mutex_lock(&store); dump(); @@ -24,13 +24,13 @@ void IPStore::clearoldest() { if (found) { if (config.debug()) { Timestamp tm((*oldest_entry).second.lastaccess); - _debugmsg(Mstr("Erasing oldest IP store entry: ") + - Mstr(inet_ntoa(oldest_entry->first)) + " on " + - tm.desc() + "\n"); + debugmsg("Erasing oldest IP store entry: " << + inet2string(oldest_entry->first) << " on " << + tm.desc() << '\n'); } store.erase(oldest_entry); } - Mutex::unlock(&store); + mutex_unlock(&store); dump(); } diff --git a/xr/ipstore/dump.cc b/xr/ipstore/dump.cc @@ -4,15 +4,15 @@ void IPStore::dump() { if (!config.debug()) return; - _debugmsg(Mstr("IPStore dump:\n")); + debugmsg("IPStore dump:\n"); for (StoreMap::iterator iter = store.begin(); iter != store.end(); iter++) { Timestamp tm((*iter).second.lastaccess); ostringstream o; - o << "Client IP " << inet_ntoa(iter->first) << " on " + o << "Client IP " << inet2string(iter->first) << " on " << tm.desc() << " to back end " << (*iter).second.targetbackend << '\n'; - _debugmsg(o.str()); + debugmsg(o.str()); } } diff --git a/xr/ipstore/target.cc b/xr/ipstore/target.cc @@ -11,10 +11,10 @@ int IPStore::target(struct in_addr clientip) { if (store.count(clientip) > 0) { if (config.verbose()) { Timestamp tm(store[clientip].lastaccess); - msg(Mstr("Client IP ") + Mstr(inet_ntoa(clientip)) + - " last visited on " + tm.desc() + " and went to " + - balancer.backend(store[clientip].targetbackend).description() + - "\n"); + msg("Client IP " << inet2string(clientip) << + " last visited on " << tm.desc() << " and went to " << + balancer.backend(store[clientip].targetbackend).description() + << '\n'); } return store[clientip].targetbackend; } diff --git a/xr/ipstore/weed.cc b/xr/ipstore/weed.cc @@ -4,7 +4,7 @@ void IPStore::weed() { time_t now = time(0); bool done = false; - Mutex::lock(&store); + mutex_lock(&store); while (!done) { done = true; @@ -14,9 +14,8 @@ void IPStore::weed() { if (now - ((*iter).second.lastaccess) > config.ipstoretimeout()) { if (config.debug()) { Timestamp tm((*iter).second.lastaccess); - _debugmsg (Mstr("Stale entry: ") + Mstr(inet_ntoa(iter->first)) + - Mstr(" visited on ") + tm.desc() + - ", erasing\n"); + debugmsg ("Stale entry: " << inet2string(iter->first) << + " visited on " << tm.desc() << ", erasing\n"); } done = false; store.erase(iter); @@ -25,5 +24,5 @@ void IPStore::weed() { } } - Mutex::unlock(&store); + mutex_unlock(&store); } diff --git a/xr/memory/memdisplay.cc b/xr/memory/memdisplay.cc @@ -1,13 +1,13 @@ #include "memory" void Memory::mem_display() { - Mutex::lock(&s_memlog); + mutex_lock(&s_memlog); for (unsigned i = 0; i < s_memlog.size(); i++) { MemoryEntry ent = s_memlog[i]; - Mutex::lock(&cout); + mutex_lock(&cout); cout << "Memory::mem_display " << ent.ptr << ' ' << ent.sz << ' ' << ent.desc << '\n'; - Mutex::unlock(&cout); + mutex_unlock(&cout); } - Mutex::unlock(&s_memlog); + mutex_unlock(&s_memlog); } diff --git a/xr/memory/memfree.cc b/xr/memory/memfree.cc @@ -5,19 +5,19 @@ void Memory::free(void *ptr) { return; for (unsigned i = 0; i < s_memlog.size(); i++) { - Mutex::lock(&s_memlog); + mutex_lock(&s_memlog); MemoryEntry ent = s_memlog[i]; - Mutex::unlock(&s_memlog); + mutex_unlock(&s_memlog); if (ent.ptr == ptr) { if (s_follow) { - Mutex::lock(&cout); + mutex_lock(&cout); cout << "Memory::free(" << ptr << ")\n"; - Mutex::unlock(&cout); + mutex_unlock(&cout); } ::free (ent.ptr); - Mutex::lock(&s_memlog); + mutex_lock(&s_memlog); s_memlog.erase(s_memlog.begin() + i); - Mutex::unlock(&s_memlog); + mutex_unlock(&s_memlog); return; } } diff --git a/xr/memory/memmalloc.cc b/xr/memory/memmalloc.cc @@ -3,14 +3,14 @@ void *Memory::malloc(size_t sz, string const &desc) { void *ptr = ::malloc(sz); MemoryEntry ent = { ptr, sz, desc }; - Mutex::lock(&s_memlog); + mutex_lock(&s_memlog); s_memlog.push_back(ent); - Mutex::unlock(&s_memlog); + mutex_unlock(&s_memlog); if (s_follow) { - Mutex::lock(&cout); + mutex_lock(&cout); cout << "Memory::malloc(" << sz << ") -> " << ptr << ' ' << desc << '\n'; - Mutex::unlock(&cout); + mutex_unlock(&cout); } return ptr; } diff --git a/xr/memory/memmark.cc b/xr/memory/memmark.cc @@ -2,7 +2,7 @@ void Memory::mem_mark(string const &desc) { MemoryEntry ent = { 0, 0, "MARK " + desc }; - Mutex::lock(&s_memlog); + mutex_lock(&s_memlog); s_memlog.push_back(ent); - Mutex::unlock(&s_memlog); + mutex_unlock(&s_memlog); } diff --git a/xr/memory/memrealloc.cc b/xr/memory/memrealloc.cc @@ -11,14 +11,14 @@ void *Memory::realloc(void *ptr, size_t newsz, string const &desc) { ent.ptr = ::realloc(ptr, newsz); ent.sz = newsz; ent.desc = desc; - Mutex::lock(&s_memlog); + mutex_lock(&s_memlog); s_memlog[i] = ent; - Mutex::unlock(&s_memlog); + mutex_unlock(&s_memlog); if (s_follow) { - Mutex::lock(&cout); + mutex_lock(&cout); cout << "Memory::realloc(" << ptr << ", " << newsz << ") -> " << ent.ptr << ' ' << desc << '\n'; - Mutex::unlock(&cout); + mutex_unlock(&cout); } return ent.ptr; } diff --git a/xr/mstr/mstr b/xr/mstr/mstr @@ -1,57 +0,0 @@ -#ifndef _MSTR_ -#define _MSTR_ - -#include "sys/sys" - -class Mstr: public string { -public: - Mstr(string s): string(s) {} - Mstr(char const *s): string(s) {} - Mstr(int i) { - ostringstream o; - o << i; - *this = o.str(); - } - Mstr const &operator+ (int i) { - ostringstream o; - o << i; - *this += o.str(); - return *this; - } - Mstr const &operator+ (unsigned i) { - ostringstream o; - o << i; - *this += o.str(); - return *this; - } - Mstr const &operator+ (time_t i) { - ostringstream o; - o << i; - *this += o.str(); - return *this; - } - Mstr const &operator+ (double i) { - ostringstream o; - o << i; - *this += o.str(); - return *this; - } - Mstr const &operator+(string const &s) { - *this += s; - return *this; - } - Mstr const &operator+(void const *p) { - ostringstream o; - o << p; - *this += o.str(); - return *this; - } - Mstr const &operator+(rlim_t r) { - ostringstream o; - o << r; - *this += o.str(); - return *this; - } -}; - -#endif diff --git a/xr/netbuffer/checkspace.cc b/xr/netbuffer/checkspace.cc @@ -11,7 +11,7 @@ void Netbuffer::check_space(unsigned extra) { if (extra == config.buffersize() && config.stype() == Servertype::t_http) buf_alloced <<= 1; - debugmsg (Mstr("Netbuffer: reserving ") + buf_alloced + + debugmsg("Netbuffer: reserving " << buf_alloced << " bytes for network buffer\n"); LOCK_MALLOC; buf_data = (char*)malloc(buf_alloced); @@ -19,9 +19,9 @@ void Netbuffer::check_space(unsigned extra) { if (! buf_data) throw Error("Memory fault in Netbuffer::check_space"); } else if (buf_sz + extra > buf_alloced) { - debugmsg((Mstr("Netbuffer: reallocating net buffer from ") + - buf_alloced) + - (Mstr(" to ") + (buf_alloced + extra)) + " bytes\n"); + debugmsg("Netbuffer: reallocating net buffer from " << + buf_alloced << " to " << + (buf_alloced + extra) << " bytes\n"); buf_alloced += extra; LOCK_MALLOC; buf_data = (char*)realloc(buf_data, buf_alloced); diff --git a/xr/netbuffer/destroy.cc b/xr/netbuffer/destroy.cc @@ -1,8 +1,7 @@ #include "netbuffer" void Netbuffer::destroy() { - debugmsg(Mstr("Netbuffer: destroying ") + Mstr(buf_alloced) + - Mstr( " bytes\n")); + debugmsg("Netbuffer: destroying " << buf_alloced << " bytes\n"); free(buf_data); buf_data = 0; buf_sz = 0; diff --git a/xr/netbuffer/insertat.cc b/xr/netbuffer/insertat.cc @@ -2,12 +2,17 @@ bool Netbuffer::insertat(unsigned index, char const *s, unsigned len) { PROFILE("Netbuffer::insertat"); - debugmsg(Mstr("Netbuffer: inserting ") + Mstr(s) + Mstr(" at ") + - Mstr(index) + "\n"); if (!len) len = strlen(s); + if (config.debug()) { + string pr; + for (unsigned int i = 0; i < len; i++) + pr += printable(s[i]); + debugmsg("Netbuffer: inserting " << pr << " at " << index << '\n'); + } + if (index >= buf_sz) return false; check_space(len); diff --git a/xr/netbuffer/netbuffer b/xr/netbuffer/netbuffer @@ -13,8 +13,8 @@ /* A few defs when malloc() / realloc() are suspected to be not thread-safe. * The defines are used in eg. copy() and check_space(). */ #ifdef MISTRUST_MALLOC_THREADSAFE -#define LOCK_MALLOC Mutex::lock((void*)malloc) -#define UNLOCK_MALLOC Mutex::unlock((void*)malloc) +#define LOCK_MALLOC mutex_lock((void*)malloc) +#define UNLOCK_MALLOC mutex_unlock((void*)malloc) #else #define LOCK_MALLOC #define UNLOCK_MALLOC diff --git a/xr/netbuffer/netbuffer1.cc b/xr/netbuffer/netbuffer1.cc @@ -1,5 +1,5 @@ #include "netbuffer" Netbuffer::Netbuffer(): buf_data(0), buf_sz(0), buf_alloced(0) { - debugmsg(Mstr("Netbuffer: creating zero size buffer\n")); + debugmsg("Netbuffer: creating zero size buffer\n"); } diff --git a/xr/netbuffer/netread.cc b/xr/netbuffer/netread.cc @@ -8,9 +8,8 @@ unsigned Netbuffer::netread (int fd, int timeout) { set.add(fd); set.wait_r(); if (! set.readable(fd)) { - msg(Mstr("Fd ") + Mstr(fd) + - Mstr(" failed to become readable within ") + Mstr(timeout) + - Mstr(" sec")); + msg("Fd "<< fd << " failed to become readable within " << + timeout << " sec\n"); return 0; } } @@ -21,7 +20,7 @@ unsigned Netbuffer::netread (int fd, int timeout) { // because it's quite common (too much logging otherwise). ssize_t nread = read (fd, buf_data + buf_sz, config.buffersize()); if (nread < 0) { - msg(Mstr("Read failed on fd ") + fd + ": " + strerror(errno)); + msg("Read failed on fd " << fd + ": " << strerror(errno) << '\n'); return 0; } buf_sz += nread; @@ -32,7 +31,7 @@ unsigned Netbuffer::netread (int fd, int timeout) { for (unsigned i = 0; i < (unsigned)nread; i++) o << printable(buf_data[i]); o << "\n"; - _debugmsg (o.str()); + debugmsg (o.str()); } return nread; diff --git a/xr/netbuffer/netwrite.cc b/xr/netbuffer/netwrite.cc @@ -4,9 +4,8 @@ unsigned Netbuffer::netwrite (int fd, int timeout) const { PROFILE("Netbuffer::netwrite"); - debugmsg((Mstr("About to write ") + buf_sz) + - (Mstr(" bytes to fd ") + fd) + - (Mstr(", timeout ") + timeout) + "\n"); + debugmsg("About to write " << buf_sz << " buytes to fd " << fd + << ", timeout " << timeout << '\n'); if (!buf_sz) return (0); @@ -17,10 +16,10 @@ unsigned Netbuffer::netwrite (int fd, int timeout) const { of << config.dumpdir() << "/" << balancer.requestnr() << "." << fd; FILE *f; if ( (!(f = fopen (of.str().c_str(), "a"))) && - (!(f = fopen (of.str().c_str(), "w"))) ) - warnmsg ("Cannot write traffic log " + of.str() + ": " + - strerror(errno) + "\n"); - else { + (!(f = fopen (of.str().c_str(), "w"))) ) { + warnmsg("Cannot write traffic log " << of.str() << ": " << + strerror(errno) << '\n'); + } else { fwrite (buf_data, 1, buf_sz, f); fclose (f); } @@ -65,11 +64,11 @@ unsigned Netbuffer::netwrite (int fd, int timeout) const { for (unsigned i = totwritten; i < totwritten + nwritten; i++) o << printable(buf_data[i]); o << "\n"; - _debugmsg (o.str()); + debugmsg(o.str()); } totwritten += nwritten; } else if (errno == EINVAL || errno == EINPROGRESS) { - msg(Mstr("Write warning: ") + Mstr(strerror(errno)) + "\n"); + msg("Write warning: " << strerror(errno) << '\n'); } else { ostringstream o; o << "Write/send failed: errno=" << int(errno) << ", " diff --git a/xr/netbuffer/opassign.cc b/xr/netbuffer/opassign.cc @@ -1,7 +1,7 @@ #include "netbuffer" Netbuffer const &Netbuffer::operator= (Netbuffer const &other) { - debugmsg(Mstr("Netbuffer: copying other\n")); + debugmsg("Netbuffer: copying other\n"); if (this != &other) { destroy(); copy (other); diff --git a/xr/netbuffer/setstring.cc b/xr/netbuffer/setstring.cc @@ -1,7 +1,7 @@ #include "netbuffer" void Netbuffer::setstring(string const &s) { - debugmsg(Mstr("Netbuffer: setting to string\n")); + debugmsg("Netbuffer: setting to string\n"); destroy(); check_space(s.size() + 1); diff --git a/xr/sys/anymsg.cc b/xr/sys/anymsg.cc @@ -1,17 +0,0 @@ -#include "sys" -#include "config/config" -#include "ThreadsAndMutexes/mutex/mutex" -#include "profiler/profiler" -#include "mstr/mstr" -#include "timestamp/timestamp" - -void anymsg (Mstr const &s, ostream &o, string const &label) { - Mutex::lock(&o); - if (config.prefixtimestamp()) { - Timestamp tm; - o << tm.desc() << ' '; - } - o << pthread_self() << ' ' << label << ": " << s; - o.flush(); - Mutex::unlock(&o); -} diff --git a/xr/sys/debugmsg.cc b/xr/sys/debugmsg.cc @@ -1,11 +0,0 @@ -#include "sys" -#include "config/config" -#include "ThreadsAndMutexes/mutex/mutex" -#include "profiler/profiler" -#include "mstr/mstr" -#include "timestamp/timestamp" - -void _debugmsg (Mstr const &s) { - PROFILE("debugmsg"); - anymsg(s, cerr, "DEBUG"); -} diff --git a/xr/sys/inet2string.cc b/xr/sys/inet2string.cc @@ -0,0 +1,12 @@ +#include "sys/sys" +#include "ThreadsAndMutexes/mutex/mutex" + +string inet2string(struct in_addr in) { + string ret; + + mutex_lock((void*)inet_ntoa); + ret = inet_ntoa(in); + mutex_unlock((void*)inet_ntoa); + + return ret; +} diff --git a/xr/sys/ipmatch.cc b/xr/sys/ipmatch.cc @@ -9,9 +9,9 @@ bool ipmatch (struct in_addr adr, struct in_addr mask) { memcpy (&lmask, &mask, sizeof(mask)); bool match = ( (laddr & lmask) == laddr ); - debugmsg ("Matching ip " + (string)inet_ntoa(adr) + " against mask " + - (string)inet_ntoa(mask) + ": " + - (match ? "match" : "miss") + "\n"); + debugmsg("Matching ip " << inet2string(adr) << " against mask " << + inet2string(mask) << ": " << + (match ? "match" : "miss") << '\n'); return (match); } diff --git a/xr/sys/main.cc b/xr/sys/main.cc @@ -49,7 +49,7 @@ static void showlimits() { static int org_argc; static char **org_argv; static void sigcatcher (int sig) { - debugmsg ("Seen signal " + sig + '\n'); + debugmsg("Seen signal " << sig << '\n'); switch (sig) { case SIGHUP: /* Generate a report to the log. Somewhat stale given the @@ -81,7 +81,7 @@ int main (int argc, char **argv) { if (config.verbose()) showlimits(); - msg ((Mstr("XR running as PID ") + getpid()) + "\n"); + msg("XR running as PID " << getpid() << '\n'); // Load the signal handler. for (unsigned i = 0; i < sizeof(relevant_sig) / sizeof(int); i++) diff --git a/xr/sys/msg.cc b/xr/sys/msg.cc @@ -1,11 +0,0 @@ -#include "sys" -#include "config/config" -#include "ThreadsAndMutexes/mutex/mutex" -#include "profiler/profiler" -#include "mstr/mstr" -#include "timestamp/timestamp" - -void _msg (Mstr const &s) { - PROFILE("msg"); - anymsg(s, cerr, "INFO"); -} diff --git a/xr/sys/mtrand.cc b/xr/sys/mtrand.cc @@ -1,9 +1,11 @@ /* - NOTE: All of the functions have been commented out, with two exceptions: + NOTE: All of the functions have been commented out, with two + exceptions: - init_genrand(seed) has been renamed to mt_srand(seed) - genrand_int32(void) has been renamed to mt_rand(void) - The renaming was to resemble the naming of srand() and rand(). All other - functions were unnecessary, and as such commented out. + The renaming was to resemble the naming of srand() and rand(). + All other functions were unnecessary, and as such commented out. + -- KK */ @@ -36,7 +38,8 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR @@ -58,8 +61,9 @@ #define UPPER_MASK 0x80000000UL /* most significant w-r bits */ #define LOWER_MASK 0x7fffffffUL /* least significant r bits */ -static unsigned long mt[N]; /* the array for the state vector */ -static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */ +static unsigned long mt[N + M]; /* the array for the state vector */ +static int mti = N + 1; /* mti == N+1 means: */ + /* mt[N] is not initialized */ /* initializes mt[N] with a seed */ void mt_srand(unsigned long s) @@ -116,10 +120,10 @@ unsigned long mt_rand(void) if (mti >= N) { /* generate N words at one time */ int kk; - if (mti == N+1) /* if init_genrand() has not been called, */ - mt_srand(5489UL); /* a default initial seed is used */ + if (mti == N+1) /* if init_genrand() has not been called, */ + mt_srand(5489UL); /* a default initial seed is used */ - for (kk=0;kk<N-M;kk++) { + for (kk = 0; kk < N - M; kk++) { y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL]; } diff --git a/xr/sys/mutexlock.cc b/xr/sys/mutexlock.cc @@ -0,0 +1,28 @@ +#include "sys" +#include "ThreadsAndMutexes/mutextable/mutextable" +#include "ThreadsAndMutexes/mutex/mutex" + +static MutexTable mt(100); + +void mutex_lock(void *o) { + mt.lock(o); +} + +void mutex_unlock(void *o) { + mt.unlock(o); +} + +static Mutex cout_lock, cerr_lock; + +bool mutex_lock_cout() { + return cout_lock.trylock(); +} +void mutex_unlock_cout() { + cout_lock.unlock(); +} +bool mutex_lock_cerr() { + return cerr_lock.trylock(); +} +void mutex_unlock_cerr() { + cerr_lock.unlock(); +} diff --git a/xr/sys/reportmsg.cc b/xr/sys/reportmsg.cc @@ -1,9 +0,0 @@ -#include "sys" -#include "config/config" -#include "ThreadsAndMutexes/mutex/mutex" -#include "mstr/mstr" -#include "timestamp/timestamp" - -void reportmsg (Mstr const &s) { - anymsg(s, cerr, "REPORT"); -} diff --git a/xr/sys/socketclose.cc b/xr/sys/socketclose.cc @@ -5,7 +5,7 @@ void socketclose (int fd) { PROFILE("socketclose"); if (fd > 2) { - debugmsg ((Mstr("Closing socket ") + fd) + "\n"); + debugmsg("Closing socket " << fd << '\n'); if (config.fastclose()) { struct linger l; diff --git a/xr/sys/sys b/xr/sys/sys @@ -68,23 +68,14 @@ using namespace std; -// This we need locally for msg(), debugmsg() -#include "mstr/mstr" // This is for the Servertype of serversocket() #include "servertype/servertype" -/* Messaging. Conditionals are defined as a macro to speed things up. */ -void _msg (Mstr const &s); -#define msg(x) if(config.verbose()) _msg(x) -void _debugmsg (Mstr const &s); -#define debugmsg(x) if (config.debug()) _debugmsg(x) -void reportmsg (Mstr const &s); -void warnmsg (Mstr const &s); -void anymsg(Mstr const &s, ostream &o, string const &label); - -/* Other */ + +/* Generic funtions */ int serversocket (string addr, int port, string description, Servertype::Type t); +string inet2string(struct in_addr in); bool ipmatch (struct in_addr addr, struct in_addr mask); void socketclose (int fd); vector<string> str2parts (string const &s, char sep); @@ -94,6 +85,13 @@ bool check_acl(string const &ipstr, struct in_addr ipaddr); int sysrun (string const &s); int maxtimeout(int a, int b); +void mutex_lock(void *obj); +void mutex_unlock(void *obj); +bool mutex_lock_cout(); +void mutex_unlock_cout(); +bool mutex_lock_cerr(); +void mutex_unlock_cerr(); + #ifndef HAVE_INET_ATON int inet_aton (char const *name, struct in_addr *addr); #endif @@ -102,4 +100,45 @@ int inet_aton (char const *name, struct in_addr *addr); char *strnstr (char const *s, char const *find, size_t slen); #endif +/* Messaging. Conditionals are defined as a macro to speed things up. */ +#define msg(x) \ +if (config.debug() && mutex_lock_cout()) { \ + if (config.prefixtimestamp()) { \ + Timestamp tm; \ + cout << tm.desc() << ' '; \ + } \ + cout << pthread_self() << " INFO: " << x; \ + cout.flush(); \ + mutex_unlock_cout(); \ +} +#define debugmsg(x) \ +if (config.debug() && mutex_lock_cout()) { \ + if (config.prefixtimestamp()) { \ + Timestamp tm; \ + cout << tm.desc() << ' '; \ + } \ + cout << pthread_self() << " DEBUG: " << x; \ + cout.flush(); \ + mutex_unlock_cout(); \ +} +#define reportmsg(x) \ +if (mutex_lock_cerr()) { \ + if (config.prefixtimestamp()) { \ + Timestamp tm; \ + cerr << tm.desc() << ' '; \ + } \ + cerr << pthread_self() << " REPORT " << x; \ + mutex_unlock_cerr(); \ +} +#define warnmsg(x) \ +if (mutex_lock_cerr()) { \ + if (config.prefixtimestamp()) { \ + Timestamp tm; \ + cerr << tm.desc() << ' '; \ + } \ + cerr << pthread_self() << " WARNING " << x; \ + mutex_unlock_cerr(); \ +} + #endif + diff --git a/xr/sys/sysrun.cc b/xr/sys/sysrun.cc @@ -4,19 +4,18 @@ int sysrun(string const &s) { int ret = system(s.c_str()); if (ret == -1) { - warnmsg(Mstr("Failed to start command: ") + s + "\n"); + warnmsg("Failed to start command: " << s << '\n'); return -1; } if (WIFEXITED(ret)) { int stat = WEXITSTATUS(ret); - if (stat) - warnmsg(Mstr("Command" ) + s + - Mstr(" exited with status ") + Mstr(stat) + "\n"); - else - msg(Mstr("Command ") + s + - Mstr(" terminated normally.\n")); + if (stat) { + warnmsg("Command" << s << " exited with status " << stat << '\n'); + } else { + msg("Command " << s << " terminated normally\n"); + } return stat; } - warnmsg(Mstr("Command ") + s + Mstr(" failed miserably!\n")); + warnmsg("Command " << s << " failed miserably!\n"); return ret; } diff --git a/xr/sys/warnmsg.cc b/xr/sys/warnmsg.cc @@ -1,9 +0,0 @@ -#include "sys" -#include "config/config" -#include "ThreadsAndMutexes/mutex/mutex" -#include "mstr/mstr" -#include "timestamp/timestamp" - -void warnmsg (Mstr const &s) { - anymsg(s, cerr, "WARNING"); -} diff --git a/xr/webinterface/answer.cc b/xr/webinterface/answer.cc @@ -3,9 +3,9 @@ static void stop_backend_thread(pthread_t id) { Threadinfo info = Threadlist::info(id); - msg((Mstr("Stopping thread ") + id) + - (Mstr(" (backend socket ") + info.backendfd()) + - (Mstr(", client socket ") + info.clientfd()) + ")\n"); + msg("Stopping thread " << id << + " (backend socket " << info.backendfd() << + ", client socket " << info.clientfd() + ")\n"); socketclose(info.backendfd()); socketclose(info.clientfd()); Threadlist::deregister(id); diff --git a/xr/webinterface/answerstatus.cc b/xr/webinterface/answerstatus.cc @@ -56,7 +56,7 @@ void Webinterface::answer_status() { o << " <allowfrom>\n" " <nr>" << i << "</nr>\n" - " <mask>" << inet_ntoa(config.allow(i)) << "</mask>\n" + " <mask>" << inet2string(config.allow(i)) << "</mask>\n" " </allowfrom>\n"; o << " </allow>\n" @@ -65,7 +65,7 @@ void Webinterface::answer_status() { o << " <denyfrom>\n" " <nr>" << i << "</nr>\n" - " <mask>" << inet_ntoa(config.deny(i)) << "</mask>\n" + " <mask>" << inet2string(config.deny(i)) << "</mask>\n" " </denyfrom>\n"; o << " </deny>\n" @@ -139,7 +139,7 @@ void Webinterface::answer_status() { o << "</address>\n" " <duration>" << thread_info.timestamp().elapsed() << "</duration>\n" - " <clientip>" << inet_ntoa(thread_info.clientip()) << "</clientip>\n" + " <clientip>" << inet2string(thread_info.clientip()) << "</clientip>\n" " </thread>\n"; } /* The estimate of the number of used fd's is: diff --git a/xr/webinterface/execute.cc b/xr/webinterface/execute.cc @@ -11,7 +11,7 @@ void Webinterface::execute() { // so we just retry for a bit. while (true) { try { - msg ("Starting web interface\n"); + msg("Starting web interface\n"); sfd = serversocket (config.webinterfaceip(), config.webinterfaceport(), "web interface", Servertype::t_tcp); @@ -23,7 +23,7 @@ void Webinterface::execute() { break; } - msg ((Mstr("Web interface started on socket ") + sfd) + "\n"); + msg("Web interface started on socket " << sfd << "\n"); while (!balancer.terminate()) { try { Fdset fdset(0); @@ -33,11 +33,10 @@ void Webinterface::execute() { int size; struct sockaddr_in clname; if ( (cfd = accept (sfd, (struct sockaddr *) &clname, - (socklen_t *)&size)) < 0 ) - warnmsg(Mstr("Web interface: failed to accept " - "network connection: ") + - Mstr(strerror(errno)) + "\n"); - else { + (socklen_t *)&size)) < 0 ) { + warnmsg("Web interface: failed to accept network " + "connection: " << strerror(errno) << '\n'); + } else { serve (); socketclose(cfd); } @@ -61,6 +60,6 @@ void Webinterface::execute() { socketclose(cfd); } } - msg ("Web interface stopping.\n"); + msg("Web interface stopping.\n"); socketclose(sfd); } diff --git a/xr/webinterface/serve.cc b/xr/webinterface/serve.cc @@ -1,11 +1,11 @@ #include "webinterface" void Webinterface::serve () { - msg ((Mstr("Webinterface serving request on client fd ") + cfd) + "\n"); + msg("Webinterface serving request on client fd " << cfd << '\n'); Httpbuffer clientrequest; clientrequest.netread(cfd, config.client_read_timeout()); - msg ("Webinterface request: " + clientrequest.firstline() + "\n"); + msg("Webinterface request: " << clientrequest.firstline() << '\n'); answer(clientrequest); } diff --git a/xr/webinterface/webinterface1.cc b/xr/webinterface/webinterface1.cc @@ -2,7 +2,7 @@ Webinterface::~Webinterface() { if (cfd) { - msg ((Mstr("Stopping web interface socket ") + sfd) + "\n"); + msg("Stopping web interface socket " << sfd << '\n'); socketclose(sfd); } } diff --git a/xrctl/xrctl b/xrctl/xrctl @@ -420,6 +420,11 @@ sub msg { sub find_bin { my $bin = shift; my @parts = split (/\s/, $bin); + + if (substr($parts[0], 0, 1) eq '/' and -x $parts[0]) { + msg("Binary '$bin' is executable as-is\n"); + return $bin; + } for my $d (split (/:/, $sysconf{path})) { if (-x "$d/$parts[0]" and -f "$d/$parts[0]") { msg ("Binary '$parts[0]' found as '$d/$parts[0]'\n");