-
Notifications
You must be signed in to change notification settings - Fork 2
/
lwsock.hpp
3611 lines (3223 loc) · 111 KB
/
lwsock.hpp
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
// The MIT License (MIT)
//
// Copyright (C) 2016 hfuj13@gmail.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#pragma once
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/tcp.h>
#include <regex.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <cassert>
#include <cerrno>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <array>
#include <chrono>
#include <exception>
#include <functional>
#include <iomanip>
#include <ios>
#include <iostream>
#include <memory>
#include <random>
#include <sstream>
#include <string>
#include <system_error>
#include <thread>
#include <tuple>
#include <type_traits>
#include <vector>
namespace lwsock {
// var string: variable name
// func_name string: function name
// param string: parameter
#define DECLARE_CALLEE(var, func_name, param) \
std::ostringstream var; \
{ var << func_name << param; }
constexpr char Version[] = "v1.4.1";
constexpr char B64chs[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
constexpr char GUID[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
constexpr char EOL[] = "\r\n"; // end of line
constexpr uint8_t Magic[] = {49, 49, 104, 102, 117, 106, 49, 51};
/// WebSocket(RFC6455) Opcode enum
enum class Opcode {
CONTINUE = 0x0,
TEXT = 0x1,
BINARY = 0x2,
CLOSE = 0x8,
PING = 0x9,
PONG = 0xa,
};
/// @brief lwsock error code
///
/// negative value. (positive value is system error)
/// @todo readjust errorcode
enum class LwsockErrc: int32_t {
NO_ERROR = 0,
COULD_NOT_OPEN_AVAILABLE_SOCKET = -102,
SOCKET_CLOSED = -103,
INVALID_HANDSHAKE = -104,
FRAME_ERROR = -106,
INVALID_PARAM = -107,
INVALID_AF = -108,
INVALID_MODE = -109,
BAD_MESSAGE = -110,
TIMED_OUT = -111,
};
enum class LogLevel: int32_t {
#if 0
DEBUG = 1,
DEBUG,
INFO,
WARNING,
ERROR,
#else
UNDER_LVL = 0,
VERBOSE,
DEBUG,
INFO,
WARNING,
ERROR,
SILENT,
OVER_LVL
#endif
};
/// @brief get emum class value as int
///
/// @param [in] value
/// @retval int value
template<typename T> auto as_int(const T value) -> typename std::underlying_type<T>::type
{
return static_cast<typename std::underlying_type<T>::type>(value);
}
/// @brief transform the adress family to string
///
/// @pram [in] af: AF_INET, AF_INET6, AF_UNSPEC
/// @retval string
inline std::string af2str(int af)
{
std::string str;
switch (af) {
case AF_INET:
str = "AF_INET";
break;
case AF_INET6:
str = "AF_INET6";
break;
case AF_UNSPEC:
str = "AF_UNSPEC";
break;
default:
str = std::to_string(af);
break;
}
return str;
}
/// @brief get now timestamp. UTC only yet
///
/// @param [in] parenthesis: ture: output with '[' and ']' <br>
// false : output with raw
/// @retval string transformed timestamp (e.g. [2016-12-11T13:24:13.058] or 2016-12-11T13:24:13.058 etc.). the output format is like the ISO8601 (that is it include milliseconds)
/// @todo correspond TIME ZONE
inline std::string now_timestamp(bool parenthesis)
{
std::chrono::time_point<std::chrono::system_clock> tp = std::chrono::system_clock::now();
//std::chrono::nanoseconds nsec_since_epoch = std::chrono::duration_cast<std::chrono::nanoseconds>(tp.time_since_epoch());
std::chrono::milliseconds msec_since_epoch = std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch());
//std::chrono::milliseconds msec_since_epoch = std::chrono::duration_cast<std::chrono::milliseconds>(nsec_since_epoch);
std::chrono::seconds sec = std::chrono::duration_cast<std::chrono::seconds>(msec_since_epoch);
std::time_t tt = sec.count();
std::size_t msec = msec_since_epoch.count() % 1000;
//std::size_t nsec = nsec_since_epoch.count() % (1000 * 1000);
struct tm stm = {0};
tzset();
gmtime_r(&tt, &stm);
std::ostringstream oss;
oss << (stm.tm_year+1900) << '-'
<< std::setw(2) << std::setfill('0') << (stm.tm_mon+1) << '-'
<< std::setw(2) << std::setfill('0') << stm.tm_mday
<< 'T'
<< std::setw(2) << std::setfill('0') << stm.tm_hour
<< ':'
<< std::setw(2) << std::setfill('0') << stm.tm_min
<< ':'
<< std::setw(2) << std::setfill('0') << stm.tm_sec
<< '.' << std::setw(3) << std::setfill('0') << msec
//<< std::setw(3) << std::setfill('0') << nsec
;
std::string str;
if (parenthesis) {
str += "[" + oss.str() + "]";
}
else {
str += oss.str();
}
return str;
}
/// @brief get timestamp by cloed parenthesis
///
/// @retval string transformed timestamp (e.g. [2016-12-11T13:24:13.058])
inline std::string now_timestamp()
{
return now_timestamp(true);
}
/// @brief trim specified characters
///
/// @param [in] str: string
/// @param [in] charset: character set (specified by a string) what you want to delete
/// @retval trimed string
inline std::string trim(const std::string& str, const std::string& charset)
{
std::string::size_type p0 = str.find_first_not_of(charset);
if (p0 == std::string::npos) {
p0 = 0;
}
std::string::size_type p1 = str.find_last_not_of(charset);
std::string result = str.substr(p0, p1 - p0 + 1);
return result;
}
/// @brief trim white spaces
///
/// @param [in] str: string
/// @retval trimed string
inline std::string trim(const std::string& str)
{
return trim(str, " \t\v\r\n");
}
/// @brief transform the string to the lowercase string
///
/// @param [in] str: string
/// @retval lower case string
inline std::string str2lower(const std::string& str)
{
std::string result;
std::transform(std::begin(str), std::end(str), std::back_inserter(result), ::tolower);
return result;
}
// a logger
class alog final {
public:
class scoped final {
public:
scoped() = delete;
scoped(const scoped&) = default;
scoped(scoped&&) = default;
scoped(const std::string& str)
: scoped(LogLevel::DEBUG, str) {}
scoped(LogLevel loglevel, const std::string& str)
: loglevel_(loglevel), oss_(str)
{
log_(loglevel_) << "[[[[ " << oss_.str() << std::endl;
}
~scoped()
{
log_(loglevel_) << "]]]] " << oss_.str() << std::endl;
}
std::string str()
{
return oss_.str();
}
scoped& clear()
{
oss_.str("");
return *this;
}
template<typename T> friend std::ostream& operator<<(scoped& slog, const T& rhs);
private:
alog& log_ = alog::get_instance();
LogLevel loglevel_ = LogLevel::DEBUG;
std::ostringstream oss_;
};
static alog& get_instance()
{
return get_instance(nullptr);
}
static alog& get_instance(std::ostream& ost)
{
return get_instance(&ost);
}
bool operator==(const alog& rhs) const
{
return &rhs == this || (rhs.level_ == level_ && rhs.ost_ == ost_);
}
bool operator!=(const alog& rhs) const
{
return (rhs.level_ != level_ || rhs.ost_ != ost_);
}
template<typename... Args> static std::string format(const std::string& fmt, Args... args)
{
std::string buff; // Used only for dynamic area control.
int ret = snprintf(&buff[0], buff.capacity(), fmt.c_str(), args...);
if (ret >= buff.capacity()) {
buff.reserve(ret+1);
ret = snprintf(&buff[0], buff.capacity(), fmt.c_str(), args...);
}
else if (ret < 0) {
abort();
}
std::string str(buff.c_str());
return str;
}
// for verbose
std::ostream& v()
{
return (*this)(LogLevel::VERBOSE) << "[V]";
}
template<typename... Args> std::ostream& v(const std::string& fmt, Args... args)
{
return v() << format(fmt, args...) << std::flush;
}
// for debug
std::ostream& d()
{
return (*this)(LogLevel::DEBUG) << "[D]";
}
template<typename... Args> std::ostream& d(const std::string& fmt, Args... args)
{
return d() << format(fmt, args...) << std::flush;
}
// for info
std::ostream& i()
{
return (*this)(LogLevel::INFO) << "[I]";
}
template<typename... Args> std::ostream& i(const std::string& fmt, Args... args)
{
return i() << format(fmt, args...) << std::flush;
}
// for warning
std::ostream& w()
{
return (*this)(LogLevel::WARNING) << "[W]";
}
template<typename... Args> std::ostream& w(const std::string& fmt, Args... args)
{
return w() << format(fmt, args...) << std::flush;
}
// for error
std::ostream& e()
{
return (*this)(LogLevel::ERROR) << "[E]";
}
template<typename... Args> std::ostream& e(const std::string& fmt, Args... args)
{
return e() << format(fmt, args...) << std::flush;
}
// ログレベル設定が何であっても強制的に出力する
std::ostream& force()
{
return (*this)();
}
template<typename... Args> std::ostream& force(const std::string& fmt, Args... args)
{
return force() << format(fmt, args...) << std::flush;
}
template<typename T> friend std::ostream& operator<<(alog& log, const T& rhs);
alog& level(LogLevel lvl)
{
assert(LogLevel::UNDER_LVL < lvl && lvl < LogLevel::OVER_LVL);
if (lvl <= LogLevel::UNDER_LVL || LogLevel::OVER_LVL <= lvl) {
abort();
}
level_ = lvl;
return *this;
}
LogLevel level()
{
return level_;
}
alog& ostream(std::ostream& ost)
{
ost_ = &ost;
return *this;
}
private:
alog() = default;
alog& operator=(const alog&) = delete;
std::ostream& output()
{
return (*ost_) << now_timestamp() << "[thd:" << std::this_thread::get_id() << "] ";
}
std::ostream& operator()()
{
return output();
}
std::ostream& operator()(LogLevel lvl)
{
return lvl >= level_ ? output() : null_ost_;
}
static alog& get_instance(std::ostream* ost)
{
static alog log;
if (ost != nullptr) {
log.ost_ = ost;
}
return log;
}
std::ostream null_ost_{nullptr}; // /dev/null like ostream
LogLevel level_ = LogLevel::SILENT;
std::ostream* ost_ = &null_ost_;
};
template<typename T> std::ostream& operator<<(alog& log, const T& rhs)
{
return (*log.ost_) << rhs;
}
template<typename T> std::ostream& operator<<(alog::scoped& slog, const T& rhs)
{
return slog.oss_ << rhs;
}
/// @brief Error class
///
/// this class contains errno(3), getaddrinfo(3)'s error, regcom(3)'s error or lwsock Errcode.
class Error final {
public:
Error() = delete;
Error(const Error&) = default;
Error(Error&&) = default;
Error(int errcode, uint32_t line, const std::string& what_arg)
: errcode_(errcode), line_(line)
{
std::ostringstream oss;
if (line_ > 0) {
oss << "line:" << line_ << ". " << "errcode=" << errcode_ << ". " << what_arg;
what_ = oss.str();
}
else {
oss << "errcode=" << errcode_ << ". " << what_arg;
what_ = oss.str();
}
alog& log = alog::get_instance();
log.e() << what_ << std::endl;
}
Error(int errcode, uint32_t line)
: Error(errcode, line, "")
{ }
Error(int errcode, const std::string& what_arg)
: Error(errcode, 0, what_arg)
{ }
explicit Error(int errcode)
: Error(errcode, 0, "")
{ }
~Error() = default;
/// @brief get error code
///
/// @retval error code. errno(3), getaddrinfo(3), regcomp(3), lwsock Errcode.
int code()
{
return errcode_;
}
void prefix(const std::string& prefix)
{
what_ = prefix + what_;
}
/// @brief get reason string
///
/// @retval reason string
const char* what() const
{
return what_.c_str();
}
private:
int errcode_ = 0;
uint32_t line_ = 0; // the line when the error occurred
std::string what_;
};
class CRegexException final: public std::exception {
public:
CRegexException() = delete;
CRegexException(const CRegexException&) = default;
CRegexException(CRegexException&&) = default;
explicit CRegexException(const Error& error)
: error_(error)
{ }
~CRegexException() = default;
const char* what() const noexcept override
{
error_.prefix("CRegexException: ");
return error_.what();
}
/// @brief get exception code (error code etc.)
///
/// @retavl error code
virtual int code()
{
return error_.code();
}
private:
mutable Error error_;
};
class GetaddrinfoException final: public std::exception {
public:
GetaddrinfoException() = delete;
GetaddrinfoException(const GetaddrinfoException&) = default;
GetaddrinfoException(GetaddrinfoException&&) = default;
explicit GetaddrinfoException(const Error& error)
: error_(error)
{ }
~GetaddrinfoException() = default;
const char* what() const noexcept override
{
error_.prefix("GetaddrinfoException: ");
return error_.what();
}
/// @brief get exception code (error code etc.)
///
/// @retavl error code
virtual int code()
{
return error_.code();
}
private:
mutable Error error_;
};
/// @brief libray error exception class
class LwsockException final: public std::exception {
public:
LwsockException() = delete;
LwsockException(const LwsockException&) = default;
LwsockException(LwsockException&&) = default;
explicit LwsockException(const Error& error)
: error_(error)
{ }
~LwsockException() = default;
const char* what() const noexcept override
{
error_.prefix("LwsockException: ");
return error_.what();
}
/// @brief get exception code (error code etc.)
///
/// @retavl error code
virtual int code()
{
return error_.code();
}
private:
mutable Error error_;
};
/// @brief system_error exception class. this is a wrapper class because i want to output logs.
///
class SystemErrorException final: public std::exception {
public:
SystemErrorException() = delete;
SystemErrorException(const SystemErrorException&) = default;
SystemErrorException(SystemErrorException&&) = default;
explicit SystemErrorException(const Error& error)
: error_(error)
{ }
~SystemErrorException() = default;
const char* what() const noexcept override
{
error_.prefix("SystemErrorException: ");
return error_.what();
}
/// @brief get exception code (error code etc.)
///
/// @retavl error code
virtual int code()
{
return error_.code();
}
private:
mutable Error error_;
};
/// @brief regex(3) wrapper
///
/// regex(3) wrapper class. because the std::regex, depending on the version of android it does not work properly.
class CRegex final {
public:
CRegex() = delete;
/// @exception CRegexException
CRegex(const std::string& re, size_t nmatch)
: nmatch_(nmatch)
{
alog& log = alog::get_instance();
//log(LogLevel::DEBUG) << "CRegex(re=\"" << re << "\", nmatch=" << nmatch << ')' << std::endl;
log.d() << "CRegex(re=\"" << re << "\", nmatch=" << nmatch << ')' << std::endl;
int err = regcomp(®buff_, re.c_str(), REG_EXTENDED);
if (err != 0) {
std::ostringstream oss;
char errbuf[256] = {0};
regerror(err, ®buff_, errbuf, sizeof errbuf);
oss << "CRegex(re=\"" << re << "\", nmatch=" << nmatch << ") " << errbuf;
throw CRegexException(Error(err, oss.str()));
}
}
~CRegex()
{
regfree(®buff_);
}
/// @brief execute regex
///
/// @param [in] src: string for regex
/// @retval matched string set. if empty then no matched
std::vector<std::string> exec(const std::string& src)
{
std::vector<std::string> matched;
std::vector<regmatch_t> match(nmatch_, {-1, -1});
int err = regexec(®buff_, src.c_str(), match.size(), &match[0], 0);
if (err != 0) {
return matched;
}
for (auto& elm : match) {
int start = elm.rm_so;
int end = elm.rm_eo;
if (start == -1 || end == -1) {
continue;
}
std::string str(std::begin(src)+start, std::begin(src)+end);
matched.push_back(str);
}
return matched;
}
private:
regex_t regbuff_{};
size_t nmatch_ = 0;
};
/// @brief base64 encoder
///
/// This referred the https://opensource.apple.com/source/QuickTimeStreamingServer/QuickTimeStreamingServer-452/CommonUtilitiesLib/base64.c
/// @param [in] src_data: array or vector
/// @param [in] src_data_sz: *src_data size. bytes
/// @retval base64 encoded string
inline std::string b64encode(const void* src_data, int src_data_sz)
{
assert(src_data_sz >= 0);
std::string dst;
const uint8_t* src = static_cast<const uint8_t*>(src_data);
int idx = 0;
for (; idx < src_data_sz - 2; idx += 3) {
dst += B64chs[(src[idx] >> 2) & 0x3F];
dst += B64chs[((src[idx] & 0x3) << 4) | ((src[idx + 1] & 0xF0) >> 4)];
dst += B64chs[((src[idx + 1] & 0xF) << 2) | ((src[idx + 2] & 0xC0) >> 6)];
dst += B64chs[src[idx + 2] & 0x3F];
}
if (idx < src_data_sz) {
dst += B64chs[(src[idx] >> 2) & 0x3F];
if (idx == (src_data_sz - 1)) {
dst += B64chs[((src[idx] & 0x3) << 4)];
dst += '=';
}
else {
dst += B64chs[((src[idx] & 0x3) << 4) | ((src[idx + 1] & 0xF0) >> 4)];
dst += B64chs[((src[idx + 1] & 0xF) << 2)];
}
dst += '=';
}
return dst;
}
/// @brief base64 decoder
///
/// @param [in] src: base64 encoded string
/// @retval base64 decoded data
/// @exception LwsockException
inline std::vector<uint8_t> b64decode(const std::string& src)
{
DECLARE_CALLEE(callee, __func__, "(src=\"" << src << "\")");
if (src.size() % 4 != 0) {
int err = as_int(LwsockErrc::INVALID_PARAM);
std::ostringstream oss;
oss << callee.str() << " src.size()=" << src.size() << " is illegal.";
throw LwsockException(Error(err, oss.str()));
}
constexpr int BLOCK_SZ = 4;
std::vector<uint8_t> dst;
for (size_t i = 0; i < src.size(); i += BLOCK_SZ) {
const char* ptr = &src[i];
std::array<uint8_t, 3> tmp;
uint8_t value[BLOCK_SZ] = {0};
int j = 0;
for (; j < BLOCK_SZ; ++j) {
if (std::isupper(ptr[j])) {
value[j] = ptr[j] - 65;
}
else if (std::islower(ptr[j])) {
value[j] = ptr[j] - 71;
}
else if (std::isdigit(ptr[j])) {
value[j] = ptr[j] + 4;
}
else if (ptr[j] == '+') {
value[j] = ptr[j] + 19;
}
else if (ptr[j] == '/') {
value[j] = ptr[j] + 16;
}
else if (ptr[j] == '=') {
break;
}
else {
int err = as_int(LwsockErrc::INVALID_PARAM);
std::ostringstream oss;
char ch = ptr[j];
oss << callee.str() << " illegal char='" << ch << '\'';
throw LwsockException(Error(err, oss.str()));
}
}
tmp[0] = value[0] << 2 | value[1] >> 4;
tmp[1] = value[1] << 4 | value[2] >> 2;
tmp[2] = value[2] << 6 | value[3];
std::copy(std::begin(tmp), std::begin(tmp) + j - 1, std::back_inserter(dst));
}
return dst;
}
/// @brief sha1 class
///
/// This referred the RFC3174 Section 7.
class Sha1 final {
public:
static constexpr int SHA1_HASH_SIZE = 20;
static constexpr int MESSAGE_BLOCK_SIZE = 64; // 512-bit message blocks
enum {
shaSuccess = 0,
shaNull, /* Null pointer parameter */
shaInputTooLong, /* input data too long */
shaStateError /* called Input after Result */
};
Sha1() = delete;
Sha1(const Sha1&) = delete;
Sha1(Sha1&&) = delete;
// This will hold context information for the SHA-1 hashing operation
class Context_t final {
public:
Context_t()
{
Intermediate_Hash[0] = 0x67452301;
Intermediate_Hash[1] = 0xEFCDAB89;
Intermediate_Hash[2] = 0x98BADCFE;
Intermediate_Hash[3] = 0x10325476;
Intermediate_Hash[4] = 0xC3D2E1F0;
}
Context_t(const Context_t&) = default;
Context_t(Context_t&&) = default;
~Context_t() = default;
Context_t& operator=(const Context_t&) = default;
Context_t& operator=(Context_t&&) = default;
uint32_t Intermediate_Hash[SHA1_HASH_SIZE / 4]; /* Message Digest */
uint32_t Length_Low = 0; /* Message length in bits */
uint32_t Length_High = 0; /* Message length in bits */
int_least16_t Message_Block_Index = 0;
uint8_t Message_Block[MESSAGE_BLOCK_SIZE]; /* 512-bit message blocks */
};
static int32_t Input(Context_t& dst, const void* message_array, int length)
{
assert(message_array != nullptr);
assert(length >= 0);
const uint8_t* p = static_cast<const uint8_t*>(message_array);
for (int i = 0; length > 0; --length, ++i) {
dst.Message_Block[dst.Message_Block_Index++] = (p[i] & 0xFF);
dst.Length_Low += 8;
if (dst.Length_Low == 0) {
dst.Length_High++;
if (dst.Length_High == 0) {
/* Message is too long */
return EMSGSIZE;
}
}
if (dst.Message_Block_Index == MESSAGE_BLOCK_SIZE) {
dst = SHA1ProcessMessageBlock(dst);
}
}
return 0;;
}
static int32_t Result(uint8_t* Message_Digest, size_t sz, const Context_t& context)
{
assert(Message_Digest != nullptr);
assert(sz == SHA1_HASH_SIZE);
Context_t ctx = SHA1PadMessage(context);
for (int i = 0; i < MESSAGE_BLOCK_SIZE; ++i) {
/* message may be sensitive, clear it out */
ctx.Message_Block[i] = 0;
}
// and clear length
ctx.Length_Low = 0;
ctx.Length_High = 0;
for (size_t i = 0; i < sz; ++i) {
Message_Digest[i] = ctx.Intermediate_Hash[i>>2] >> 8 * ( 3 - ( i & 0x03 ) );
}
return 0;
}
private:
// SHA1ProcessMessageBlock
// Description:
// This function will process the next 512 bits of the message
// stored in the Message_Block array.
// Comments:
// Many of the variable names in this code, especially the
// single character names, were used because those were the
// names used in the publication.
static Context_t SHA1ProcessMessageBlock(const Context_t& context)
{
Context_t ctx(context);
constexpr uint32_t K[] = { // Constants defined in SHA-1
0x5A827999,
0x6ED9EBA1,
0x8F1BBCDC,
0xCA62C1D6
};
int t = 0; // Loop counter
uint32_t temp = 0; // Temporary word value
uint32_t W[80] = {0}; // Word sequence
uint32_t A = 0, B = 0, C = 0, D = 0, E = 0; // Word buffers
// Initialize the first 16 words in the array W
for (t = 0; t < 16; ++t) {
W[t] = ctx.Message_Block[t * 4] << 24;
W[t] |= ctx.Message_Block[t * 4 + 1] << 16;
W[t] |= ctx.Message_Block[t * 4 + 2] << 8;
W[t] |= ctx.Message_Block[t * 4 + 3];
}
for (t = 16; t < 80; ++t) {
W[t] = SHA1CircularShift(1, W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]);
}
A = ctx.Intermediate_Hash[0];
B = ctx.Intermediate_Hash[1];
C = ctx.Intermediate_Hash[2];
D = ctx.Intermediate_Hash[3];
E = ctx.Intermediate_Hash[4];
for (t = 0; t < 20; ++t) {
temp = SHA1CircularShift(5, A) + ((B & C) | ((~B) & D)) + E + W[t] + K[0];
E = D;
D = C;
C = SHA1CircularShift(30,B);
B = A;
A = temp;
}
for (t = 20; t < 40; ++t) {
temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1];
E = D;
D = C;
C = SHA1CircularShift(30,B);
B = A;
A = temp;
}
for (t = 40; t < 60; ++t) {
temp = SHA1CircularShift(5,A) + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2];
E = D;
D = C;
C = SHA1CircularShift(30,B);
B = A;
A = temp;
}
for (t = 60; t < 80; ++t) {
temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3];
E = D;
D = C;
C = SHA1CircularShift(30,B);
B = A;
A = temp;
}
ctx.Intermediate_Hash[0] += A;
ctx.Intermediate_Hash[1] += B;
ctx.Intermediate_Hash[2] += C;
ctx.Intermediate_Hash[3] += D;
ctx.Intermediate_Hash[4] += E;
ctx.Message_Block_Index = 0;
return ctx;
}
/*
* SHA1PadMessage
*
* Description:
* According to the standard, the message must be padded to an even
* 512 bits. The first padding bit must be a '1'. The last 64
* bits represent the length of the original message. All bits in
* between should be 0. This function will pad the message
* according to those rules by filling the Message_Block array
* accordingly. It will also call the ProcessMessageBlock function
* provided appropriately. When it returns, it can be assumed that
* the message digest has been computed.
*
* Parameters:
* context: [in/out]
* The context to pad
* ProcessMessageBlock: [in]
* The appropriate SHA*ProcessMessageBlock function
* Returns:
* Nothing.
*
*/
static Context_t SHA1PadMessage(const Context_t& context)
{
Context_t ctx(context);
// Check to see if the current message block is too small to hold
// the initial padding bits and length. If so, we will pad the
// block, process it, and then continue padding into a second
// block.
if (ctx.Message_Block_Index > 55) {
ctx.Message_Block[ctx.Message_Block_Index++] = 0x80;
while (ctx.Message_Block_Index < MESSAGE_BLOCK_SIZE) {
ctx.Message_Block[ctx.Message_Block_Index++] = 0;
}
ctx = SHA1ProcessMessageBlock(ctx);
while (ctx.Message_Block_Index < 56) {
ctx.Message_Block[ctx.Message_Block_Index++] = 0;
}
}
else {
ctx.Message_Block[ctx.Message_Block_Index++] = 0x80;
while (ctx.Message_Block_Index < 56) {
ctx.Message_Block[ctx.Message_Block_Index++] = 0;
}
}
/*
* Store the message length as the last 8 octets
*/
ctx.Message_Block[56] = ctx.Length_High >> 24;
ctx.Message_Block[57] = ctx.Length_High >> 16;
ctx.Message_Block[58] = ctx.Length_High >> 8;
ctx.Message_Block[59] = ctx.Length_High;
ctx.Message_Block[60] = ctx.Length_Low >> 24;
ctx.Message_Block[61] = ctx.Length_Low >> 16;
ctx.Message_Block[62] = ctx.Length_Low >> 8;
ctx.Message_Block[63] = ctx.Length_Low;
ctx = SHA1ProcessMessageBlock(ctx);
return ctx;
}