aboutsummaryrefslogtreecommitdiff
path: root/src/util/string.cpp
blob: e6c52585d828d05b4c074a4e9254412f6bfc89c2 (plain)
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
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "string.h"
#include "pointer.h"
#include "numeric.h"
#include "log.h"

#include "hex.h"
#include "porting.h"
#include "translation.h"

#include <algorithm>
#include <sstream>
#include <iomanip>
#include <map>

#ifndef _WIN32
	#include <iconv.h>
#else
	#define _WIN32_WINNT 0x0501
	#include <windows.h>
#endif

#if defined(_ICONV_H_) && (defined(__FreeBSD__) || defined(__NetBSD__) || \
	defined(__OpenBSD__) || defined(__DragonFly__))
	#define BSD_ICONV_USED
#endif

static bool parseHexColorString(const std::string &value, video::SColor &color,
		unsigned char default_alpha = 0xff);
static bool parseNamedColorString(const std::string &value, video::SColor &color);

#ifndef _WIN32

bool convert(const char *to, const char *from, char *outbuf,
		size_t outbuf_size, char *inbuf, size_t inbuf_size)
{
	iconv_t cd = iconv_open(to, from);

#ifdef BSD_ICONV_USED
	const char *inbuf_ptr = inbuf;
#else
	char *inbuf_ptr = inbuf;
#endif

	char *outbuf_ptr = outbuf;

	size_t *inbuf_left_ptr = &inbuf_size;
	size_t *outbuf_left_ptr = &outbuf_size;

	size_t old_size = inbuf_size;
	while (inbuf_size > 0) {
		iconv(cd, &inbuf_ptr, inbuf_left_ptr, &outbuf_ptr, outbuf_left_ptr);
		if (inbuf_size == old_size) {
			iconv_close(cd);
			return false;
		}
		old_size = inbuf_size;
	}

	iconv_close(cd);
	return true;
}

#ifdef __ANDROID__
// Android need manual caring to support the full character set possible with wchar_t
const char *DEFAULT_ENCODING = "UTF-32LE";
#else
const char *DEFAULT_ENCODING = "WCHAR_T";
#endif

std::wstring utf8_to_wide(const std::string &input)
{
	size_t inbuf_size = input.length() + 1;
	// maximum possible size, every character is sizeof(wchar_t) bytes
	size_t outbuf_size = (input.length() + 1) * sizeof(wchar_t);

	char *inbuf #include <config.h>

#if USE_SYSTEM_GMP || defined (__ANDROID__) || defined (ANDROID)
	#include <gmp.h>
#else
	#include <mini-gmp.h>
#endif

#include <util/sha2.h>

#include "srp.h"
//#define CSRP_USE_SHA1
#define CSRP_USE_SHA256

#define srp_dbg_data(data, datalen, prevtext) ;
/*void srp_dbg_data(unsigned char * data, size_t datalen, char * prevtext)
{
	printf(prevtext);
	size_t i;
	for (i = 0; i < datalen; i++)
	{
		printf("%02X", data[i]);
	}
	printf("\n");
}*/

static int g_initialized = 0;

#define RAND_BUFF_MAX 128
static unsigned int g_rand_idx;
static unsigned char g_rand_buff[RAND_BUFF_MAX];

void *(*srp_alloc)(size_t) = &malloc;
void *(*srp_realloc)(void *, size_t) = &realloc;
void (*srp_free)(void *) = &free;

// clang-format off
void srp_set_memory_functions(
		void *(*new_srp_alloc)(size_t),
		void *(*new_srp_realloc)(void *, size_t),
		void (*new_srp_free)(void *))
{
	srp_alloc = new_srp_alloc;
	srp_realloc = new_srp_realloc;
	srp_free = new_srp_free;
}
// clang-format on

typedef struct {
	mpz_t N;
	mpz_t g;
} NGConstant;

struct NGHex {
	const char *n_hex;
	const char *g_hex;
};

/* All constants here were pulled from Appendix A of RFC 5054 */
static struct NGHex global_Ng_constants[] = {
	{/* 1024 */
		"EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C"
		"9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE4"
		"8E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B29"
		"7BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9A"
		"FD5138FE8376435B9FC61D2FC0EB06E3",
		"2"},
	{/* 2048 */
		"AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC319294"
		"3DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310D"
		"CD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FB"
		"D5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF74"
		"7359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A"
		"436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D"
		"5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E73"
		"03CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB6"
		"94B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F"
		"9E4AFF73",
		"2"},
	{/* 4096 */
		"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
		"8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
		"302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
		"A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
		"49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8"
		"FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D"
		"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C"
		"180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"
		"3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D"
		"04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D"
		"B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226"
		"1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
		"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC"
		"E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26"
		"99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB"
		"04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2"
		"233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127"
		"D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199"
		"FFFFFFFFFFFFFFFF",
		"5"},
	{/* 8192 */
		"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
		"8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
		"302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
		"A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
		"49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8"
		"FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D"
		"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C"
		"180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"
		"3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D"
		"04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D"
		"B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226"
		"1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
		"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC"
		"E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26"
		"99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB"
		"04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2"
		"233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127"
		"D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492"
		"36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406"
		"AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918"
		"DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151"
		"2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03"
		"F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F"
		"BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA"
		"CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B"
		"B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632"
		"387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E"
		"6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA"
		"3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C"
		"5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9"
		"22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC886"
		"2F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A6"
		"6D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC5"
		"0846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268"
		"359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6"
		"FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E71"
		"60C980DD98EDD3DFFFFFFFFFFFFFFFFF",
		"13"},
	{0, 0} /* null sentinel */
};

static void delete_ng(NGConstant *ng)
{
	if (ng) {
		mpz_clear(ng->N);
		mpz_clear(ng->g);
		srp_free(ng);
	}
}

static NGConstant *new_ng(SRP_NGType ng_type, const char *n_hex, const char *g_hex)
{
	NGConstant *ng = (NGConstant *)srp_alloc(sizeof(NGConstant));

	if (!ng) return 0;

	mpz_init(ng->N);
	mpz_init(ng->g);

	if (ng_type != SRP_NG_CUSTOM) {
		n_hex = global_Ng_constants[ng_type].n_hex;
		g_hex = global_Ng_constants[ng_type].g_hex;
	}

	int rv = 0;
	rv = mpz_set_str(ng->N, n_hex, 16);
	rv = rv | mpz_set_str(ng->g, g_hex, 16);

	if (rv) {
		delete_ng(ng);
		return 0;
	}

	return ng;
}

typedef union {
	SHA_CTX sha;
	SHA256_CTX sha256;
	// SHA512_CTX sha512;
} HashCTX;

struct SRPVerifier {
	SRP_HashAlgorithm hash_alg;
	NGConstant *ng;

	char *username;
	unsigned char *bytes_B;
	int authenticated;

	unsigned char M[SHA512_DIGEST_LENGTH];
	unsigned char H_AMK[SHA512_DIGEST_LENGTH];
	unsigned char session_key[SHA512_DIGEST_LENGTH];
};

struct SRPUser {
	SRP_HashAlgorithm hash_alg;
	NGConstant *ng;

	mpz_t a;
	mpz_t A;
	mpz_t S;

	unsigned char *bytes_A;
	int authenticated;

	char *username;
	char *username_verifier;
	unsigned char *password;
	size_t password_len;

	unsigned char M[SHA512_DIGEST_LENGTH];
	unsigned char H_AMK[SHA512_DIGEST_LENGTH];
	unsigned char session_key[SHA512_DIGEST_LENGTH];
};

// clang-format off
static int hash_init(SRP_HashAlgorithm alg, HashCTX *c)
{
	switch (alg) {
#ifdef CSRP_USE_SHA1
		case SRP_SHA1: return SHA1_Init(&c->sha);
#endif
		/*
		case SRP_SHA224: return SHA224_Init(&c->sha256);
		*/
#ifdef CSRP_USE_SHA256
		case SRP_SHA256: return SHA256_Init(&c->sha256);
#endif
		/*
		case SRP_SHA384: return SHA384_Init(&c->sha512);
		case SRP_SHA512: return SHA512_Init(&c->sha512);
		*/
		default: return -1;
	};
}
static int hash_update( SRP_HashAlgorithm alg, HashCTX *c, const void *data, size_t len )
{
	switch (alg) {
#ifdef CSRP_USE_SHA1
		case SRP_SHA1: return SHA1_Update(&c->sha, data, len);
#endif
		/*
		case SRP_SHA224: return SHA224_Update(&c->sha256, data, len);
		*/
#ifdef CSRP_USE_SHA256
		case SRP_SHA256: return SHA256_Update(&c->sha256, data, len);
#endif
		/*
		case SRP_SHA384: return SHA384_Update(&c->sha512, data, len);
		case SRP_SHA512: return SHA512_Update(&c->sha512, data, len);
		*/
		default: return -1;
	};
}
static int hash_final( SRP_HashAlgorithm alg, HashCTX *c, unsigned char *md )
{
	switch (alg) {
#ifdef CSRP_USE_SHA1
		case SRP_SHA1: return SHA1_Final(md, &c->sha);
#endif
		/*
		case SRP_SHA224: return SHA224_Final(md, &c->sha256);
		*/
#ifdef CSRP_USE_SHA256
		case SRP_SHA256: return SHA256_Final(md, &c->sha256);
#endif
		/*
		case SRP_SHA384: return SHA384_Final(md, &c->sha512);
		case SRP_SHA512: return SHA512_Final(md, &c->sha512);
		*/
		default: return -1;
	};
}
static unsigned char *hash(SRP_HashAlgorithm alg, const unsigned char *d, size_t n, unsigned char *md)
{
	switch (alg) {
#ifdef CSRP_USE_SHA1
		case SRP_SHA1: return SHA1(d, n, md);
#endif
		/*
		case SRP_SHA224: return SHA224( d, n, md );
		*/
#ifdef CSRP_USE_SHA256
		case SRP_SHA256: return SHA256(d, n, md);
#endif
		/*
		case SRP_SHA384: return SHA384( d, n, md );
		case SRP_SHA512: return SHA512( d, n, md );
		*/
		default: return 0;
	};
}
static size_t hash_length(SRP_HashAlgorithm alg)
{
	switch (alg) {
#ifdef CSRP_USE_SHA1
		case SRP_SHA1: return SHA_DIGEST_LENGTH;
#endif
		/*
		case SRP_SHA224: return SHA224_DIGEST_LENGTH;
		*/
#ifdef CSRP_USE_SHA256
		case SRP_SHA256: return SHA256_DIGEST_LENGTH;
#endif
		/*
		case SRP_SHA384: return SHA384_DIGEST_LENGTH;
		case SRP_SHA512: return SHA512_DIGEST_LENGTH;
		*/
		default: return -1;
	};
}
// clang-format on

inline static int mpz_num_bytes(const mpz_t op)
{
	return (mpz_sizeinbase(op, 2) + 7) / 8;
}

inline static void mpz_to_bin(const mpz_t op, unsigned char *to)
{
	mpz_export(to, NULL, 1, 1, 1, 0, op);
}

inline static void mpz_from_bin(const unsigned char *s, size_t len, mpz_t ret)
{
	mpz_import(ret, len, 1, 1, 1, 0, s);
}

// set op to (op1 * op2) mod d, using tmp for the calculation
inline static void mpz_mulm(
	mpz_t op, const mpz_t op1, const mpz_t op2, const mpz_t d, mpz_t tmp)
{
	mpz_mul(tmp, op1, op2);
	mpz_mod(op, tmp, d);
}

// set op to (op1 + op2) mod d, using tmp for the calculation
inline static void mpz_addm(
	mpz_t op, const mpz_t op1, const mpz_t op2, const mpz_t d, mpz_t tmp)
{
	mpz_add(tmp, op1, op2);
	mpz_mod(op, tmp, d);
}

// set op to (op1 - op2) mod d, using tmp for the calculation
inline static void mpz_subm(
	mpz_t op, const mpz_t op1, const mpz_t op2, const mpz_t d, mpz_t tmp)
{
	mpz_sub(tmp, op1, op2);
	mpz_mod(op, tmp, d);
}

static SRP_Result H_nn(
	mpz_t result, SRP_HashAlgorithm alg, const mpz_t N, const mpz_t n1, const mpz_t n2)
{
	unsigned char buff[SHA512_DIGEST_LENGTH];
	size_t len_N = mpz_num_bytes(N);
	size_t len_n1 = mpz_num_bytes(n1);
	size_t len_n2 = mpz_num_bytes(n2);
	size_t nbytes = len_N + len_N;
	unsigned char *bin = (unsigned char *)srp_alloc(nbytes);
	if (!bin) return SRP_ERR;
	if (len_n1 > len_N || len_n2 > len_N) {
		srp_free(bin);
		return SRP_ERR;
	}
	memset(bin, 0, nbytes);
	mpz_to_bin(n1, bin + (len_N - len_n1));
	mpz_to_bin(n2, bin + (len_N + len_N - len_n2));
	hash(alg, bin, nbytes, buff);
	srp_free(bin);
	mpz_from_bin(buff, hash_length(alg), result);
	return SRP_OK;
}

static SRP_Result H_ns(mpz_t result, SRP_HashAlgorithm alg, const unsigned char *n,
	size_t len_n, const unsigned char *bytes, size_t len_bytes)
{
	unsigned char buff[SHA512_DIGEST_LENGTH];
	size_t nbytes = len_n + len_bytes;
	unsigned char *bin = (unsigned char *)srp_alloc(nbytes);
	if (!bin) return SRP_ERR;
	memcpy(bin, n, len_n);
	memcpy(bin + len_n, bytes, len_bytes);
	hash(alg, bin, nbytes, buff);
	srp_free(bin);
	mpz_from_bin(buff, hash_length(alg), result);
	return SRP_OK;
}

static int calculate_x(mpz_t result, SRP_HashAlgorithm alg, const unsigned char *salt,
	size_t salt_len, const char *username, const unsigned char *password,
	size_t password_len)
{
	unsigned char ucp_hash[SHA512_DIGEST_LENGTH];
	HashCTX ctx;
	hash_init(alg, &ctx);

	srp_dbg_data((char *)username, strlen(username), "Username for x: ");
	srp_dbg_data((char *)password, password_len, "Password for x: ");
	hash_update(alg, &ctx, username, strlen(username));
	hash_update(alg, &ctx, ":", 1);
	hash_update(alg, &ctx, password, password_len);

	hash_final(alg, &ctx, ucp_hash);

	return H_ns(result, alg, salt, salt_len, ucp_hash, hash_length(alg));
}

static SRP_Result update_hash_n(SRP_HashAlgorithm alg, HashCTX *ctx, const mpz_t n)
{
	size_t len = mpz_num_bytes(n);
	unsigned char *n_bytes = (unsigned char *)srp_alloc(len);
	if (!n_bytes) return SRP_ERR;
	mpz_to_bin(n, n_bytes);
	hash_update(alg, ctx, n_bytes, len);
	srp_free(n_bytes);
	return SRP_OK;
}

static SRP_Result hash_num(SRP_HashAlgorithm alg, const mpz_t n, unsigned char *dest)
{
	int nbytes = mpz_num_bytes(n);
	unsigned char *bin = (unsigned char *)srp_alloc(nbytes);
	if (!bin) return SRP_ERR;
	mpz_to_bin(n, bin);
	hash(alg, bin, nbytes, dest);
	srp_free(bin);
	return SRP_OK;
}

static SRP_Result calculate_M(SRP_HashAlgorithm alg, NGConstant *ng, unsigned char *dest,
	const char *I, const unsigned char *s_bytes, size_t s_len, const mpz_t A,
	const mpz_t B, const unsigned char *K)
{
	unsigned char H_N[SHA512_DIGEST_LENGTH];
	unsigned char H_g[SHA512_DIGEST_LENGTH];
	unsigned char H_I[SHA512_DIGEST_LENGTH];
	unsigned char H_xor[SHA512_DIGEST_LENGTH];
	HashCTX ctx;
	size_t i = 0;
	size_t hash_len = hash_length(alg);

	if (!hash_num(alg, ng->N, H_N)) return SRP_ERR;
	if (!hash_num(alg, ng->g, H_g)) return SRP_ERR;

	hash(alg, (const unsigned char *)I, strlen(I), H_I);

	for (i = 0; i < hash_len; i++)
		H_xor[i] = H_N[i] ^ H_g[i];

	hash_init(alg, &ctx);

	hash_update(alg, &ctx, H_xor, hash_len);
	hash_update(alg, &ctx, H_I, hash_len);
	hash_update(alg, &ctx, s_bytes, s_len);
	if (!update_hash_n(alg, &ctx, A)) return SRP_ERR;
	if (!update_hash_n(alg, &ctx, B)) return SRP_ERR;
	hash_update(alg, &ctx, K, hash_len);

	hash_final(alg, &ctx, dest);
	return SRP_OK;
}

static SRP_Result calculate_H_AMK(SRP_HashAlgorithm alg, unsigned char *dest,
	const mpz_t A, const unsigned char *M, const unsigned char *K)
{
	HashCTX ctx;

	hash_init(alg, &ctx);

	if (!update_hash_n(alg, &ctx, A)) return SRP_ERR;
	hash_update(alg, &ctx, M, hash_length(alg));
	hash_update(alg, &ctx, K, hash_length(alg));

	hash_final(alg, &ctx, dest);
	return SRP_OK;
}

static SRP_Result fill_buff()
{
	g_rand_idx = 0;

#ifdef WIN32
	HCRYPTPROV wctx;
#else
	FILE *fp = 0;
#endif

#ifdef WIN32

	if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
		return SRP_ERR;
	if (!CryptGenRandom(wctx, sizeof(g_rand_buff), (BYTE *)g_rand_buff)) return SRP_ERR;
	if (!CryptReleaseContext(wctx, 0)) return SRP_ERR;

#else
	fp = fopen("/dev/urandom", "r");

	if (!fp) return SRP_ERR;

	if (fread(g_rand_buff, sizeof(g_rand_buff), 1, fp) != 1) { fclose(fp); return SRP_ERR; }
	if (fclose(fp)) return SRP_ERR;
#endif
	return SRP_OK;
}

static SRP_Result mpz_fill_random(mpz_t num)
{
	// was call: BN_rand(num, 256, -1, 0);
	if (RAND_BUFF_MAX - g_rand_idx < 32)
		if (fill_buff() != SRP_OK) return SRP_ERR;
	mpz_from_bin((const unsigned char *)(&g_rand_buff[g_rand_idx]), 32, num);
	g_rand_idx += 32;
	return SRP_OK;
}

static SRP_Result init_random()
{
	if (g_initialized) return SRP_OK;
	SRP_Result ret = fill_buff();
	g_initialized = (ret == SRP_OK);
	return ret;
}

#define srp_dbg_num(num, text) ;
/*void srp_dbg_num(mpz_t num, char * prevtext)
{
	int len_num = mpz_num_bytes(num);
	char *bytes_num = (char*) srp_alloc(len_num);
	mpz_to_bin(num, (unsigned char *) bytes_num);
	srp_dbg_data(bytes_num, len_num, prevtext);
	srp_free(bytes_num);

}*/

/***********************************************************************************************************
 *
 *  Exported Functions
 *
 ***********************************************************************************************************/

// clang-format off
SRP_Result srp_create_salted_verification_key( SRP_HashAlgorithm alg,
	SRP_NGType ng_type, const char *username_for_verifier,
	const unsigned char *password, size_t len_password,
	unsigned char **bytes_s,  size_t *len_s,
	unsigned char **bytes_v, size_t *len_v,
	const char *n_hex, const char *g_hex )
{
	SRP_Result ret = SRP_OK;

	mpz_t v; mpz_init(v);
	mpz_t x; mpz_init(x);
	// clang-format on

	NGConstant *ng = new_ng(ng_type, n_hex, g_hex);

	if (!ng) goto error_and_exit;

	if (init_random() != SRP_OK) /* Only happens once */
		goto error_and_exit;

	if (*bytes_s == NULL) {
		size_t size_to_fill = 16;
		*len_s = size_to_fill;
		if (RAND_BUFF_MAX - g_rand_idx < size_to_fill)
			if (fill_buff() != SRP_OK) goto error_and_exit;
		*bytes_s = (unsigned char *)srp_alloc(size_to_fill);
		if (!*bytes_s) goto error_and_exit;
		memcpy(*bytes_s, &g_rand_buff + g_rand_idx, size_to_fill);
		g_rand_idx += size_to_fill;
	}

	if (!calculate_x(
			x, alg, *bytes_s, *len_s, username_for_verifier, password, len_password))
		goto error_and_exit;

	srp_dbg_num(x, "Server calculated x: ");

	mpz_powm(v, ng->g, x, ng->N);

	*len_v = mpz_num_bytes(v);

	*bytes_v = (unsigned char *)srp_alloc(*len_v);

	if (!*bytes_v) goto error_and_exit;

	mpz_to_bin(v, *bytes_v);

cleanup_and_exit:
	delete_ng(ng);
	mpz_clear(v);
	mpz_clear(x);
	return ret;
error_and_exit:
	ret = SRP_ERR;
	goto cleanup_and_exit;
}

// clang-format off

/* Out: bytes_B, len_B.
 *
 * On failure, bytes_B will be set to NULL and len_B will be set to 0
 */
struct SRPVerifier *srp_verifier_new(SRP_HashAlgorithm alg,
	SRP_NGType ng_type, const char *username,
	const unsigned char *bytes_s, size_t len_s,
	const unsigned char *bytes_v, size_t len_v,
	const unsigned char *bytes_A, size_t len_A,
	const unsigned char *bytes_b, size_t len_b,
	unsigned char **bytes_B, size_t *len_B,
	const char *n_hex, const char *g_hex )
{
	mpz_t v; mpz_init(v); mpz_from_bin(bytes_v, len_v, v);uot;]        = 0x48d1cc;
	colors["mediumvioletred"]        = 0xc71585;
	colors["midnightblue"]           = 0x191970;
	colors["mintcream"]              = 0xf5fffa;
	colors["mistyrose"]              = 0xffe4e1;
	colors["moccasin"]               = 0xffe4b5;
	colors["navajowhite"]            = 0xffdead;
	colors["navy"]                   = 0x000080;
	colors["oldlace"]                = 0xfdf5e6;
	colors["olive"]                  = 0x808000;
	colors["olivedrab"]              = 0x6b8e23;
	colors["orange"]                 = 0xffa500;
	colors["orangered"]              = 0xff4500;
	colors["orchid"]                 = 0xda70d6;
	colors["palegoldenrod"]          = 0xeee8aa;
	colors["palegreen"]              = 0x98fb98;
	colors["paleturquoise"]          = 0xafeeee;
	colors["palevioletred"]          = 0xdb7093;
	colors["papayawhip"]             = 0xffefd5;
	colors["peachpuff"]              = 0xffdab9;
	colors["peru"]                   = 0xcd853f;
	colors["pink"]                   = 0xffc0cb;
	colors["plum"]                   = 0xdda0dd;
	colors["powderblue"]             = 0xb0e0e6;
	colors["purple"]                 = 0x800080;
	colors["red"]                    = 0xff0000;
	colors["rosybrown"]              = 0xbc8f8f;
	colors["royalblue"]              = 0x4169e1;
	colors["saddlebrown"]            = 0x8b4513;
	colors["salmon"]                 = 0xfa8072;
	colors["sandybrown"]             = 0xf4a460;
	colors["seagreen"]               = 0x2e8b57;
	colors["seashell"]               = 0xfff5ee;
	colors["sienna"]                 = 0xa0522d;
	colors["silver"]                 = 0xc0c0c0;
	colors["skyblue"]                = 0x87ceeb;
	colors["slateblue"]              = 0x6a5acd;
	colors["slategray"]              = 0x708090;
	colors["slategrey"]              = 0x708090;
	colors["snow"]                   = 0xfffafa;
	colors["springgreen"]            = 0x00ff7f;
	colors["steelblue"]              = 0x4682b4;
	colors["tan"]                    = 0xd2b48c;
	colors["teal"]                   = 0x008080;
	colors["thistle"]                = 0xd8bfd8;
	colors["tomato"]                 = 0xff6347;
	colors["turquoise"]              = 0x40e0d0;
	colors["violet"]                 = 0xee82ee;
	colors["wheat"]                  = 0xf5deb3;
	colors["white"]                  = 0xffffff;
	colors["whitesmoke"]             = 0xf5f5f5;
	colors["yellow"]                 = 0xffff00;
	colors["yellowgreen"]            = 0x9acd32;

}

static const ColorContainer named_colors;

static bool parseNamedColorString(const std::string &value, video::SColor &color)
{
	std::string color_name;
	std::string alpha_string;

	/* If the string has a # in it, assume this is the start of a specified
	 * alpha value (if it isn't the string is invalid and the error will be
	 * caught later on, either because the color name won't be found or the
	 * alpha value will fail conversion)
	 */
	size_t alpha_pos = value.find('#');
	if (alpha_pos != std::string::npos) {
		color_name = value.substr(0, alpha_pos);
		alpha_string = value.substr(alpha_pos + 1);
	} else {
		color_name = value;
	}

	color_name = lowercase(value);

	std::map<const std::string, unsigned>::const_iterator it;
	it = named_colors.colors.find(color_name);
	if (it == named_colors.colors.end())
		return false;

	u32 color_temp = it->second;

	/* An empty string for alpha is ok (none of the color table entries
	 * have an alpha value either). Color strings without an alpha specified
	 * are interpreted as fully opaque
	 *
	 * For named colors the supplied alpha string (representing a hex value)
	 * must be exactly two digits. For example:  colorname#08
	 */
	if (!alpha_string.empty()) {
		if (alpha_string.length() != 2)
			return false;

		unsigned char d1, d2;
		if (!hex_digit_decode(alpha_string.at(0), d1)
				|| !hex_digit_decode(alpha_string.at(1), d2))
			return false;
		color_temp |= ((d1 & 0xf) << 4 | (d2 & 0xf)) << 24;
	} else {
		color_temp |= 0xff << 24;  // Fully opaque
	}

	color = video::SColor(color_temp);

	return true;
}

void str_replace(std::string &str, char from, char to)
{
	std::replace(str.begin(), str.end(), from, to);
}

/* Translated strings have the following format:
 * \x1bT marks the beginning of a translated string
 * \x1bE marks its end
 *
 * \x1bF marks the beginning of an argument, and \x1bE its end.
 *
 * Arguments are *not* translated, as they may contain escape codes.
 * Thus, if you want a translated argument, it should be inside \x1bT/\x1bE tags as well.
 *
 * This representation is chosen so that clients ignoring escape codes will
 * see untranslated strings.
 *
 * For instance, suppose we have a string such as "@1 Wool" with the argument "White"
 * The string will be sent as "\x1bT\x1bF\x1bTWhite\x1bE\x1bE Wool\x1bE"
 * To translate this string, we extract what is inside \x1bT/\x1bE tags.
 * When we notice the \x1bF tag, we recursively extract what is there up to the \x1bE end tag,
 * translating it as well.
 * We get the argument "White", translated, and create a template string with "@1" instead of it.
 * We finally get the template "@1 Wool" that was used in the beginning, which we translate
 * before filling it again.
 */

void translate_all(const std::wstring &s, size_t &i, std::wstring &res);

void translate_string(const std::wstring &s, const std::wstring &textdomain,
		size_t &i, std::wstring &res) {
	std::wostringstream output;
	std::vector<std::wstring> args;
	int arg_number = 1;
	while (i < s.length()) {
		// Not an escape sequence: just add the character.
		if (s[i] != '\x1b') {
			output.put(s[i]);
			// The character is a literal '@'; add it twice
			// so that it is not mistaken for an argument.
			if (s[i] == L'@')
				output.put(L'@');
			++i;
			continue;
		}

		// We have an escape sequence: locate it and its data
		// It is either a single character, or it begins with '('
		// and extends up to the following ')', with '\' as an escape character.
		++i;
		size_t start_index = i;
		size_t length;
		if (i == s.length()) {
			length = 0;
		} else if (s[i] == L'(') {
			++i;
			++start_index;
			while (i < s.length() && s[i] != L')') {
				if (s[i] == L'\\')
					++i;
				++i;
			}
			length = i - start_index;
			++i;
			if (i > s.length())
				i = s.length();
		} else {
			++i;
			length = 1;
		}
		std::wstring escape_sequence(s, start_index, length);

		// The escape sequence is now reconstructed.
		std::vector<std::wstring> parts = split(escape_sequence, L'@');
		if (parts[0] == L"E") {
			// "End of translation" escape sequence. We are done locating the string to translate.
			break;
		} else if (parts[0] == L"F") {
			// "Start of argument" escape sequence.
			// Recursively translate the argument, and add it to the argument list.
			// Add an "@n" instead of the argument to the template to translate.
			if (arg_number >= 10) {
				errorstream << "Ignoring too many arguments to translation" << std::endl;
				std::wstring arg;
				translate_all(s, i, arg);
				args.push_back(arg);
				continue;
			}
			output.put(L'@');
			output << arg_number;
			++arg_number;
			std::wstring arg;
			translate_all(s, i, arg);
			args.push_back(arg);
		} else {
			// This is an escape sequence *inside* the template string to translate itself.
			// This should not happen, show an error message.
			errorstream << "Ignoring escape sequence '" << wide_to_narrow(escape_sequence) << "' in translation" << std::endl;
		}
	}

	// Translate the template.
	std::wstring toutput = g_translations->getTranslation(textdomain, output.str());

	// Put back the arguments in the translated template.
	std::wostringstream result;
	size_t j = 0;
	while (j < toutput.length()) {
		// Normal character, add it to output and continue.
		if (toutput[j] != L'@' || j == toutput.length() - 1) {
			result.put(toutput[j]);
			++j;
			continue;
		}

		++j;
		// Literal escape for '@'.
		if (toutput[j] == L'@') {
			result.put(L'@');
			++j;
			continue;
		}

		// Here we have an argument; get its index and add the translated argument to the output.
		int arg_index = toutput[j] - L'1';
		++j;
		if (0 <= arg_index && (size_t)arg_index < args.size()) {
			result << args[arg_index];
		} else {
			// This is not allowed: show an error message
			errorstream << "Ignoring out-of-bounds argument escape sequence in translation" << std::endl;
		}
	}
	res = result.str();
}

void translate_all(const std::wstring &s, size_t &i, std::wstring &res) {
	std::wostringstream output;
	while (i < s.length()) {
		// Not an escape sequence: just add the character.
		if (s[i] != '\x1b') {
			output.put(s[i]);
			++i;
			continue;
		}

		// We have an escape sequence: locate it and its data
		// It is either a single character, or it begins with '('
		// and extends up to the following ')', with '\' as an escape character.
		size_t escape_start = i;
		++i;
		size_t start_index = i;
		size_t length;
		if (i == s.length()) {
			length = 0;
		} else if (s[i] == L'(') {
			++i;
			++start_index;
			while (i < s.length() && s[i] != L')') {
				if (s[i] == L'\\') {
					++i;
				}
				++i;
			}
			length = i - start_index;
			++i;
			if (i > s.length())
				i = s.length();
		} else {
			++i;
			length = 1;
		}
		std::wstring escape_sequence(s, start_index, length);

		// The escape sequence is now reconstructed.
		std::vector<std::wstring> parts = split(escape_sequence, L'@');
		if (parts[0] == L"E") {
			// "End of argument" escape sequence. Exit.
			break;
		} else if (parts[0] == L"T") {
			// Beginning of translated string.
			std::wstring textdomain;
			if (parts.size() > 1)
				textdomain = parts[1];
			std::wstring translated;
			translate_string(s, textdomain, i, translated);
			output << translated;
		} else {
			// Another escape sequence, such as colors. Preserve it.
			output << std::wstring(s, escape_start, i - escape_start);
		}
	}

	res = output.str();
}

std::wstring translate_string(const std::wstring &s) {
	size_t i = 0;
	std::wstring res;
	translate_all(s, i, res);
	return res;
}