forked from networkupstools/nut
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nutclient.cpp
2010 lines (1742 loc) · 38.5 KB
/
nutclient.cpp
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
/* nutclient.cpp - nutclient C++ library implementation
Copyright (C) 2012 Emilien Kia <[email protected]>
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 "nutclient.h"
#include <sstream>
#include <errno.h>
#include <string.h>
#include <stdio.h>
/* Windows/Linux Socket compatibility layer: */
/* Thanks to Benjamin Roux (http://broux.developpez.com/articles/c/sockets/) */
#ifdef WIN32
# include <winsock2.h>
#else
# include <sys/types.h>
# include <sys/socket.h>
# include <netinet/in.h>
# include <arpa/inet.h>
# include <unistd.h> /* close */
# include <netdb.h> /* gethostbyname */
# include <fcntl.h>
# define INVALID_SOCKET -1
# define SOCKET_ERROR -1
# define closesocket(s) close(s)
typedef int SOCKET;
typedef struct sockaddr_in SOCKADDR_IN;
typedef struct sockaddr SOCKADDR;
typedef struct in_addr IN_ADDR;
#endif /* WIN32 */
/* End of Windows/Linux Socket compatibility layer: */
/* Include nut common utility functions or define simple ones if not */
#ifdef HAVE_NUTCOMMON
#include "common.h"
#else /* HAVE_NUTCOMMON */
#include <stdlib.h>
#include <string.h>
static inline void *xmalloc(size_t size){return malloc(size);}
static inline void *xcalloc(size_t number, size_t size){return calloc(number, size);}
static inline void *xrealloc(void *ptr, size_t size){return realloc(ptr, size);}
static inline char *xstrdup(const char *string){return strdup(string);}
#endif /* HAVE_NUTCOMMON */
/* To stay in line with modern C++, we use nullptr (not numeric NULL
* or shim __null on some systems) which was defined after C++98.
* The NUT C++ interface is intended for C++11 and newer, so we
* quiesce these warnigns if possible.
* An idea might be to detect if we do build with old C++ standard versions
* and define a nullptr like https://stackoverflow.com/a/44517878/4715872
* but again - currently we do not intend to support that officially.
*/
#ifdef HAVE_PRAGMAS_FOR_GCC_DIAGNOSTIC_IGNORED_CXX98_COMPAT
#pragma GCC diagnostic push
#endif
#ifdef HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_CXX98_COMPAT_PEDANTIC
#pragma GCC diagnostic ignored "-Wc++98-compat-pedantic"
#endif
#ifdef HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_CXX98_COMPAT
#pragma GCC diagnostic ignored "-Wc++98-compat"
#endif
namespace nut
{
SystemException::SystemException():
NutException(err())
{
}
std::string SystemException::err()
{
if(errno==0)
return "Undefined system error";
else
{
std::stringstream str;
str << "System error " << errno << ": " << strerror(errno);
return str.str();
}
}
/* Implemented out-of-line to avoid "Weak vtables" warnings and related overheads
* But now with clang-9 C++11 linter (though not C++17) they complain with
* error: definition of implicit copy constructor for 'NutException'
* is deprecated because it has a user-declared destructor
* This is fixed in header with declarations like:
* NutException(const NutException&) = default;
* and assignment operator to accompany the copy constructor, per
* https://lgtm.com/rules/2165180572/ like:
* NutException& operator=(NutException& rhs) = default;
*/
NutException::~NutException() {}
SystemException::~SystemException() {}
IOException::~IOException() {}
UnknownHostException::~UnknownHostException() {}
NotConnectedException::~NotConnectedException() {}
TimeoutException::~TimeoutException() {}
namespace internal
{
/**
* Internal socket wrapper.
* Provides only client socket functions.
*
* Implemented as separate internal class to easily hide plateform specificities.
*/
class Socket
{
public:
Socket();
~Socket();
void connect(const std::string& host, int port);
void disconnect();
bool isConnected()const;
void setTimeout(long timeout);
bool hasTimeout()const{return _tv.tv_sec>=0;}
size_t read(void* buf, size_t sz);
size_t write(const void* buf, size_t sz);
std::string read();
void write(const std::string& str);
private:
SOCKET _sock;
struct timeval _tv;
std::string _buffer; /* Received buffer, string because data should be text only. */
};
Socket::Socket():
_sock(INVALID_SOCKET),
_tv()
{
_tv.tv_sec = -1;
_tv.tv_usec = 0;
}
Socket::~Socket()
{
disconnect();
}
void Socket::setTimeout(long timeout)
{
_tv.tv_sec = timeout;
}
void Socket::connect(const std::string& host, int port)
{
int sock_fd;
struct addrinfo hints, *res, *ai;
char sport[NI_MAXSERV];
int v;
fd_set wfds;
int error;
socklen_t error_size;
long fd_flags;
_sock = -1;
if (host.empty()) {
throw nut::UnknownHostException();
}
snprintf(sport, sizeof(sport), "%hu", static_cast<unsigned short int>(port));
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
while ((v = getaddrinfo(host.c_str(), sport, &hints, &res)) != 0) {
switch (v)
{
case EAI_AGAIN:
continue;
case EAI_NONAME:
throw nut::UnknownHostException();
case EAI_SYSTEM:
throw nut::SystemException();
case EAI_MEMORY:
throw nut::NutException("Out of memory");
default:
throw nut::NutException("Unknown error");
}
}
for (ai = res; ai != nullptr; ai = ai->ai_next) {
sock_fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
if (sock_fd < 0) {
switch (errno)
{
case EAFNOSUPPORT:
case EINVAL:
break;
default:
throw nut::SystemException();
}
continue;
}
/* non blocking connect */
if(hasTimeout()) {
fd_flags = fcntl(sock_fd, F_GETFL);
fd_flags |= O_NONBLOCK;
fcntl(sock_fd, F_SETFL, fd_flags);
}
while ((v = ::connect(sock_fd, ai->ai_addr, ai->ai_addrlen)) < 0) {
if(errno == EINPROGRESS) {
FD_ZERO(&wfds);
FD_SET(sock_fd, &wfds);
select(sock_fd+1, nullptr, &wfds, nullptr, hasTimeout() ? &_tv : nullptr);
if (FD_ISSET(sock_fd, &wfds)) {
error_size = sizeof(error);
getsockopt(sock_fd, SOL_SOCKET, SO_ERROR,
&error, &error_size);
if( error == 0) {
/* connect successful */
v = 0;
break;
}
errno = error;
}
else {
/* Timeout */
v = -1;
break;
}
}
switch (errno)
{
case EAFNOSUPPORT:
break;
case EINTR:
case EAGAIN:
continue;
default:
// ups->upserror = UPSCLI_ERR_CONNFAILURE;
// ups->syserrno = errno;
break;
}
break;
}
if (v < 0) {
close(sock_fd);
continue;
}
/* switch back to blocking operation */
if(hasTimeout()) {
fd_flags = fcntl(sock_fd, F_GETFL);
fd_flags &= ~O_NONBLOCK;
fcntl(sock_fd, F_SETFL, fd_flags);
}
_sock = sock_fd;
// ups->upserror = 0;
// ups->syserrno = 0;
break;
}
freeaddrinfo(res);
if (_sock < 0) {
throw nut::IOException("Cannot connect to host");
}
#ifdef OLD
struct hostent *hostinfo = nullptr;
SOCKADDR_IN sin = { 0 };
hostinfo = ::gethostbyname(host.c_str());
if(hostinfo == nullptr) /* Host doesnt exist */
{
throw nut::UnknownHostException();
}
// Create socket
_sock = ::socket(PF_INET, SOCK_STREAM, 0);
if(_sock == INVALID_SOCKET)
{
throw nut::IOException("Cannot create socket");
}
// Connect
sin.sin_addr = *(IN_ADDR *) hostinfo->h_addr;
sin.sin_port = htons(port);
sin.sin_family = AF_INET;
if(::connect(_sock,(SOCKADDR *) &sin, sizeof(SOCKADDR)) == SOCKET_ERROR)
{
_sock = INVALID_SOCKET;
throw nut::IOException("Cannot connect to host");
}
#endif // OLD
}
void Socket::disconnect()
{
if(_sock != INVALID_SOCKET)
{
::closesocket(_sock);
_sock = INVALID_SOCKET;
}
_buffer.clear();
}
bool Socket::isConnected()const
{
return _sock!=INVALID_SOCKET;
}
size_t Socket::read(void* buf, size_t sz)
{
if(!isConnected())
{
throw nut::NotConnectedException();
}
if(_tv.tv_sec>=0)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(_sock, &fds);
int ret = select(_sock+1, &fds, nullptr, nullptr, &_tv);
if (ret < 1) {
throw nut::TimeoutException();
}
}
ssize_t res = ::read(_sock, buf, sz);
if(res==-1)
{
disconnect();
throw nut::IOException("Error while reading on socket");
}
return static_cast<size_t>(res);
}
size_t Socket::write(const void* buf, size_t sz)
{
if(!isConnected())
{
throw nut::NotConnectedException();
}
if(_tv.tv_sec>=0)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(_sock, &fds);
int ret = select(_sock+1, nullptr, &fds, nullptr, &_tv);
if (ret < 1) {
throw nut::TimeoutException();
}
}
ssize_t res = ::write(_sock, buf, sz);
if(res==-1)
{
disconnect();
throw nut::IOException("Error while writing on socket");
}
return static_cast<size_t>(res);
}
std::string Socket::read()
{
std::string res;
char buff[256];
while(true)
{
// Look at already read data in _buffer
if(!_buffer.empty())
{
size_t idx = _buffer.find('\n');
if(idx!=std::string::npos)
{
res += _buffer.substr(0, idx);
_buffer.erase(0, idx+1);
return res;
}
res += _buffer;
}
// Read new buffer
size_t sz = read(&buff, 256);
if(sz==0)
{
disconnect();
throw nut::IOException("Server closed connection unexpectedly");
}
_buffer.assign(buff, sz);
}
}
void Socket::write(const std::string& str)
{
// write(str.c_str(), str.size());
// write("\n", 1);
std::string buff = str + "\n";
write(buff.c_str(), buff.size());
}
}/* namespace internal */
/*
*
* Client implementation
*
*/
/* Pedantic builds complain about the static variable below...
* It is assumed safe to ignore since it is a std::string with
* no complex teardown at program exit.
*/
#if (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_PUSH_POP) && (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_EXIT_TIME_DESTRUCTORS || defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_GLOBAL_CONSTRUCTORS)
#pragma GCC diagnostic push
# ifdef HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_GLOBAL_CONSTRUCTORS
# pragma GCC diagnostic ignored "-Wglobal-constructors"
# endif
# ifdef HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_EXIT_TIME_DESTRUCTORS
# pragma GCC diagnostic ignored "-Wexit-time-destructors"
# endif
#endif
const Feature Client::TRACKING = "TRACKING";
#if (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_PUSH_POP) && (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_EXIT_TIME_DESTRUCTORS || defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_GLOBAL_CONSTRUCTORS)
#pragma GCC diagnostic pop
#endif
Client::Client()
{
}
Client::~Client()
{
}
bool Client::hasDevice(const std::string& dev)
{
std::set<std::string> devs = getDeviceNames();
return devs.find(dev) != devs.end();
}
Device Client::getDevice(const std::string& name)
{
if(hasDevice(name))
return Device(this, name);
else
return Device(nullptr, "");
}
std::set<Device> Client::getDevices()
{
std::set<Device> res;
std::set<std::string> devs = getDeviceNames();
for(std::set<std::string>::iterator it=devs.begin(); it!=devs.end(); ++it)
{
res.insert(Device(this, *it));
}
return res;
}
bool Client::hasDeviceVariable(const std::string& dev, const std::string& name)
{
std::set<std::string> names = getDeviceVariableNames(dev);
return names.find(name) != names.end();
}
std::map<std::string,std::vector<std::string> > Client::getDeviceVariableValues(const std::string& dev)
{
std::map<std::string,std::vector<std::string> > res;
std::set<std::string> names = getDeviceVariableNames(dev);
for(std::set<std::string>::iterator it=names.begin(); it!=names.end(); ++it)
{
const std::string& name = *it;
res[name] = getDeviceVariableValue(dev, name);
}
return res;
}
std::map<std::string,std::map<std::string,std::vector<std::string> > > Client::getDevicesVariableValues(const std::set<std::string>& devs)
{
std::map<std::string,std::map<std::string,std::vector<std::string> > > res;
for(std::set<std::string>::const_iterator it=devs.cbegin(); it!=devs.cend(); ++it)
{
res[*it] = getDeviceVariableValues(*it);
}
return res;
}
bool Client::hasDeviceCommand(const std::string& dev, const std::string& name)
{
std::set<std::string> names = getDeviceCommandNames(dev);
return names.find(name) != names.end();
}
bool Client::hasFeature(const Feature& feature)
{
try
{
// If feature is known, querying it won't throw an exception.
isFeatureEnabled(feature);
return true;
}
catch(...)
{
return false;
}
}
/*
*
* TCP Client implementation
*
*/
TcpClient::TcpClient():
Client(),
_host("localhost"),
_port(3493),
_timeout(0),
_socket(new internal::Socket)
{
// Do not connect now
}
TcpClient::TcpClient(const std::string& host, int port):
Client(),
_timeout(0),
_socket(new internal::Socket)
{
connect(host, port);
}
TcpClient::~TcpClient()
{
delete _socket;
}
void TcpClient::connect(const std::string& host, int port)
{
_host = host;
_port = port;
connect();
}
void TcpClient::connect()
{
_socket->connect(_host, _port);
}
std::string TcpClient::getHost()const
{
return _host;
}
int TcpClient::getPort()const
{
return _port;
}
bool TcpClient::isConnected()const
{
return _socket->isConnected();
}
void TcpClient::disconnect()
{
_socket->disconnect();
}
void TcpClient::setTimeout(long timeout)
{
_timeout = timeout;
}
long TcpClient::getTimeout()const
{
return _timeout;
}
void TcpClient::authenticate(const std::string& user, const std::string& passwd)
{
detectError(sendQuery("USERNAME " + user));
detectError(sendQuery("PASSWORD " + passwd));
}
void TcpClient::logout()
{
detectError(sendQuery("LOGOUT"));
_socket->disconnect();
}
Device TcpClient::getDevice(const std::string& name)
{
try
{
get("UPSDESC", name);
}
catch(NutException& ex)
{
if(ex.str()=="UNKNOWN-UPS")
return Device(nullptr, "");
else
throw;
}
return Device(this, name);
}
std::set<std::string> TcpClient::getDeviceNames()
{
std::set<std::string> res;
std::vector<std::vector<std::string> > devs = list("UPS");
for(std::vector<std::vector<std::string> >::iterator it=devs.begin();
it!=devs.end(); ++it)
{
std::string id = (*it)[0];
if(!id.empty())
res.insert(id);
}
return res;
}
std::string TcpClient::getDeviceDescription(const std::string& name)
{
return get("UPSDESC", name)[0];
}
std::set<std::string> TcpClient::getDeviceVariableNames(const std::string& dev)
{
std::set<std::string> set;
std::vector<std::vector<std::string> > res = list("VAR", dev);
for(size_t n=0; n<res.size(); ++n)
{
set.insert(res[n][0]);
}
return set;
}
std::set<std::string> TcpClient::getDeviceRWVariableNames(const std::string& dev)
{
std::set<std::string> set;
std::vector<std::vector<std::string> > res = list("RW", dev);
for(size_t n=0; n<res.size(); ++n)
{
set.insert(res[n][0]);
}
return set;
}
std::string TcpClient::getDeviceVariableDescription(const std::string& dev, const std::string& name)
{
return get("DESC", dev + " " + name)[0];
}
std::vector<std::string> TcpClient::getDeviceVariableValue(const std::string& dev, const std::string& name)
{
return get("VAR", dev + " " + name);
}
std::map<std::string,std::vector<std::string> > TcpClient::getDeviceVariableValues(const std::string& dev)
{
std::map<std::string,std::vector<std::string> > map;
std::vector<std::vector<std::string> > res = list("VAR", dev);
for(size_t n=0; n<res.size(); ++n)
{
std::vector<std::string>& vals = res[n];
std::string var = vals[0];
vals.erase(vals.begin());
map[var] = vals;
}
return map;
}
std::map<std::string,std::map<std::string,std::vector<std::string> > > TcpClient::getDevicesVariableValues(const std::set<std::string>& devs)
{
std::map<std::string,std::map<std::string,std::vector<std::string> > > map;
if (devs.empty())
{
// This request might come from processing the empty valid
// response of an upsd server which was allowed to start
// with no device sections in its ups.conf
return map;
}
std::vector<std::string> queries;
for (std::set<std::string>::const_iterator it=devs.cbegin(); it!=devs.cend(); ++it)
{
queries.push_back("LIST VAR " + *it);
}
sendAsyncQueries(queries);
for (std::set<std::string>::const_iterator it=devs.cbegin(); it!=devs.cend(); ++it)
{
try
{
std::map<std::string,std::vector<std::string> > map2;
std::vector<std::vector<std::string> > res = parseList("VAR " + *it);
for (std::vector<std::vector<std::string> >::iterator it2=res.begin(); it2!=res.end(); ++it2)
{
std::vector<std::string>& vals = *it2;
std::string var = vals[0];
vals.erase(vals.begin());
map2[var] = vals;
}
map[*it] = map2;
}
catch (NutException&)
{
// We sent a bunch of queries, we need to process them all to clear up the backlog.
}
}
if (map.empty())
{
// We may fail on some devices, but not on ALL devices.
throw NutException("Invalid device");
}
return map;
}
TrackingID TcpClient::setDeviceVariable(const std::string& dev, const std::string& name, const std::string& value)
{
std::string query = "SET VAR " + dev + " " + name + " " + escape(value);
return sendTrackingQuery(query);
}
TrackingID TcpClient::setDeviceVariable(const std::string& dev, const std::string& name, const std::vector<std::string>& values)
{
std::string query = "SET VAR " + dev + " " + name;
for(size_t n=0; n<values.size(); ++n)
{
query += " " + escape(values[n]);
}
return sendTrackingQuery(query);
}
std::set<std::string> TcpClient::getDeviceCommandNames(const std::string& dev)
{
std::set<std::string> cmds;
std::vector<std::vector<std::string> > res = list("CMD", dev);
for(size_t n=0; n<res.size(); ++n)
{
cmds.insert(res[n][0]);
}
return cmds;
}
std::string TcpClient::getDeviceCommandDescription(const std::string& dev, const std::string& name)
{
return get("CMDDESC", dev + " " + name)[0];
}
TrackingID TcpClient::executeDeviceCommand(const std::string& dev, const std::string& name, const std::string& param)
{
return sendTrackingQuery("INSTCMD " + dev + " " + name + " " + param);
}
void TcpClient::deviceLogin(const std::string& dev)
{
detectError(sendQuery("LOGIN " + dev));
}
/* FIXME: Protocol update needed to handle master/primary alias
* and probably an API bump also, to rename/alias the routine.
*/
void TcpClient::deviceMaster(const std::string& dev)
{
detectError(sendQuery("MASTER " + dev));
}
void TcpClient::deviceForcedShutdown(const std::string& dev)
{
detectError(sendQuery("FSD " + dev));
}
int TcpClient::deviceGetNumLogins(const std::string& dev)
{
std::string num = get("NUMLOGINS", dev)[0];
return atoi(num.c_str());
}
TrackingResult TcpClient::getTrackingResult(const TrackingID& id)
{
if (id.empty())
{
return TrackingResult::SUCCESS;
}
std::string result = sendQuery("GET TRACKING " + id);
if (result == "PENDING")
{
return TrackingResult::PENDING;
}
else if (result == "SUCCESS")
{
return TrackingResult::SUCCESS;
}
else if (result == "ERR UNKNOWN")
{
return TrackingResult::UNKNOWN;
}
else if (result == "ERR INVALID-ARGUMENT")
{
return TrackingResult::INVALID_ARGUMENT;
}
else
{
return TrackingResult::FAILURE;
}
}
bool TcpClient::isFeatureEnabled(const Feature& feature)
{
std::string result = sendQuery("GET " + feature);
detectError(result);
if (result == "ON")
{
return true;
}
else if (result == "OFF")
{
return false;
}
else
{
throw NutException("Unknown feature result " + result);
}
}
void TcpClient::setFeature(const Feature& feature, bool status)
{
std::string result = sendQuery("SET " + feature + " " + (status ? "ON" : "OFF"));
detectError(result);
}
std::vector<std::string> TcpClient::get
(const std::string& subcmd, const std::string& params)
{
std::string req = subcmd;
if(!params.empty())
{
req += " " + params;
}
std::string res = sendQuery("GET " + req);
detectError(res);
if(res.substr(0, req.size()) != req)
{
throw NutException("Invalid response");
}
return explode(res, req.size());
}
std::vector<std::vector<std::string> > TcpClient::list
(const std::string& subcmd, const std::string& params)
{
std::string req = subcmd;
if(!params.empty())
{
req += " " + params;
}
std::vector<std::string> query;
query.push_back("LIST " + req);
sendAsyncQueries(query);
return parseList(req);
}
std::vector<std::vector<std::string> > TcpClient::parseList
(const std::string& req)
{
std::string res = _socket->read();
detectError(res);
if(res != ("BEGIN LIST " + req))
{
throw NutException("Invalid response");
}
std::vector<std::vector<std::string> > arr;
while(true)
{
res = _socket->read();
detectError(res);
if(res == ("END LIST " + req))
{
return arr;
}
if(res.substr(0, req.size()) == req)
{
arr.push_back(explode(res, req.size()));
}
else
{
throw NutException("Invalid response");
}
}
}
std::string TcpClient::sendQuery(const std::string& req)
{
_socket->write(req);
return _socket->read();
}
void TcpClient::sendAsyncQueries(const std::vector<std::string>& req)
{
for (std::vector<std::string>::const_iterator it = req.cbegin(); it != req.cend(); ++it)
{
_socket->write(*it);
}
}
void TcpClient::detectError(const std::string& req)
{
if(req.substr(0,3)=="ERR")
{
throw NutException(req.substr(4));
}
}
std::vector<std::string> TcpClient::explode(const std::string& str, size_t begin)
{
std::vector<std::string> res;
std::string temp;
enum STATE {
INIT,
SIMPLE_STRING,
QUOTED_STRING,
SIMPLE_ESCAPE,
QUOTED_ESCAPE
} state = INIT;
for(size_t idx=begin; idx<str.size(); ++idx)
{
char c = str[idx];
switch(state)
{
case INIT:
if(c==' ' /* || c=='\t' */)
{ /* Do nothing */ }
else if(c=='"')
{
state = QUOTED_STRING;
}
else if(c=='\\')
{
state = SIMPLE_ESCAPE;
}