1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
|
/*
nutwriter.cpp - NUT writer
Copyright (C) 2012 Eaton
Author: Vaclav Krpec <VaclavKrpec@Eaton.com>
Copyright (C) 2024-2025 NUT Community
Author: Jim Klimov <jimklimov+nut@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "config.h"
#include "nutwriter.hpp"
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <list>
#include <map>
#include <cassert>
#include <typeinfo>
/**
* \brief NUT configuration directive generator
*
* The macro is used to simplify generation of
* NUT config. directives.
*
* IMPORTANT NOTE:
* In case of writing error, the macro causes immediate
* return from the calling function (propagating the writing status).
*
* \param name Directive name
* \param arg_t Directive argument implementation type
* \param arg Directive argument
* \param quote_arg Boolean flag; check to quote the argument
*/
#define CONFIG_DIRECTIVEX(name, arg_t, arg, quote_arg) \
do { \
if ((arg).set()) { \
const arg_t & arg_val = (arg); \
std::stringstream ss; \
ss << name << ' '; \
if (quote_arg) \
ss << '"'; \
ss << arg_val; \
if (quote_arg) \
ss << '"'; \
status_t status = writeDirective(ss.str()); \
if (NUTW_OK != status) \
return status; \
} \
} while (0)
/**
* \brief Shell (envvar) configuration directive generator
*
* The macro is used to simplify generation of
* nut.conf file directives.
*
* IMPORTANT NOTE:
* In case of writing error, the macro causes immediate
* return from the calling function (propagating the writing status).
*
* \param name Directive name
* \param arg_t Directive argument implementation type
* \param arg Directive argument
* \param quote_arg Boolean flag; check to quote the argument
*/
// NOTE: Due to this being a macro applied to any argument type,
// implementation for e.g. bool handling jumps through hoops like
// stringification and back. FIXME: working optimization welcome.
#define SHELL_CONFIG_DIRECTIVEX(name, arg_t, arg, quote_arg) \
do { \
if ((arg).set()) { \
const arg_t & arg_val = (arg); \
std::stringstream ss; \
ss << name << '='; \
if (quote_arg) \
ss << '\''; \
if (typeid(arg_val) == typeid(bool&)) { \
std::stringstream ssb; \
ssb << arg_val; \
std::string sb = ssb.str(); \
if ("1" == sb) { ss << "true"; } \
else if ("0" == sb) { ss << "false"; } \
else { ss << arg_val; } \
} else \
ss << arg_val; \
if (quote_arg) \
ss << '\''; \
status_t status = writeDirective(ss.str()); \
if (NUTW_OK != status) \
return status; \
} \
} while (0)
namespace nut {
/* Trivial implementations out of class declaration to avoid
* error: 'ClassName' has no out-of-line virtual method definitions; its vtable
* will be emitted in every translation unit [-Werror,-Wweak-vtables]
*/
NutConfigWriter::~NutConfigWriter() {} // generic interface/base class
// Flat-config classes:
NutConfConfigWriter::~NutConfConfigWriter() {} // nut.conf, shell format
UpsmonConfigWriter::~UpsmonConfigWriter() {} // upsmon.conf
UpsdConfigWriter::~UpsdConfigWriter() {} // upsd.conf
// Structured-config classes R/W is handled via GenericConfiguration:
// UpsConfiguration: ups.conf
// UpsdUsersConfiguration: upsd.users
// Not handled currently:
// xxx: upssched.conf
// xxx: upsset.conf
// xxx: hosts.conf
// End-of-Line separators (arch. dependent)
/** UNIX style EoL */
static const std::string LF("\n");
// TODO: Make a compile-time selection
#if (0)
// M$ Windows EoL
static const std::string CRLF("\r\n");
// Apple MAC EoL
static const std::string CR("\r");
#endif // end of #if (0)
const std::string & NutWriter::eol(LF);
const std::string GenericConfigWriter::s_default_section_entry_indent("\t");
const std::string GenericConfigWriter::s_default_section_entry_separator(" = ");
/**
* \brief NSS certificate identity serializer
*
* \param ident Certificate identity object
*
* \return Serialized certificate identity
*/
static std::string serializeCertIdent(const nut::CertIdent & ident) {
std::stringstream directive;
const std::string & val1 = (ident.certName), val2 = (ident.certDbPass);
directive << "CERTIDENT \"" << val1 << "\" \"" << val2 << "\"";
return directive.str();
}
/**
* \brief NSS certificate-protected host info serializer
*
* \param certHost Certificate-protected host info object
*
* \return Serialized certificate-protected host info
*/
static std::string serializeCertHost(const nut::CertHost & certHost) {
std::stringstream directive;
const std::string & val1 = (certHost.host), val2 = (certHost.certName);
directive << "CERTHOST \"" << val1 << "\" \"" << val2 << "\"";
// Spec says to write these as 0/1 integers
nut::BoolInt bi;
int i;
// NOTE: After copy-assignments below (which inherit original strictness),
// need to add relaxed mode for 0/1 as false/true handling:
//bi.bool01 = true;
// Avoid static analysis concerns that the internal _value
// "may be used uninitialized in this function" (ETOOSMART):
bi = false;
// Assumed to be set() - exception otherwise
bi = certHost.certVerify;
bi.bool01 = true;
i = bi;
directive << " " << i;
bi = certHost.forceSsl;
bi.bool01 = true;
i = bi;
directive << " " << i;
return directive.str();
}
NutWriter::status_t NutWriter::writeEachLine(const std::string & str, const std::string & pref) {
for (size_t pos = 0; pos < str.size(); ) {
// Prefix every line
status_t status = write(pref);
if (NUTW_OK != status)
return status;
// Write up to the next EoL (or till the end)
size_t eol_pos = str.find(eol, pos);
if (str.npos == eol_pos)
return write(str.substr(pos) + eol);
eol_pos += eol.size();
status = write(str.substr(pos, eol_pos));
if (NUTW_OK != status)
return status;
// Update position
pos = eol_pos;
}
return NUTW_OK;
}
NutWriter::status_t SectionlessConfigWriter::writeDirective(const std::string & str) {
return write(str + eol);
}
NutWriter::status_t SectionlessConfigWriter::writeComment(const std::string & str) {
return writeEachLine(str, "# ");
}
NutWriter::status_t SectionlessConfigWriter::writeSectionName(const std::string & name) {
std::string e("INTERNAL ERROR: Attempt to write section name ");
e += name + " to a section-less configuration file";
throw std::logic_error(e);
}
NutWriter::status_t NutConfConfigWriter::writeConfig(const NutConfiguration & config) {
// Mode
// TBD: How should I serialize an unknown mode?
if (config.mode.set()) {
status_t status;
std::string mode_str;
NutConfiguration::NutMode mode = config.mode;
switch (mode) {
case NutConfiguration::MODE_UNKNOWN:
// BEWARE! Intentional fall-through to MODE_NONE branch
case NutConfiguration::MODE_NONE:
mode_str = "none";
break;
case NutConfiguration::MODE_STANDALONE:
mode_str = "standalone";
break;
case NutConfiguration::MODE_NETSERVER:
mode_str = "netserver";
break;
case NutConfiguration::MODE_NETCLIENT:
mode_str = "netclient";
break;
case NutConfiguration::MODE_CONTROLLED:
mode_str = "controlled";
break;
case NutConfiguration::MODE_MANUAL:
mode_str = "manual";
break;
#if (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_PUSH_POP) && ( (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_COVERED_SWITCH_DEFAULT) || (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_UNREACHABLE_CODE) )
# pragma GCC diagnostic push
#endif
#ifdef HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_COVERED_SWITCH_DEFAULT
# pragma GCC diagnostic ignored "-Wcovered-switch-default"
#endif
#ifdef HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_UNREACHABLE_CODE
# pragma GCC diagnostic ignored "-Wunreachable-code"
#endif
/* Older CLANG (e.g. clang-3.4) seems to not support the GCC pragmas above */
#ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wunreachable-code"
# pragma clang diagnostic ignored "-Wcovered-switch-default"
#endif
default:
/* Must not occur. */
break;
#ifdef __clang__
# pragma clang diagnostic pop
#endif
#if (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_PUSH_POP) && ( (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_COVERED_SWITCH_DEFAULT) || (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_UNREACHABLE_CODE) )
# pragma GCC diagnostic pop
#endif
}
status = writeDirective("MODE=" + mode_str);
if (NUTW_OK != status)
return status;
}
#if (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_PUSH_POP) && (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_UNREACHABLE_CODE)
# pragma GCC diagnostic push
#endif
#ifdef HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_UNREACHABLE_CODE
# pragma GCC diagnostic ignored "-Wunreachable-code"
#endif
/* Older CLANG (e.g. clang-3.4) seems to not support the GCC pragmas above */
#ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wunreachable-code"
#endif
SHELL_CONFIG_DIRECTIVEX("ALLOW_NO_DEVICE", bool, config.allowNoDevice, false);
SHELL_CONFIG_DIRECTIVEX("ALLOW_NOT_ALL_LISTENERS", bool, config.allowNotAllListeners, false);
SHELL_CONFIG_DIRECTIVEX("UPSD_OPTIONS", std::string, config.upsdOptions, true);
SHELL_CONFIG_DIRECTIVEX("UPSMON_OPTIONS", std::string, config.upsmonOptions, true);
SHELL_CONFIG_DIRECTIVEX("POWEROFF_WAIT", unsigned int, config.poweroffWait, false);
SHELL_CONFIG_DIRECTIVEX("POWEROFF_QUIET", bool, config.poweroffQuiet, false);
SHELL_CONFIG_DIRECTIVEX("NUT_DEBUG_LEVEL", int, config.debugLevel, false);
#ifdef __clang__
# pragma clang diagnostic pop
#endif
#if (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_PUSH_POP) && (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_UNREACHABLE_CODE)
# pragma GCC diagnostic pop
#endif
return NUTW_OK;
}
/** Notify types & flags strings */
struct NotifyFlagsStrings {
// TBD: Shouldn't this mapping be shared with the parser?
// This is an obvious redundancy...
/** Notify type strings list */
typedef const char * TypeStrings[UpsmonConfiguration::NOTIFY_TYPE_MAX];
/** Notify flag strings map */
typedef std::map<UpsmonConfiguration::NotifyFlag, const char *> FlagStrings;
/** Notify type strings */
static const TypeStrings type_str;
/** Notify flag strings */
static const FlagStrings flag_str;
/**
* \brief Initialize notify flag strings
*
* \return Notify flag strings map
*/
static FlagStrings initFlagStrings() {
FlagStrings str;
str[UpsmonConfiguration::NOTIFY_IGNORE] = "IGNORE";
str[UpsmonConfiguration::NOTIFY_SYSLOG] = "SYSLOG";
str[UpsmonConfiguration::NOTIFY_WALL] = "WALL";
str[UpsmonConfiguration::NOTIFY_EXEC] = "EXEC";
return str;
}
}; // end of struct NotifyFlagsStrings
const NotifyFlagsStrings::TypeStrings NotifyFlagsStrings::type_str = {
"ONLINE", // NOTIFY_ONLINE
"ONBATT", // NOTIFY_ONBATT
"LOWBATT", // NOTIFY_LOWBATT
"FSD\t", // NOTIFY_FSD (including padding)
"COMMOK", // NOTIFY_COMMOK
"COMMBAD", // NOTIFY_COMMBAD
"SHUTDOWN", // NOTIFY_SHUTDOWN
"REPLBATT", // NOTIFY_REPLBATT
"NOCOMM", // NOTIFY_NOCOMM
"NOPARENT", // NOTIFY_NOPARENT
"CAL\t", // NOTIFY_CAL (including padding)
"NOTCAL", // NOTIFY_NOTCAL
"OFF\t", // NOTIFY_OFF (including padding)
"NOTOFF", // NOTIFY_NOTOFF
"BYPASS", // NOTIFY_BYPASS
"NOTBYPASS", // NOTIFY_NOTBYPASS
"ECO\t", // NOTIFY_ECO (including padding); NOTE: inverter mode, not ups state, for notifications
"NOTECO", // NOTIFY_NOTECO
"ALARM", // NOTIFY_ALARM
"NOTALARM", // NOTIFY_NOTALARM
"OVER", // NOTIFY_OVER
"NOTOVER", // NOTIFY_NOTOVER
"TRIM", // NOTIFY_TRIM
"NOTTRIM", // NOTIFY_NOTTRIM
"BOOST", // NOTIFY_BOOST
"NOTBOOST", // NOTIFY_NOTBOOST
"OTHER", // NOTIFY_OTHER
"NOTOTHER", // NOTIFY_NOTOTHER
"SUSPEND_STARTING", // NOTIFY_SUSPEND_STARTING
"SUSPEND_FINISHED", // NOTIFY_SUSPEND_FINISHED
};
const NotifyFlagsStrings::FlagStrings NotifyFlagsStrings::flag_str =
NotifyFlagsStrings::initFlagStrings();
/**
* \brief upsmon notify flags serializer
*
* \param type Notification type
* \param flags Notification flags
*
* \return NOTIFYFLAG directive string
*/
static std::string serializeNotifyFlags(UpsmonConfiguration::NotifyType type, unsigned int flags) {
static const NotifyFlagsStrings::FlagStrings::const_iterator ignore_str_iter =
NotifyFlagsStrings::flag_str.find(UpsmonConfiguration::NOTIFY_IGNORE);
static const std::string ignore_str(ignore_str_iter->second);
assert(type < UpsmonConfiguration::NOTIFY_TYPE_MAX);
std::string directive("NOTIFYFLAG ");
directive += NotifyFlagsStrings::type_str[type];
char separator = '\t';
// The IGNORE flag is actually no-flag case
if (UpsmonConfiguration::NOTIFY_IGNORE == flags) {
directive += separator;
directive += ignore_str;
return directive;
}
NotifyFlagsStrings::FlagStrings::const_iterator fl_iter =
NotifyFlagsStrings::flag_str.begin();
for (; fl_iter != NotifyFlagsStrings::flag_str.end(); ++fl_iter) {
if (fl_iter->first & flags) {
directive += separator;
directive += fl_iter->second;
separator = '+';
}
}
return directive;
}
/**
* \brief upsmon notify messages serializer
*
* \param type Notification type
* \param msg Notification message
*
* \return NOTIFYMSG directive string
*/
static std::string serializeNotifyMessage(UpsmonConfiguration::NotifyType type, const std::string & msg) {
assert(type < UpsmonConfiguration::NOTIFY_TYPE_MAX);
std::string directive("NOTIFYMSG ");
directive += NotifyFlagsStrings::type_str[type];
directive += '\t';
directive += '"' + msg + '"';
return directive;
}
/**
* \brief Get notify type successor
*
* TBD: Should be in nutconf.hpp
*
* \param type Notify type
*
* \return Notify type successor
*/
inline static UpsmonConfiguration::NotifyType nextNotifyType(UpsmonConfiguration::NotifyType type) {
assert(type < UpsmonConfiguration::NOTIFY_TYPE_MAX);
int type_ord = static_cast<int>(type);
return static_cast<UpsmonConfiguration::NotifyType>(type_ord + 1);
}
/**
* \brief Notify type pre-increment
*
* TBD: Should be in nutconf.hpp
*
* \param[in,out] type Notify type
*
* \return \c type successor
*/
inline static UpsmonConfiguration::NotifyType operator ++(UpsmonConfiguration::NotifyType & type) {
return type = nextNotifyType(type);
}
/**
* \brief Notify type post-increment
*
* TBD: Should be in nutconf.hpp
*
* \param[in,out] type Notify type
*
* \return \c type
*/
/* // CURRENTLY UNUSED
inline static UpsmonConfiguration::NotifyType operator ++(UpsmonConfiguration::NotifyType & type, int) {
UpsmonConfiguration::NotifyType type_copy = type;
type = nextNotifyType(type);
return type_copy;
}
*/
/**
* \brief UPS monitor definition serializer
*
* \param monitor Monitor
*
* \return Monitor config. directive
*/
static std::string serializeMonitor(const UpsmonConfiguration::Monitor & monitor) {
std::stringstream directive;
directive << "MONITOR ";
// System
directive << monitor.upsname << '@' << monitor.hostname;
if (monitor.port)
directive << ':' << monitor.port;
directive << ' ';
// Power value
directive << monitor.powerValue << ' ';
// Username & password
directive << monitor.username << ' ' << monitor.password << ' ';
// Primary/secondary (legacy master/slave)
directive << (monitor.isPrimary ? "primary" : "secondary");
/* NUT v2.7.4 and older: directive << (monitor.isPrimary ? "master" : "slave");*/
return directive.str();
}
NutWriter::status_t UpsmonConfigWriter::writeConfig(const UpsmonConfiguration & config) {
/**
* \brief upsmon directive generator
*
* The macro is locally used to simplify generation of
* upsmon config. directives (except those with enumerated
* arguments).
*
* NOTE that the macro may cause return from the function
* (upon writing error).
* See \ref CONFIG_DIRECTIVEX for more information.
*
* \param name Directive name
* \param arg_t Directive argument implementation type
* \param arg Directive argument
* \param quote_arg Boolean flag; check to quote the argument
*/
# define UPSMON_DIRECTIVEX(name, arg_t, arg, quote_arg) \
CONFIG_DIRECTIVEX(name, arg_t, arg, quote_arg)
/* The "false" arg in macro below evaluates to `if (false) ...` after
* pre-processing, and causes warnings about unreachable code */
#if (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_PUSH_POP) && (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_UNREACHABLE_CODE)
# pragma GCC diagnostic push
#endif
#ifdef HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_UNREACHABLE_CODE
# pragma GCC diagnostic ignored "-Wunreachable-code"
#endif
/* Older CLANG (e.g. clang-3.4) seems to not support the GCC pragmas above */
#ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wunreachable-code"
#endif
UPSMON_DIRECTIVEX("DEBUG_MIN", int, config.debugMin, false);
UPSMON_DIRECTIVEX("RUN_AS_USER", std::string, config.runAsUser, true);
UPSMON_DIRECTIVEX("SHUTDOWNCMD", std::string, config.shutdownCmd, true);
UPSMON_DIRECTIVEX("NOTIFYCMD", std::string, config.notifyCmd, true);
UPSMON_DIRECTIVEX("POWERDOWNFLAG", std::string, config.powerDownFlag, true);
UPSMON_DIRECTIVEX("MINSUPPLIES", unsigned int, config.minSupplies, false);
UPSMON_DIRECTIVEX("POLLFREQ", unsigned int, config.pollFreq, false);
UPSMON_DIRECTIVEX("POLLFREQALERT", unsigned int, config.pollFreqAlert, false);
UPSMON_DIRECTIVEX("POLLFAIL_LOG_THROTTLE_MAX", int, config.pollFailLogThrottleMax, false);
UPSMON_DIRECTIVEX("OFFDURATION", int, config.offDuration, false);
UPSMON_DIRECTIVEX("OBLBDURATION", int, config.oblbDuration, false);
UPSMON_DIRECTIVEX("OVERDURATION", int, config.overDuration, false);
UPSMON_DIRECTIVEX("SHUTDOWNEXIT", nut::BoolInt, config.shutdownExit, false);
UPSMON_DIRECTIVEX("CERTPATH", std::string, config.certPath, true);
// Spec says to write these as 0/1 integers
// and the macro requires Settable<>
// Mumbo-jumbo below for guaranteed casting to int
nut::BoolInt bi, bi2;
Settable<nut::BoolInt> bis;
int i;
// NOTE: After copy-assignments below (which inherit original strictness),
// need to add relaxed mode for 0/1 as false/true handling:
// bi.bool01 = true;
bi2.bool01 = false; // strict mode for 0/1 as int handling
// Avoid static analysis concerns that the internal _value
// "may be used uninitialized in this function" (ETOOSMART):
bi = false;
bi2 = false;
if (config.certVerify.set()) {
bi = config.certVerify;
bi.bool01 = true;
i = bi;
bi2 = i;
bis = bi2;
UPSMON_DIRECTIVEX("CERTVERIFY", nut::BoolInt, bis, false);
}
if (config.forceSsl.set()) {
bi = config.forceSsl;
bi.bool01 = true;
i = bi;
bi2 = i;
bis = bi2;
UPSMON_DIRECTIVEX("FORCESSL", nut::BoolInt, bis, false);
}
if (config.alarmCritical.set()) {
bi = config.alarmCritical;
bi.bool01 = true;
i = bi;
bi2 = i;
bis = bi2;
UPSMON_DIRECTIVEX("ALARMCRITICAL", nut::BoolInt, bis, false);
}
UPSMON_DIRECTIVEX("HOSTSYNC", unsigned int, config.hostSync, false);
UPSMON_DIRECTIVEX("DEADTIME", unsigned int, config.deadTime, false);
UPSMON_DIRECTIVEX("RBWARNTIME", unsigned int, config.rbWarnTime, false);
UPSMON_DIRECTIVEX("NOCOMMWARNTIME", unsigned int, config.noCommWarnTime, false);
UPSMON_DIRECTIVEX("FINALDELAY", unsigned int, config.finalDelay, false);
#ifdef __clang__
# pragma clang diagnostic pop
#endif
#if (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_PUSH_POP) && (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_UNREACHABLE_CODE)
# pragma GCC diagnostic pop
#endif
# undef UPSMON_DIRECTIVEX
// Certificate identity
if (config.certIdent.set()) {
std::string directive = serializeCertIdent(config.certIdent);
status_t status = writeDirective(directive);
if (NUTW_OK != status)
return status;
}
// Remote host(s) protected by specific certificates on their listeners
std::list<nut::CertHost>::const_iterator la_iter = config.certHosts.begin();
for (; la_iter != config.certHosts.end(); ++la_iter) {
std::string directive = serializeCertHost(*la_iter);
status_t status = writeDirective(directive);
if (NUTW_OK != status)
return status;
}
UpsmonConfiguration::NotifyType type;
// Notify flags
type = UpsmonConfiguration::NOTIFY_ONLINE;
for (; type < UpsmonConfiguration::NOTIFY_TYPE_MAX; ++type) {
if (config.notifyFlags[type].set()) {
std::string directive = serializeNotifyFlags(type, config.notifyFlags[type]);
status_t status = writeDirective(directive);
if (NUTW_OK != status)
return status;
}
}
// Notify messages
type = UpsmonConfiguration::NOTIFY_ONLINE;
for (; type < UpsmonConfiguration::NOTIFY_TYPE_MAX; ++type) {
if (config.notifyMessages[type].set()) {
std::string directive = serializeNotifyMessage(type, config.notifyMessages[type]);
status_t status = writeDirective(directive);
if (NUTW_OK != status)
return status;
}
}
// Monitors
std::list<UpsmonConfiguration::Monitor>::const_iterator mon_iter = config.monitors.begin();
for (; mon_iter != config.monitors.end(); ++mon_iter) {
std::string directive = serializeMonitor(*mon_iter);
status_t status = writeDirective(directive);
if (NUTW_OK != status)
return status;
}
return NUTW_OK;
}
/**
* \brief upsd listen address serializer
*
* \param address Listen address
*
* \return Serialized listen address
*/
static std::string serializeUpsdListenAddress(const UpsdConfiguration::Listen & address) {
std::stringstream directive;
directive << "LISTEN " << address.address;
if (address.port.set())
directive << ' ' << static_cast<unsigned short>(address.port);
return directive.str();
}
NutWriter::status_t UpsdConfigWriter::writeConfig(const UpsdConfiguration & config) {
/**
* \brief upsd directive generator
*
* The macro is locally used to simplify generation of
* upsd config. directives (except the listen addresses).
*
* NOTE that the macro may cause return from the function
* (upon writing error).
* See \ref CONFIG_DIRECTIVEX for more information.
*
* \param name Directive name
* \param arg_t Directive argument implementation type
* \param arg Directive argument
*/
# define UPSD_DIRECTIVEX(name, arg_t, arg) \
CONFIG_DIRECTIVEX(name, arg_t, arg, false)
/* The "false" arg in macro below evaluates to `if (false) ...` after
* pre-processing, and causes warnings about unreachable code */
#if (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_PUSH_POP) && (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_UNREACHABLE_CODE)
# pragma GCC diagnostic push
#endif
#ifdef HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_UNREACHABLE_CODE
# pragma GCC diagnostic ignored "-Wunreachable-code"
#endif
/* Older CLANG (e.g. clang-3.4) seems to not support the GCC pragmas above */
#ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wunreachable-code"
#endif
UPSD_DIRECTIVEX("DEBUG_MIN", int, config.debugMin);
UPSD_DIRECTIVEX("MAXAGE", unsigned int, config.maxAge);
UPSD_DIRECTIVEX("MAXCONN", unsigned int, config.maxConn);
UPSD_DIRECTIVEX("TRACKINGDELAY", unsigned int, config.trackingDelay);
UPSD_DIRECTIVEX("ALLOW_NO_DEVICE", bool, config.allowNoDevice);
UPSD_DIRECTIVEX("ALLOW_NOT_ALL_LISTENERS", bool, config.allowNotAllListeners);
UPSD_DIRECTIVEX("DISABLE_WEAK_SSL", bool, config.disableWeakSsl);
CONFIG_DIRECTIVEX("STATEPATH", std::string, config.statePath, true);
CONFIG_DIRECTIVEX("CERTFILE", std::string, config.certFile, true);
CONFIG_DIRECTIVEX("CERTPATH", std::string, config.certPath, true);
UPSD_DIRECTIVEX("CERTREQUEST", unsigned int, config.certRequestLevel);
#ifdef __clang__
# pragma clang diagnostic pop
#endif
#if (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_PUSH_POP) && (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_UNREACHABLE_CODE)
# pragma GCC diagnostic pop
#endif
# undef UPSD_DIRECTIVEX
// Certificate identity
if (config.certIdent.set()) {
std::string directive = serializeCertIdent(config.certIdent);
status_t status = writeDirective(directive);
if (NUTW_OK != status)
return status;
}
// Listen addresses
std::list<UpsdConfiguration::Listen>::const_iterator la_iter = config.listens.begin();
for (; la_iter != config.listens.end(); ++la_iter) {
std::string directive = serializeUpsdListenAddress(*la_iter);
status_t status = writeDirective(directive);
if (NUTW_OK != status)
return status;
}
return NUTW_OK;
}
NutWriter::status_t DefaultConfigWriter::writeComment(const std::string & str) {
return writeEachLine(str, "# ");
}
NutWriter::status_t DefaultConfigWriter::writeSectionName(const std::string & name) {
std::string section_line("[");
section_line += name + "]" + eol;
return write(section_line);
}
NutWriter::status_t DefaultConfigWriter::writeDirective(const std::string & str) {
return write(str + eol);
}
/**
* \brief Value quoting and escaping
*
* The function checks whether the value string contains
* any spaces and/or '=' characters.
* If so, the result is double-quoted and all inner double
* quotes shall be escaped using backslash.
*
* \param val Value string
*
* \return Value string ready for serialization
*/
static std::string encodeValue(const std::string & val) {
// Check the string for spaces and '='
bool quote = false;
for (size_t i = 0; i < val.size() && !quote; ++i) {
char ch = val[i];
quote = ' ' == ch || '=' == ch || ':' == ch;
}
if (!quote)
return val;
// Quote value and escape inner quotes
std::string qval;
qval += '"';
for (size_t i = 0; i < val.size(); ++i) {
char ch = val[i];
if ('"' == ch)
qval += '\\';
qval += ch;
}
qval += '"';
return qval;
}
NutWriter::status_t GenericConfigWriter::writeSectionEntry(
const GenericConfigSectionEntry & entry,
const std::string & indent,
const std::string & kv_sep)
{
ConfigParamList::const_iterator value_iter = entry.values.begin();
for (; value_iter != entry.values.end(); ++value_iter) {
std::string value = encodeValue(*value_iter);
status_t status = writeDirective(indent + entry.name + kv_sep + value);
if (NUTW_OK != status)
return status;
}
return NUTW_OK;
}
NutWriter::status_t GenericConfigWriter::writeSection(const GenericConfigSection & section) {
status_t status;
// Note that global scope definitions are in section
// with an empty name
// The section name won't be written and the assignments
// won't be indented
std::string indent;
if (!section.name.empty()) {
status = writeSectionName(section.name);
if (NUTW_OK != status)
return status;
indent += "\t";
}
// Write section name/value pairs
GenericConfigSection::EntryMap::const_iterator entry_iter = section.entries.begin();
for (; entry_iter != section.entries.end(); ++entry_iter) {
status = writeSectionEntry(entry_iter->second, indent);
if (NUTW_OK != status)
return status;
}
return NUTW_OK;
}
NutWriter::status_t GenericConfigWriter::writeConfig(const GenericConfiguration & config) {
// Write sections
// Note that lexicographic ordering places the global
// (i.e. empty-name) section as the first one
GenericConfiguration::SectionMap::const_iterator section_iter = config.sections.begin();
for (; section_iter != config.sections.end(); ++section_iter) {
status_t status = writeSection(section_iter->second);
if (NUTW_OK != status)
return status;
// TBD: Write one empty line as section separator
status = write(eol);
if (NUTW_OK != status)
return status;
}
return NUTW_OK;
}
NutWriter::status_t UpsdUsersConfigWriter::writeSection(const GenericConfigSection & section) {
static const std::string upsmon_entry_separator(" ");
status_t status;
// upsmon section requires special handling because of the upsmon (master|slave) directive
if ("upsmon" != section.name)
return GenericConfigWriter::writeSection(section);
status = writeSectionName(section.name);
if (NUTW_OK != status)
return status;
// Write section name/value pairs
GenericConfigSection::EntryMap::const_iterator entry_iter = section.entries.begin();
for (; entry_iter != section.entries.end(); ++entry_iter) {
// Special case of upsmon parameter
if ("upsmon" == entry_iter->second.name) {
status = writeSectionEntry(entry_iter->second,
s_default_section_entry_indent,
upsmon_entry_separator);
}
// Standard entry serialization
else {
status = writeSectionEntry(entry_iter->second);
}
if (NUTW_OK != status)
return status;
}
return NUTW_OK;
}
} // end of namespace nut
|