forked from ethereum-mining/ethminer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ApiServer.cpp
1281 lines (1124 loc) · 43 KB
/
ApiServer.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
#include "ApiServer.h"
#include <ethminer/buildinfo.h>
#include <libethcore/Farm.h>
#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 255
#endif
// Define grayscale palette
#define HTTP_HDR0_COLOR "#e8e8e8"
#define HTTP_HDR1_COLOR "#f0f0f0"
#define HTTP_ROW0_COLOR "#f8f8f8"
#define HTTP_ROW1_COLOR "#ffffff"
#define HTTP_ROWRED_COLOR "#f46542"
/* helper functions getting values from a JSON request */
static bool getRequestValue(const char* membername, bool& refValue, Json::Value& jRequest,
bool optional, Json::Value& jResponse)
{
if (!jRequest.isMember(membername))
{
if (!optional)
{
jResponse["error"]["code"] = -32602;
jResponse["error"]["message"] =
std::string("Missing '") + std::string(membername) + std::string("'");
}
return optional;
}
if (!jRequest[membername].isBool())
{
jResponse["error"]["code"] = -32602;
jResponse["error"]["message"] =
std::string("Invalid type of value '") + std::string(membername) + std::string("'");
return false;
}
if (jRequest[membername].empty())
{
jResponse["error"]["code"] = -32602;
jResponse["error"]["message"] =
std::string("Empty '") + std::string(membername) + std::string("'");
return false;
}
refValue = jRequest[membername].asBool();
return true;
}
static bool getRequestValue(const char* membername, unsigned& refValue, Json::Value& jRequest,
bool optional, Json::Value& jResponse)
{
if (!jRequest.isMember(membername))
{
if (!optional)
{
jResponse["error"]["code"] = -32602;
jResponse["error"]["message"] =
std::string("Missing '") + std::string(membername) + std::string("'");
}
return optional;
}
if (!jRequest[membername].isUInt())
{
jResponse["error"]["code"] = -32602;
jResponse["error"]["message"] =
std::string("Invalid type of value '") + std::string(membername) + std::string("'");
return false;
}
if (jRequest[membername].empty())
{
jResponse["error"]["code"] = -32602;
jResponse["error"]["message"] =
std::string("Empty '") + std::string(membername) + std::string("'");
return false;
}
refValue = jRequest[membername].asUInt();
return true;
}
static bool getRequestValue(const char* membername, uint64_t& refValue, Json::Value& jRequest,
bool optional, Json::Value& jResponse)
{
if (!jRequest.isMember(membername))
{
if (!optional)
{
jResponse["error"]["code"] = -32602;
jResponse["error"]["message"] =
std::string("Missing '") + std::string(membername) + std::string("'");
}
return optional;
}
/* as there is no isUInt64() function we can not check the type */
if (jRequest[membername].empty())
{
jResponse["error"]["code"] = -32602;
jResponse["error"]["message"] =
std::string("Empty '") + std::string(membername) + std::string("'");
return false;
}
try
{
refValue = jRequest[membername].asUInt64();
}
catch (...)
{
jRequest["error"]["code"] = -32602;
jResponse["error"]["message"] =
std::string("Bad value in '") + std::string(membername) + std::string("'");
return false;
}
return true;
}
static bool getRequestValue(const char* membername, Json::Value& refValue, Json::Value& jRequest,
bool optional, Json::Value& jResponse)
{
if (!jRequest.isMember(membername))
{
if (!optional)
{
jResponse["error"]["code"] = -32602;
jResponse["error"]["message"] =
std::string("Missing '") + std::string(membername) + std::string("'");
}
return optional;
}
if (!jRequest[membername].isObject())
{
jResponse["error"]["code"] = -32602;
jResponse["error"]["message"] =
std::string("Invalid type of value '") + std::string(membername) + std::string("'");
return false;
}
if (jRequest[membername].empty())
{
jResponse["error"]["code"] = -32602;
jResponse["error"]["message"] =
std::string("Empty '") + std::string(membername) + std::string("'");
return false;
}
refValue = jRequest[membername];
return true;
}
static bool getRequestValue(const char* membername, std::string& refValue, Json::Value& jRequest,
bool optional, Json::Value& jResponse)
{
if (!jRequest.isMember(membername))
{
if (!optional)
{
jResponse["error"]["code"] = -32602;
jResponse["error"]["message"] =
std::string("Missing '") + std::string(membername) + std::string("'");
}
return optional;
}
if (!jRequest[membername].isString())
{
jResponse["error"]["code"] = -32602;
jResponse["error"]["message"] =
std::string("Invalid type of value '") + std::string(membername) + std::string("'");
return false;
}
if (jRequest[membername].empty())
{
jResponse["error"]["code"] = -32602;
jResponse["error"]["message"] =
std::string("Empty '") + std::string(membername) + std::string("'");
return false;
}
refValue = jRequest[membername].asString();
return true;
}
static bool checkApiWriteAccess(bool is_read_only, Json::Value& jResponse)
{
if (is_read_only)
{
jResponse["error"]["code"] = -32601;
jResponse["error"]["message"] = "Method not available";
}
return !is_read_only;
}
static bool parseRequestId(Json::Value& jRequest, Json::Value& jResponse)
{
const char* membername = "id";
// NOTE: all errors have the same code (-32600) indicating this is an invalid request
// be sure id is there and it's not empty, otherwise raise an error
if (!jRequest.isMember(membername) || jRequest[membername].empty())
{
jResponse[membername] = Json::nullValue;
jResponse["error"]["code"] = -32600;
jResponse["error"]["message"] = "Invalid Request (missing or empty id)";
return false;
}
// try to parse id as Uint
if (jRequest[membername].isUInt())
{
jResponse[membername] = jRequest[membername].asUInt();
return true;
}
// try to parse id as String
if (jRequest[membername].isString())
{
jResponse[membername] = jRequest[membername].asString();
return true;
}
// id has invalid type
jResponse[membername] = Json::nullValue;
jResponse["error"]["code"] = -32600;
jResponse["error"]["message"] = "Invalid Request (id has invalid type)";
return false;
}
ApiServer::ApiServer(string address, int portnum, string password)
: m_password(std::move(password)),
m_address(address),
m_acceptor(g_io_service),
m_io_strand(g_io_service)
{
if (portnum < 0)
{
m_portnumber = -portnum;
m_readonly = true;
}
else
{
m_portnumber = portnum;
m_readonly = false;
}
}
void ApiServer::start()
{
// cnote << "ApiServer::start";
if (m_portnumber == 0)
return;
tcp::endpoint endpoint(boost::asio::ip::address::from_string(m_address), m_portnumber);
// Try to bind to port number
// if exception occurs it may be due to the fact that
// requested port is already in use by another service
try
{
m_acceptor.open(endpoint.protocol());
m_acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
m_acceptor.bind(endpoint);
m_acceptor.listen(64);
}
catch (const std::exception&)
{
cwarn << "Could not start API server on port: " +
to_string(m_acceptor.local_endpoint().port());
cwarn << "Ensure port is not in use by another service";
return;
}
cnote << "Api server listening on port " + to_string(m_acceptor.local_endpoint().port())
<< (m_password.empty() ? "." : ". Authentication needed.");
m_running.store(true, std::memory_order_relaxed);
m_workThread = std::thread{boost::bind(&ApiServer::begin_accept, this)};
}
void ApiServer::stop()
{
// Exit if not started
if (!m_running.load(std::memory_order_relaxed))
return;
m_acceptor.cancel();
m_acceptor.close();
m_workThread.join();
m_running.store(false, std::memory_order_relaxed);
// Dispose all sessions (if any)
m_sessions.clear();
}
void ApiServer::begin_accept()
{
if (!isRunning())
return;
auto session =
std::make_shared<ApiConnection>(m_io_strand, ++lastSessionId, m_readonly, m_password);
m_acceptor.async_accept(
session->socket(), m_io_strand.wrap(boost::bind(&ApiServer::handle_accept, this, session,
boost::asio::placeholders::error)));
}
void ApiServer::handle_accept(std::shared_ptr<ApiConnection> session, boost::system::error_code ec)
{
// Start new connection
// cnote << "ApiServer::handle_accept";
if (!ec)
{
session->onDisconnected([&](int id) {
// Destroy pointer to session
auto it = find_if(m_sessions.begin(), m_sessions.end(),
[&id](const std::shared_ptr<ApiConnection> session) {
return session->getId() == id;
});
if (it != m_sessions.end())
{
auto index = std::distance(m_sessions.begin(), it);
m_sessions.erase(m_sessions.begin() + index);
}
});
m_sessions.push_back(session);
cnote << "New API session from " << session->socket().remote_endpoint();
session->start();
}
else
{
session.reset();
}
// Resubmit new accept
begin_accept();
}
void ApiConnection::disconnect()
{
// cnote << "ApiConnection::disconnect";
// Cancel pending operations
m_socket.cancel();
if (m_socket.is_open())
{
boost::system::error_code ec;
m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
m_socket.close(ec);
}
if (m_onDisconnected)
{
m_onDisconnected(this->getId());
}
}
ApiConnection::ApiConnection(
boost::asio::io_service::strand& _strand, int id, bool readonly, string password)
: m_sessionId(id),
m_socket(g_io_service),
m_io_strand(_strand),
m_readonly(readonly),
m_password(std::move(password))
{
m_jSwBuilder.settings_["indentation"] = "";
if (!m_password.empty())
m_is_authenticated = false;
}
void ApiConnection::start()
{
// cnote << "ApiConnection::start";
recvSocketData();
}
void ApiConnection::processRequest(Json::Value& jRequest, Json::Value& jResponse)
{
jResponse["jsonrpc"] = "2.0";
// Strict sanity checks over jsonrpc v2
if (!parseRequestId(jRequest, jResponse))
return;
std::string jsonrpc;
std::string _method;
if (!getRequestValue("jsonrpc", jsonrpc, jRequest, false, jResponse) || jsonrpc != "2.0" ||
!getRequestValue("method", _method, jRequest, false, jResponse))
{
jResponse["error"]["code"] = -32600;
jResponse["error"]["message"] = "Invalid Request";
return;
}
// Check authentication
if (!m_is_authenticated || _method == "api_authorize")
{
if (_method != "api_authorize")
{
// Use error code like http 403 Forbidden
jResponse["error"]["code"] = -403;
jResponse["error"]["message"] = "Authorization needed";
return;
}
m_is_authenticated =
false; /* we allow api_authorize method even if already authenticated */
Json::Value jRequestParams;
if (!getRequestValue("params", jRequestParams, jRequest, false, jResponse))
return;
std::string psw;
if (!getRequestValue("psw", psw, jRequestParams, false, jResponse))
return;
// max password length that we actually verify
// (this limit can be removed by introducing a collision-resistant compressing hash,
// like blake2b/sha3, but 500 should suffice and is much easier to implement)
const int max_length = 500;
char input_copy[max_length] = {0};
char password_copy[max_length] = {0};
// note: copy() is not O(1) , but i don't think it matters
psw.copy(&input_copy[0], max_length);
// ps, the following line can be optimized to only run once on startup and thus save a
// minuscule amount of cpu cycles.
m_password.copy(&password_copy[0], max_length);
int result = 0;
for (int i = 0; i < max_length; ++i)
{
result |= input_copy[i] ^ password_copy[i];
}
if (result == 0)
{
m_is_authenticated = true;
}
else
{
// Use error code like http 401 Unauthorized
jResponse["error"]["code"] = -401;
jResponse["error"]["message"] = "Invalid password";
cerr << "API : Invalid password provided.";
// Should we close the connection in the outer function after invalid password ?
}
/*
* possible wait here a fixed time of eg 10s before respond after 5 invalid
authentications were submitted to prevent brute force password attacks.
*/
return;
}
assert(m_is_authenticated);
cnote << "API : Method " << _method << " requested";
if (_method == "miner_getstat1")
{
jResponse["result"] = getMinerStat1();
}
else if (_method == "miner_getstatdetail")
{
jResponse["result"] = getMinerStatDetail();
}
else if (_method == "miner_shuffle")
{
if (!checkApiWriteAccess(m_readonly, jResponse))
return;
// Gives nonce scrambler a new range
jResponse["result"] = true;
Farm::f().shuffle();
}
else if (_method == "miner_ping")
{
// Replies back to (check for liveness)
jResponse["result"] = "pong";
}
else if (_method == "miner_restart")
{
// Send response to client of success
// and invoke an async restart
// to prevent locking
if (!checkApiWriteAccess(m_readonly, jResponse))
return;
jResponse["result"] = true;
Farm::f().restart_async();
}
else if (_method == "miner_reboot")
{
if (!checkApiWriteAccess(m_readonly, jResponse))
return;
jResponse["result"] = Farm::f().reboot({{"api_miner_reboot"}});
}
else if (_method == "miner_getconnections")
{
// Returns a list of configured pools
jResponse["result"] = PoolManager::p().getConnectionsJson();
}
else if (_method == "miner_addconnection")
{
if (!checkApiWriteAccess(m_readonly, jResponse))
return;
Json::Value jRequestParams;
if (!getRequestValue("params", jRequestParams, jRequest, false, jResponse))
return;
std::string sUri;
if (!getRequestValue("uri", sUri, jRequestParams, false, jResponse))
return;
try
{
// If everything ok then add this new uri
PoolManager::p().addConnection(sUri);
jResponse["result"] = true;
}
catch (...)
{
jResponse["error"]["code"] = -422;
jResponse["error"]["message"] = "Bad URI : " + sUri;
}
}
else if (_method == "miner_setactiveconnection")
{
if (!checkApiWriteAccess(m_readonly, jResponse))
return;
Json::Value jRequestParams;
if (!getRequestValue("params", jRequestParams, jRequest, false, jResponse))
return;
if (jRequestParams.isMember("index"))
{
unsigned index;
if (getRequestValue("index", index, jRequestParams, false, jResponse))
{
try
{
PoolManager::p().setActiveConnection(index);
}
catch (const std::exception& _ex)
{
std::string what = _ex.what();
jResponse["error"]["code"] = -422;
jResponse["error"]["message"] = what;
return;
}
}
else
{
jResponse["error"]["code"] = -422;
jResponse["error"]["message"] = "Invalid index";
return;
}
}
else
{
string uri;
if (getRequestValue("URI", uri, jRequestParams, false, jResponse))
{
try
{
PoolManager::p().setActiveConnection(uri);
}
catch (const std::exception& _ex)
{
std::string what = _ex.what();
jResponse["error"]["code"] = -422;
jResponse["error"]["message"] = what;
return;
}
}
else
{
jResponse["error"]["code"] = -422;
jResponse["error"]["message"] = "Invalid index";
return;
}
}
jResponse["result"] = true;
}
else if (_method == "miner_removeconnection")
{
if (!checkApiWriteAccess(m_readonly, jResponse))
return;
Json::Value jRequestParams;
if (!getRequestValue("params", jRequestParams, jRequest, false, jResponse))
return;
unsigned index;
if (!getRequestValue("index", index, jRequestParams, false, jResponse))
return;
try
{
PoolManager::p().removeConnection(index);
jResponse["result"] = true;
}
catch (const std::exception& _ex)
{
std::string what = _ex.what();
jResponse["error"]["code"] = -422;
jResponse["error"]["message"] = what;
return;
}
}
else if (_method == "miner_getscramblerinfo")
{
jResponse["result"] = Farm::f().get_nonce_scrambler_json();
}
else if (_method == "miner_setscramblerinfo")
{
if (!checkApiWriteAccess(m_readonly, jResponse))
return;
Json::Value jRequestParams;
if (!getRequestValue("params", jRequestParams, jRequest, false, jResponse))
return;
bool any_value_provided = false;
uint64_t nonce = Farm::f().get_nonce_scrambler();
unsigned exp = Farm::f().get_segment_width();
if (jRequestParams.isMember("noncescrambler"))
{
string nonceHex;
any_value_provided = true;
nonceHex = jRequestParams["noncescrambler"].asString();
if (nonceHex.substr(0, 2) == "0x")
{
try
{
nonce = std::stoul(nonceHex, nullptr, 16);
}
catch (const std::exception&)
{
jResponse["error"]["code"] = -422;
jResponse["error"]["message"] = "Invalid nonce";
return;
}
}
else
{
// as we already know there is a "noncescrambler" element we can use optional=false
if (!getRequestValue("noncescrambler", nonce, jRequestParams, false, jResponse))
return;
}
}
if (jRequestParams.isMember("segmentwidth"))
{
any_value_provided = true;
if (!getRequestValue("segmentwidth", exp, jRequestParams, false, jResponse))
return;
}
if (!any_value_provided)
{
jResponse["error"]["code"] = -32602;
jResponse["error"]["message"] = "Missing parameters";
return;
}
if (exp < 10)
exp = 10; // Not below
if (exp > 50)
exp = 40; // Not above
Farm::f().set_nonce_scrambler(nonce);
Farm::f().set_nonce_segment_width(exp);
jResponse["result"] = true;
}
else if (_method == "miner_pausegpu")
{
if (!checkApiWriteAccess(m_readonly, jResponse))
return;
Json::Value jRequestParams;
if (!getRequestValue("params", jRequestParams, jRequest, false, jResponse))
return;
unsigned index;
if (!getRequestValue("index", index, jRequestParams, false, jResponse))
return;
bool pause;
if (!getRequestValue("pause", pause, jRequestParams, false, jResponse))
return;
auto const& miner = Farm::f().getMiner(index);
if (miner)
{
if (pause)
miner->pause(MinerPauseEnum::PauseDueToAPIRequest);
else
miner->resume(MinerPauseEnum::PauseDueToAPIRequest);
jResponse["result"] = true;
}
else
{
jResponse["error"]["code"] = -422;
jResponse["error"]["message"] = "Index out of bounds";
return;
}
}
else if (_method == "miner_setverbosity")
{
if (!checkApiWriteAccess(m_readonly, jResponse))
return;
Json::Value jRequestParams;
if (!getRequestValue("params", jRequestParams, jRequest, false, jResponse))
return;
unsigned verbosity;
if (!getRequestValue("verbosity", verbosity, jRequestParams, false, jResponse))
return;
if (verbosity >= LOG_NEXT)
{
jResponse["error"]["code"] = -422;
jResponse["error"]["message"] =
"Verbosity out of bounds (0-" + to_string(LOG_NEXT - 1) + ")";
return;
}
cnote << "Setting verbosity level to " << verbosity;
g_logOptions = verbosity;
jResponse["result"] = true;
}
else
{
// Any other method not found
jResponse["error"]["code"] = -32601;
jResponse["error"]["message"] = "Method not found";
}
}
void ApiConnection::recvSocketData()
{
boost::asio::async_read(m_socket, m_recvBuffer, boost::asio::transfer_at_least(1),
m_io_strand.wrap(boost::bind(&ApiConnection::onRecvSocketDataCompleted, this,
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)));
}
void ApiConnection::onRecvSocketDataCompleted(
const boost::system::error_code& ec, std::size_t bytes_transferred)
{
/*
Standard http request detection pattern
1st group : any UPPERCASE word
2nd group : the path
3rd group : HTTP version
*/
static std::regex http_pattern("^([A-Z]{1,6}) (\\/[\\S]*) (HTTP\\/1\\.[0-9]{1})");
std::smatch http_matches;
if (!ec && bytes_transferred > 0)
{
// Extract received message and free the buffer
std::string rx_message(
boost::asio::buffer_cast<const char*>(m_recvBuffer.data()), bytes_transferred);
m_recvBuffer.consume(bytes_transferred);
m_message.append(rx_message);
std::string line;
std::string linedelimiter;
std::size_t linedelimiteroffset;
if (m_message.size() < 4)
return; // Wait for other data to come in
if (std::regex_search(
m_message, http_matches, http_pattern, std::regex_constants::match_default))
{
// We got an HTTP request
std::string http_method = http_matches[1].str();
std::string http_path = http_matches[2].str();
std::string http_ver = http_matches[3].str();
// Do we support method ?
if (http_method != "GET")
{
std::string what = "Method " + http_method + " not allowed";
std::stringstream ss;
ss << http_ver << " "
<< "405 Method not allowed\r\n"
<< "Server: " << ethminer_get_buildinfo()->project_name_with_version << "\r\n"
<< "Content-Type: text/plain\r\n"
<< "Content-Length: " << what.size() << "\r\n\r\n"
<< what << "\r\n";
sendSocketData(ss.str(), true);
m_message.clear();
return;
}
// Do we support path ?
if (http_path != "/" && http_path != "/getstat1")
{
std::string what =
"The requested resource " + http_path + " not found on this server";
std::stringstream ss;
ss << http_ver << " "
<< "404 Not Found\r\n"
<< "Server: " << ethminer_get_buildinfo()->project_name_with_version << "\r\n"
<< "Content-Type: text/plain\r\n"
<< "Content-Length: " << what.size() << "\r\n\r\n"
<< what << "\r\n";
sendSocketData(ss.str(), true);
m_message.clear();
return;
}
//// Get all the lines - we actually don't care much
//// until we support other http methods or paths
//// Keep this for future use (if any)
//// Remember to #include <boost/algorithm/string.hpp>
// std::vector<std::string> lines;
// boost::split(lines, m_message, [](char _c) { return _c == '\n'; });
std::stringstream ss; // Builder of the response
if (http_method == "GET" && (http_path == "/" || http_path == "/getstat1"))
{
try
{
std::string body = getHttpMinerStatDetail();
ss.clear();
ss << http_ver << " "
<< "200 Ok Error\r\n"
<< "Server: " << ethminer_get_buildinfo()->project_name_with_version
<< "\r\n"
<< "Content-Type: text/html; charset=utf-8\r\n"
<< "Content-Length: " << body.size() << "\r\n\r\n"
<< body << "\r\n";
}
catch (const std::exception& _ex)
{
std::string what = "Internal error : " + std::string(_ex.what());
ss.clear();
ss << http_ver << " "
<< "500 Internal Server Error\r\n"
<< "Server: " << ethminer_get_buildinfo()->project_name_with_version
<< "\r\n"
<< "Content-Type: text/plain\r\n"
<< "Content-Length: " << what.size() << "\r\n\r\n"
<< what << "\r\n";
}
}
sendSocketData(ss.str(), true);
m_message.clear();
}
else
{
// We got a Json request
// Process each line in the transmission
linedelimiter = "\n";
linedelimiteroffset = m_message.find(linedelimiter);
while (linedelimiteroffset != string::npos)
{
if (linedelimiteroffset > 0)
{
line = m_message.substr(0, linedelimiteroffset);
boost::trim(line);
if (!line.empty())
{
// Test validity of chunk and process
Json::Value jMsg;
Json::Value jRes;
Json::Reader jRdr;
if (jRdr.parse(line, jMsg))
{
try
{
// Run in sync so no 2 different async reads may overlap
processRequest(jMsg, jRes);
}
catch (const std::exception& _ex)
{
jRes = Json::Value();
jRes["jsonrpc"] = "2.0";
jRes["id"] = Json::Value::null;
jRes["error"]["errorcode"] = "500";
jRes["error"]["message"] = _ex.what();
}
}
else
{
jRes = Json::Value();
jRes["jsonrpc"] = "2.0";
jRes["id"] = Json::Value::null;
jRes["error"]["errorcode"] = "-32700";
string what = jRdr.getFormattedErrorMessages();
boost::replace_all(what, "\n", " ");
cwarn << "API : Got invalid Json message " << what;
jRes["error"]["message"] = "Json parse error : " + what;
}
// Send response to client
sendSocketData(jRes);
}
}
// Next line (if any)
m_message.erase(0, linedelimiteroffset + 1);
linedelimiteroffset = m_message.find(linedelimiter);
}
// Eventually keep reading from socket
if (m_socket.is_open())
recvSocketData();
}
}
else
{
disconnect();
}
}
void ApiConnection::sendSocketData(Json::Value const& jReq, bool _disconnect)
{
if (!m_socket.is_open())
return;
std::stringstream line;
line << Json::writeString(m_jSwBuilder, jReq) << std::endl;
sendSocketData(line.str(), _disconnect);
}
void ApiConnection::sendSocketData(std::string const& _s, bool _disconnect)
{
if (!m_socket.is_open())
return;
std::ostream os(&m_sendBuffer);
os << _s;
async_write(m_socket, m_sendBuffer,
m_io_strand.wrap(boost::bind(&ApiConnection::onSendSocketDataCompleted, this,
boost::asio::placeholders::error, _disconnect)));
}
void ApiConnection::onSendSocketDataCompleted(const boost::system::error_code& ec, bool _disconnect)
{
if (ec || _disconnect)
disconnect();
}
Json::Value ApiConnection::getMinerStat1()
{
auto connection = PoolManager::p().getActiveConnection();
TelemetryType t = Farm::f().Telemetry();
auto runningTime =
std::chrono::duration_cast<std::chrono::minutes>(steady_clock::now() - t.start);
ostringstream totalMhEth;
ostringstream totalMhDcr;
ostringstream detailedMhEth;
ostringstream detailedMhDcr;
ostringstream tempAndFans;
ostringstream poolAddresses;
ostringstream invalidStats;
totalMhEth << std::fixed << std::setprecision(0) << t.farm.hashrate / 1000.0f << ";"
<< t.farm.solutions.accepted << ";" << t.farm.solutions.rejected;
totalMhDcr << "0;0;0"; // DualMining not supported
invalidStats << t.farm.solutions.failed << ";0"; // Invalid + Pool switches
poolAddresses << connection->Host() << ':' << connection->Port();
invalidStats << ";0;0"; // DualMining not supported
int gpuIndex;
int numGpus = t.miners.size();
for (gpuIndex = 0; gpuIndex < numGpus; gpuIndex++)
{
detailedMhEth << std::fixed << std::setprecision(0)
<< t.miners.at(gpuIndex).hashrate / 1000.0f
<< (((numGpus - 1) > gpuIndex) ? ";" : "");
detailedMhDcr << "off"
<< (((numGpus - 1) > gpuIndex) ? ";" : ""); // DualMining not supported
}
for (gpuIndex = 0; gpuIndex < numGpus; gpuIndex++)
{
tempAndFans << t.miners.at(gpuIndex).sensors.tempC << ";"
<< t.miners.at(gpuIndex).sensors.fanP
<< (((numGpus - 1) > gpuIndex) ? ";" : ""); // Fetching Temp and Fans
}