forked from amule-project/amule
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathWebServer.cpp
More file actions
2166 lines (1918 loc) · 58.5 KB
/
Copy pathWebServer.cpp
File metadata and controls
2166 lines (1918 loc) · 58.5 KB
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
//
// This file is part of the aMule Project.
//
// Copyright (c) 2003-2011 Angel Vidal ( [email protected] )
// Copyright (c) 2003-2026 aMule Team ( https://amule-org.github.io )
// Copyright (c) 2002-2011 Merkur ( [email protected] / http://www.emule-project.net )
//
// Any parts of this program derived from the xMule, lMule or eMule project,
// or contributed by third-party developers are copyrighted by their
// respective authors.
//
// 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
//
#include <cctype> // Needed for std::toupper()
#include <wx/math.h> // Needed for cos, M_PI
#include <string> // Do_not_auto_remove (g++-4.0.1)
// CryptoPP::AutoSeededRandomPool, for the session-token CSPRNG. See
// CryptoPP_Inc.h for pragma rationale.
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-copy-with-user-provided-dtor"
#pragma clang diagnostic ignored "-Wdeprecated-copy-with-user-provided-copy"
#pragma clang diagnostic ignored "-Wdeprecated-dynamic-exception-spec"
#endif
#include <cryptopp/osrng.h>
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#include <wx/datetime.h>
//-------------------------------------------------------------------
#include <wx/tokenzr.h> // for wxTokenizer
#include <wx/wfstream.h>
#include <ec/cpp/ECFileConfig.h> // Needed for CECFileConfig
#include <ec/cpp/ECSpecialTags.h>
#include <common/MD5Sum.h>
#include <common/Format.h> // Needed for CFormat
#include <protocol/ed2k/Constants.h> // Needed for PARTSIZE
#include "Constants.h" // Needed for PR_*
//-------------------------------------------------------------------
#include "WebSocket.h" // Needed for StopSockets()
#include <amuleIPV4Address.h>
#include "php_core_lib.h"
//-------------------------------------------------------------------
typedef uint32_t COLORTYPE;
#ifdef RGB
#undef RGB
#endif
inline unsigned long RGB(int r, int g, int b)
{
return ((b & 0xff) << 16) | ((g & 0xff) << 8) | (r & 0xff);
}
inline void set_rgb_color_val(unsigned char *start, uint32 val, unsigned char mod)
{
unsigned char r = val, g = val >> 8, b = val >> 16;
start[0] = (r > mod) ? (r - mod) : 1;
start[1] = (g > mod) ? (g - mod) : 1;
start[2] = (b > mod) ? (b - mod) : 1;
}
wxString _SpecialChars(wxString str)
{
str.Replace("&", "&");
str.Replace("<", "<");
str.Replace(">", ">");
str.Replace("\"", """);
return str;
}
static uint8 GetHigherPrio(uint32 prio, bool auto_priority)
{
if (auto_priority) {
return PR_LOW;
} else {
switch (prio) {
case PR_LOW:
return PR_NORMAL;
case PR_NORMAL:
return PR_HIGH;
case PR_HIGH:
return PR_AUTO;
case PR_AUTO:
return PR_LOW;
default:
return PR_AUTO;
}
}
}
static uint8 GetHigherPrioShared(uint32 prio, bool auto_priority)
{
// The arrows walk the manual scale only; they never set or pass
// through Auto (that mode can only be chosen from the selector).
// Raising while in Auto leaves it for the manual scale at High.
if (auto_priority) {
return PR_HIGH;
} else {
switch (prio) {
case PR_VERY_LOW:
return PR_LOW;
case PR_LOW:
return PR_NORMAL;
case PR_NORMAL:
return PR_HIGH;
case PR_HIGH:
return PR_VERYHIGH;
case PR_VERYHIGH:
return PR_POWERSHARE;
case PR_POWERSHARE:
return PR_POWERSHARE;
default:
return PR_NORMAL;
}
}
}
static uint8 GetLowerPrio(uint32 prio, bool auto_priority)
{
if (auto_priority) {
return PR_HIGH;
} else {
switch (prio) {
case PR_LOW:
return PR_AUTO;
case PR_NORMAL:
return PR_LOW;
case PR_HIGH:
return PR_NORMAL;
case PR_AUTO:
return PR_HIGH;
default:
return PR_AUTO;
}
}
}
static uint8 GetLowerPrioShared(uint32 prio, bool auto_priority)
{
// The arrows walk the manual scale only; they never set or pass
// through Auto (that mode can only be chosen from the selector).
// Lowering while in Auto leaves it for the manual scale at Low.
if (auto_priority) {
return PR_LOW;
} else {
switch (prio) {
case PR_POWERSHARE:
return PR_VERYHIGH;
case PR_VERYHIGH:
return PR_HIGH;
case PR_HIGH:
return PR_NORMAL;
case PR_NORMAL:
return PR_LOW;
case PR_LOW:
return PR_VERY_LOW;
case PR_VERY_LOW:
return PR_VERY_LOW;
default:
return PR_NORMAL;
}
}
}
/*
* Url string decoder
*/
wxString CURLDecoder::Decode(const wxString &url)
{
size_t n = url.length();
std::vector<char> buffer(n + 1);
size_t i, j;
for (i = 0, j = 0; i < n; i++, j++) {
if (url[i] == '+') {
buffer[j] = ' ';
} else if (url[i] == '%' && i < n - 2) {
char ch1 = std::toupper(url[i + 1]);
char ch2 = std::toupper(url[i + 2]);
if (((ch1 >= '0' && ch1 <= '9') || (ch1 >= 'A' && ch1 <= 'F')) &&
((ch2 >= '0' && ch2 <= '9') || (ch2 >= 'A' && ch2 <= 'F'))) {
i += 2;
buffer[j] = ((ch1 > '9' ? ch1 - 'A' + 10 : ch1 - '0') << 4) |
(ch2 > '9' ? ch2 - 'A' + 10 : ch2 - '0');
} else {
// Invalid %-escape sequence
buffer[j] = url[i];
}
} else {
buffer[j] = url[i];
}
}
buffer[j] = '\0';
return UTF82unicode(&buffer[0]);
}
CParsedUrl::CParsedUrl(const wxString &url)
{
if (url.Find('/') != -1) {
m_path = url.BeforeFirst('/');
m_file = url.AfterFirst('/');
}
if (url.Find('?') != -1) {
m_file.Truncate(m_file.Find('?'));
wxString params = url.AfterFirst('?');
wxStringTokenizer tkz(params, "&");
while (tkz.HasMoreTokens()) {
wxString param_val = tkz.GetNextToken();
wxString key = param_val.BeforeFirst('=');
wxString val = param_val.AfterFirst('=');
val = CURLDecoder::Decode(val);
if (m_params.count(key)) {
m_params[key] = m_params[key] + "|" + val;
} else {
m_params[key] = val;
}
}
}
}
void CParsedUrl::ConvertParams(std::map<std::string, std::string> &dst)
{
for (std::map<wxString, wxString>::iterator i = m_params.begin(); i != m_params.end(); ++i) {
std::string key(unicode2char(i->first)), value(unicode2char(i->second));
dst[key] = value;
}
}
CWebServerBase::CWebServerBase(CamulewebApp *webApp, const wxString &templateDir)
: m_ServersInfo(webApp)
, m_SharedFileInfo(webApp)
, m_DownloadFileInfo(webApp, &m_ImageLib)
, m_UploadsInfo(webApp)
, m_SearchInfo(webApp)
, m_Stats(500, webApp)
, m_ImageLib(templateDir)
{
webInterface = webApp;
//
// Init stat graphs
#ifdef WITH_LIBPNG
m_ImageLib.AddImage(
new CDynStatisticImage(200, true, m_Stats.DownloadSpeed()), "/amule_stats_download.png");
m_ImageLib.AddImage(
new CDynStatisticImage(200, true, m_Stats.UploadSpeed()), "/amule_stats_upload.png");
m_ImageLib.AddImage(
new CDynStatisticImage(200, false, m_Stats.ConnCount()), "/amule_stats_conncount.png");
m_ImageLib.AddImage(new CDynStatisticImage(200, false, m_Stats.KadCount()), "/amule_stats_kad.png");
#endif
m_upnpEnabled = webInterface->m_UPnPWebServerEnabled;
m_upnpTCPPort = webInterface->m_UPnPTCPPort;
m_AsioService = new CAsioService;
}
// Probably always terminated by Ctrl-C or kill, but make a clean shutdown of the service anyway
CWebServerBase::~CWebServerBase()
{
m_AsioService->Stop();
delete m_AsioService;
}
// sends output to web interface
void CWebServerBase::Print(const wxString &s)
{
webInterface->Show(s);
}
void CWebServerBase::StartServer()
{
#ifdef ENABLE_UPNP
if (m_upnpEnabled) {
m_upnpMappings.resize(1);
m_upnpMappings[0] = CUPnPPortMapping(
webInterface->m_WebserverPort, "TCP", true, "aMule TCP Webserver Socket");
m_upnp = new CUPnPControlPoint(m_upnpTCPPort);
m_upnp->AddPortMappings(m_upnpMappings);
}
#endif
amuleIPV4Address addr;
addr.AnyAddress();
addr.Service(webInterface->m_WebserverPort);
m_webserver_socket = new CWebLibSocketServer(addr, MULE_SOCKET_REUSEADDR, this);
m_webserver_socket->Notify(true);
if (!m_webserver_socket->IsOk()) {
delete m_webserver_socket;
m_webserver_socket = 0;
}
}
void CWebServerBase::StopServer()
{
if (m_webserver_socket) {
delete m_webserver_socket;
}
#ifdef ENABLE_UPNP
if (m_upnpEnabled) {
m_upnp->DeletePortMappings(m_upnpMappings);
delete m_upnp;
}
#endif
}
CWebLibSocketServer::CWebLibSocketServer(
const class amuleIPV4Address &adr, int flags, CWebServerBase *webServerBase)
: CLibSocketServer(adr, flags)
, m_webServerBase(webServerBase)
{
}
void CWebLibSocketServer::OnAccept()
{
CWebSocket *client = new CWebSocket(m_webServerBase);
if (AcceptWith(*client, false)) {
m_webServerBase->webInterface->Show(_("web client connection accepted\n"));
} else {
delete client;
m_webServerBase->webInterface->Show(_("ERROR: cannot accept web client connection\n"));
}
}
void CScriptWebServer::ProcessImgFileReq(ThreadData Data)
{
webInterface->DebugShow("**** imgrequest: " + Data.sURL + "\n");
const CSession *session = CheckLoggedin(Data);
// To prevent access to non-template images, we disallow use of paths in filenames.
wxString imgName = "/" + wxFileName(Data.parsedURL.File()).GetFullName();
CAnyImage *img = m_ImageLib.GetImage(imgName);
// Only static images are available to visitors, in order to prevent
// information leakage, but still allowing images on the login page.
if (img && (session->m_logged_in || dynamic_cast<CFileImage *>(img))) {
int img_size = 0;
unsigned char *img_data = img->RequestData(img_size);
// This unicode2char is ok.
Data.pSocket->SendContent(unicode2char(img->GetHTTP()), img_data, img_size);
} else if (!session->m_logged_in) {
webInterface->DebugShow("**** imgrequest: failed, not logged in\n");
ProcessURL(Data);
} else {
webInterface->DebugShow("**** imgrequest: failed\n");
}
}
// send EC request and discard output
void CWebServerBase::Send_Discard_V2_Request(CECPacket *request)
{
const CECPacket *reply = webInterface->SendRecvMsg_v2(request);
const CECTag *tag = NULL;
if (reply) {
if (reply->GetOpCode() == EC_OP_STRINGS) {
for (CECPacket::const_iterator it = reply->begin(); it != reply->end(); ++it) {
tag = &*it;
if (tag->GetTagName() == EC_TAG_STRING) {
webInterface->Show(tag->GetStringData());
}
}
} else if (reply->GetOpCode() == EC_OP_FAILED) {
tag = reply->GetFirstTagSafe();
if (tag->IsString()) {
webInterface->Show(
CFormat(_("Request failed with the following error: %s.")) %
wxString(wxGetTranslation(tag->GetStringData())));
} else {
webInterface->Show(_("Request failed with an unknown error."));
}
}
delete reply;
}
}
//
// Command interface
//
void CWebServerBase::Send_SharedFile_Cmd(wxString file_hash, wxString cmd, uint32 opt_arg)
{
CECPacket *ec_cmd = 0;
CMD4Hash fileHash;
wxCHECK2(fileHash.Decode(file_hash), /* Do nothing. */);
CECTag hashtag(EC_TAG_KNOWNFILE, fileHash);
if (cmd == "prio") {
ec_cmd = new CECPacket(EC_OP_SHARED_SET_PRIO);
hashtag.AddTag(CECTag(EC_TAG_PARTFILE_PRIO, (uint8)opt_arg));
} else if (cmd == "prioup") {
SharedFile *file = m_SharedFileInfo.GetByHash(fileHash);
if (file) {
ec_cmd = new CECPacket(EC_OP_SHARED_SET_PRIO);
hashtag.AddTag(CECTag(EC_TAG_PARTFILE_PRIO,
GetHigherPrioShared(file->nFilePriority, file->bFileAutoPriority)));
}
} else if (cmd == "priodown") {
SharedFile *file = m_SharedFileInfo.GetByHash(fileHash);
if (file) {
ec_cmd = new CECPacket(EC_OP_SHARED_SET_PRIO);
hashtag.AddTag(CECTag(EC_TAG_PARTFILE_PRIO,
GetLowerPrioShared(file->nFilePriority, file->bFileAutoPriority)));
}
}
if (ec_cmd) {
ec_cmd->AddTag(hashtag);
Send_Discard_V2_Request(ec_cmd);
delete ec_cmd;
}
}
void CWebServerBase::Send_ReloadSharedFile_Cmd()
{
CECPacket ec_cmd(EC_OP_SHAREDFILES_RELOAD);
Send_Discard_V2_Request(&ec_cmd);
}
void CWebServerBase::Send_DownloadFile_Cmd(wxString file_hash, wxString cmd, uint32 opt_arg)
{
CECPacket *ec_cmd = 0;
CMD4Hash fileHash;
wxCHECK2(fileHash.Decode(file_hash), /* Do nothing. */);
CECTag hashtag(EC_TAG_PARTFILE, fileHash);
if (cmd == "pause") {
ec_cmd = new CECPacket(EC_OP_PARTFILE_PAUSE);
} else if (cmd == "resume") {
ec_cmd = new CECPacket(EC_OP_PARTFILE_RESUME);
} else if (cmd == "cancel") {
ec_cmd = new CECPacket(EC_OP_PARTFILE_DELETE);
} else if (cmd == "prio") {
ec_cmd = new CECPacket(EC_OP_PARTFILE_PRIO_SET);
hashtag.AddTag(CECTag(EC_TAG_PARTFILE_PRIO, (uint8)opt_arg));
} else if (cmd == "prioup") {
DownloadFile *file = m_DownloadFileInfo.GetByHash(fileHash);
if (file) {
ec_cmd = new CECPacket(EC_OP_PARTFILE_PRIO_SET);
hashtag.AddTag(CECTag(EC_TAG_PARTFILE_PRIO,
GetHigherPrio(file->lFilePrio, file->bFileAutoPriority)));
}
} else if (cmd == "priodown") {
DownloadFile *file = m_DownloadFileInfo.GetByHash(fileHash);
if (file) {
ec_cmd = new CECPacket(EC_OP_PARTFILE_PRIO_SET);
hashtag.AddTag(CECTag(EC_TAG_PARTFILE_PRIO,
GetLowerPrio(file->lFilePrio, file->bFileAutoPriority)));
}
}
if (ec_cmd) {
ec_cmd->AddTag(hashtag);
Send_Discard_V2_Request(ec_cmd);
delete ec_cmd;
}
}
void CWebServerBase::Send_DownloadSearchFile_Cmd(wxString file_hash, uint8 cat)
{
CMD4Hash fileHash;
wxCHECK2(fileHash.Decode(file_hash), /* Do nothing. */);
CECPacket ec_cmd(EC_OP_DOWNLOAD_SEARCH_RESULT);
CECTag link_tag(EC_TAG_KNOWNFILE, fileHash);
link_tag.AddTag(CECTag(EC_TAG_PARTFILE_CAT, cat));
ec_cmd.AddTag(link_tag);
Send_Discard_V2_Request(&ec_cmd);
}
void CWebServerBase::Send_AddServer_Cmd(wxString addr, wxString port, wxString name)
{
CECPacket ec_cmd(EC_OP_SERVER_ADD);
ec_cmd.AddTag(CECTag(EC_TAG_SERVER_ADDRESS, addr.Trim() + ":" + port.Trim()));
ec_cmd.AddTag(CECTag(EC_TAG_SERVER_NAME, name));
Send_Discard_V2_Request(&ec_cmd);
}
void CWebServerBase::Send_Server_Cmd(uint32 ip, uint16 port, wxString cmd)
{
if (!ip) {
return;
}
CECPacket *ec_cmd = 0;
if (cmd == "connect") {
ec_cmd = new CECPacket(EC_OP_SERVER_CONNECT);
} else if (cmd == "remove") {
ec_cmd = new CECPacket(EC_OP_SERVER_REMOVE);
} else if (cmd == "disconnect") {
ec_cmd = new CECPacket(EC_OP_SERVER_DISCONNECT);
}
if (ec_cmd) {
ec_cmd->AddTag(CECTag(EC_TAG_SERVER, EC_IPv4_t(ip, port)));
Send_Discard_V2_Request(ec_cmd);
delete ec_cmd;
}
}
void CWebServerBase::Send_Search_Cmd(wxString search,
wxString extention,
wxString type,
EC_SEARCH_TYPE search_type,
uint32 avail,
uint32 min_size,
uint32 max_size)
{
CECPacket search_req(EC_OP_SEARCH_START);
search_req.AddTag(CEC_Search_Tag(search, search_type, type, extention, avail, min_size, max_size));
Send_Discard_V2_Request(&search_req);
}
bool CWebServerBase::Send_DownloadEd2k_Cmd(wxString link, uint8 cat)
{
CECPacket req(EC_OP_ADD_LINK);
CECTag link_tag(EC_TAG_STRING, link);
link_tag.AddTag(CECTag(EC_TAG_PARTFILE_CAT, cat));
req.AddTag(link_tag);
const CECPacket *response = webInterface->SendRecvMsg_v2(&req);
// SendRecvMsg_v2 returns null on EC connection failure.
// Treat a missing response as a failed command (same as EC_OP_FAILED)
// so the PHP caller gets a defined bool rather than a crash.
if (!response) {
return true;
}
bool result = (response->GetOpCode() == EC_OP_FAILED);
delete response;
return result;
}
// We have to add gz-header and some other stuff
// to standard zlib functions in order to use gzip in web pages
int CWebServerBase::GzipCompress(
Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen, int level)
{
static const int gz_magic[2] = { 0x1f, 0x8b }; // gzip magic header
z_stream stream = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
stream.zalloc = (alloc_func)0;
stream.zfree = (free_func)0;
stream.opaque = (voidpf)0;
uLong crc = crc32(0L, Z_NULL, 0);
// init Zlib stream
// NOTE windowBits is passed < 0 to suppress zlib header
int err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);
if (err != Z_OK) {
return err;
}
snprintf((char *)dest,
*destLen,
"%c%c%c%c%c%c%c%c%c%c",
gz_magic[0],
gz_magic[1],
Z_DEFLATED,
0 /*flags*/,
0,
0,
0,
0 /*time*/,
0 /*xflags*/,
255);
// wire buffers
stream.next_in = const_cast<Bytef *>(source);
stream.avail_in = (uInt)sourceLen;
stream.next_out = ((Bytef *)dest) + 10;
stream.avail_out = *destLen - 18;
// doit
err = deflate(&stream, Z_FINISH);
if (err != Z_STREAM_END) {
deflateEnd(&stream);
return err;
}
err = deflateEnd(&stream);
crc = crc32(crc, (const Bytef *)source, sourceLen);
// CRC
*(((Bytef *)dest) + 10 + stream.total_out) = (Bytef)(crc & 0xFF);
*(((Bytef *)dest) + 10 + stream.total_out + 1) = (Bytef)((crc >> 8) & 0xFF);
*(((Bytef *)dest) + 10 + stream.total_out + 2) = (Bytef)((crc >> 16) & 0xFF);
*(((Bytef *)dest) + 10 + stream.total_out + 3) = (Bytef)((crc >> 24) & 0xFF);
// Length
*(((Bytef *)dest) + 10 + stream.total_out + 4) = (Bytef)(sourceLen & 0xFF);
*(((Bytef *)dest) + 10 + stream.total_out + 5) = (Bytef)((sourceLen >> 8) & 0xFF);
*(((Bytef *)dest) + 10 + stream.total_out + 6) = (Bytef)((sourceLen >> 16) & 0xFF);
*(((Bytef *)dest) + 10 + stream.total_out + 7) = (Bytef)((sourceLen >> 24) & 0xFF);
// return destLength
*destLen = 10 + stream.total_out + 8;
return err;
}
/*
* Item container implementation
*/
ServersInfo *ServerEntry::GetContainerInstance()
{
return ServersInfo::m_This;
}
ServersInfo *ServersInfo::m_This = 0;
ServersInfo::ServersInfo(CamulewebApp *webApp)
: ItemsContainer<ServerEntry>(webApp)
{
m_This = this;
}
bool ServersInfo::ReQuery()
{
CECPacket srv_req(EC_OP_GET_SERVER_LIST);
const CECPacket *srv_reply = m_webApp->SendRecvMsg_v2(&srv_req);
if (!srv_reply) {
return false;
}
//
// query succeeded - flush existing values and refill
EraseAll();
for (CECPacket::const_iterator it = srv_reply->begin(); it != srv_reply->end(); ++it) {
const CECTag *tag = &*it;
ServerEntry Entry;
Entry.sServerName = _SpecialChars(tag->GetTagByNameSafe(EC_TAG_SERVER_NAME)->GetStringData());
Entry.sServerDescription =
_SpecialChars(tag->GetTagByNameSafe(EC_TAG_SERVER_DESC)->GetStringData());
Entry.sServerIP = tag->GetIPv4Data().StringIP(false);
Entry.nServerIP = tag->GetIPv4Data().IP();
Entry.nServerPort = tag->GetIPv4Data().m_port;
Entry.nServerUsers = tag->GetTagByNameSafe(EC_TAG_SERVER_USERS)->GetInt();
Entry.nServerMaxUsers = tag->GetTagByNameSafe(EC_TAG_SERVER_USERS_MAX)->GetInt();
Entry.nServerFiles = tag->GetTagByNameSafe(EC_TAG_SERVER_FILES)->GetInt();
AddItem(Entry);
}
delete srv_reply;
return true;
}
SharedFile::SharedFile(CEC_SharedFile_Tag *tag)
: CECID(tag->ID())
{
sFileName = _SpecialChars(tag->FileName());
lFileSize = tag->SizeFull();
sED2kLink = _SpecialChars(tag->FileEd2kLink());
nHash = tag->FileHash();
ProcessUpdate(tag);
}
void SharedFile::ProcessUpdate(CEC_SharedFile_Tag *tag)
{
nFileTransferred = tag->GetXferred();
nFileAllTimeTransferred = tag->GetAllXferred();
nFileRequests = tag->GetRequests();
nFileAllTimeRequests = tag->GetAllRequests();
nFileAccepts = tag->GetAccepts();
nFileAllTimeAccepts = tag->GetAllAccepts();
sFileHash = nHash.Encode();
nFilePriority = tag->UpPrio();
if (nFilePriority >= 10) {
bFileAutoPriority = true;
nFilePriority -= 10;
} else {
bFileAutoPriority = false;
}
}
SharedFileInfo *SharedFile::GetContainerInstance()
{
return SharedFileInfo::m_This;
}
SharedFileInfo *SharedFileInfo::m_This = 0;
SharedFileInfo::SharedFileInfo(CamulewebApp *webApp)
: UpdatableItemsContainer<SharedFile, CEC_SharedFile_Tag, uint32>(webApp)
{
m_This = this;
}
bool SharedFileInfo::ReQuery()
{
DoRequery(EC_OP_GET_SHARED_FILES, EC_TAG_KNOWNFILE);
return true;
}
DownloadFile::DownloadFile(CEC_PartFile_Tag *tag)
: CECID(tag->ID())
{
nHash = tag->FileHash();
sFileName = _SpecialChars(tag->FileName());
lFileSize = tag->SizeFull();
sFileHash = nHash.Encode();
sED2kLink = _SpecialChars(tag->FileEd2kLink());
lFileCompleted = tag->SizeDone();
lFileTransferred = tag->SizeXfer();
lFileSpeed = tag->Speed();
fCompleted = (100.0 * lFileCompleted) / lFileSize;
wxtLastSeenComplete = wxDateTime(tag->LastSeenComplete());
ProcessUpdate(tag);
}
void DownloadFile::ProcessUpdate(CEC_PartFile_Tag *tag)
{
if (!tag) {
return;
}
lFilePrio = tag->DownPrio();
if (lFilePrio >= 10) {
lFilePrio -= 10;
bFileAutoPriority = true;
} else {
bFileAutoPriority = false;
}
nCat = tag->FileCat();
nFileStatus = tag->FileStatus();
lSourceCount = tag->SourceCount();
lNotCurrentSourceCount = tag->SourceNotCurrCount();
lTransferringSourceCount = tag->SourceXferCount();
lSourceCountA4AF = tag->SourceCountA4AF();
if (lTransferringSourceCount > 0) {
lFileCompleted = tag->SizeDone();
lFileTransferred = tag->SizeXfer();
lFileSpeed = tag->Speed();
fCompleted = (100.0 * lFileCompleted) / lFileSize;
} else {
lFileSpeed = 0;
}
CECTag *gap_tag = tag->GetTagByName(EC_TAG_PARTFILE_GAP_STATUS);
CECTag *part_tag = tag->GetTagByName(EC_TAG_PARTFILE_PART_STATUS);
CECTag *req_tag = tag->GetTagByName(EC_TAG_PARTFILE_REQ_STATUS);
if (gap_tag) {
m_Encoder.DecodeGaps(gap_tag, m_Gaps);
}
if (part_tag) {
m_Encoder.DecodeParts(part_tag, m_PartInfo);
}
if (req_tag) {
ArrayOfUInts64 reqs;
m_Encoder.DecodeReqs(req_tag, reqs);
int reqcount = reqs.size() / 2;
m_ReqParts.resize(reqcount);
for (int i = 0; i < reqcount; i++) {
m_ReqParts[i].start = reqs[2 * i];
m_ReqParts[i].end = reqs[2 * i + 1];
}
}
}
DownloadFileInfo *DownloadFile::GetContainerInstance()
{
return DownloadFileInfo::m_This;
}
DownloadFileInfo *DownloadFileInfo::m_This = 0;
DownloadFileInfo::DownloadFileInfo(CamulewebApp *webApp, CImageLib *imlib)
: UpdatableItemsContainer<DownloadFile, CEC_PartFile_Tag, uint32>(webApp)
{
m_This = this;
m_ImageLib = imlib;
}
void DownloadFileInfo::LoadImageParams(wxString &tpl, int width, int height)
{
m_Template = tpl;
m_width = width;
m_height = height;
}
void DownloadFileInfo::ItemInserted(DownloadFile *item)
{
item->m_Image = new CDynProgressImage(m_width, m_height, m_Template, item);
#ifdef WITH_LIBPNG
m_ImageLib->AddImage(item->m_Image, "/" + item->m_Image->Name());
#endif
}
void DownloadFileInfo::ItemDeleted(DownloadFile *item)
{
#ifdef WITH_LIBPNG
m_ImageLib->RemoveImage("/" + item->m_Image->Name());
#else
delete item->m_Image;
#endif
}
bool DownloadFileInfo::ReQuery()
{
DoRequery(EC_OP_GET_DLOAD_QUEUE, EC_TAG_PARTFILE);
return true;
}
UploadFile::UploadFile(CEC_UpDownClient_Tag *tag)
: CECID(tag->ID())
{
sUserName = _SpecialChars(tag->ClientName());
nSpeed = tag->SpeedUp();
nTransferredUp = tag->XferUp();
nTransferredDown = tag->XferDown();
nUploadFile = 0;
tag->UploadFile(nUploadFile);
}
UploadsInfo *UploadFile::GetContainerInstance()
{
return UploadsInfo::m_This;
}
UploadsInfo *UploadsInfo::m_This = 0;
UploadsInfo::UploadsInfo(CamulewebApp *webApp)
: ItemsContainer<UploadFile>(webApp)
{
m_This = this;
}
bool UploadsInfo::ReQuery()
{
CECPacket up_req(EC_OP_GET_ULOAD_QUEUE);
const CECPacket *up_reply = m_webApp->SendRecvMsg_v2(&up_req);
if (!up_reply) {
return false;
}
//
// query succeeded - flush existing values and refill
EraseAll();
for (CECPacket::const_iterator it = up_reply->begin(); it != up_reply->end(); ++it) {
UploadFile curr((CEC_UpDownClient_Tag *)&*it);
AddItem(curr);
}
delete up_reply;
return true;
}
SearchFile::SearchFile(CEC_SearchFile_Tag *tag)
: CECID(tag->ID())
{
nHash = tag->FileHash();
sHash = nHash.Encode();
sFileName = _SpecialChars(tag->FileName());
lFileSize = tag->SizeFull();
lSourceCount = tag->SourceCount();
bPresent = tag->AlreadyHave();
}
void SearchFile::ProcessUpdate(CEC_SearchFile_Tag *tag)
{
lSourceCount = tag->SourceCount();
}
SearchInfo *SearchFile::GetContainerInstance()
{
return SearchInfo::m_This;
}
SearchInfo *SearchInfo::m_This = 0;
SearchInfo::SearchInfo(CamulewebApp *webApp)
: UpdatableItemsContainer<SearchFile, CEC_SearchFile_Tag, uint32>(webApp)
{
m_This = this;
}
bool SearchInfo::ReQuery()
{
DoRequery(EC_OP_SEARCH_RESULTS, EC_TAG_SEARCHFILE);
return true;
}
/*!
* Image classes:
*
* CFileImage: simply represent local file
* CDynProgressImage: dynamically generated from gap info
*/
CAnyImage::CAnyImage(int size)
{
m_size = 0;
m_alloc_size = size;
if (m_alloc_size) {
m_data = new unsigned char[m_alloc_size];
} else {
m_data = 0;
}
}
CAnyImage::CAnyImage(int width, int height)
: m_width(width)
, m_height(height)
{
m_size = 0;
// allocate considering image header
m_alloc_size =
static_cast<unsigned long>(width) * static_cast<unsigned long>(height) * sizeof(uint32) +
0x100;
if (m_alloc_size) {
m_data = new unsigned char[m_alloc_size];
} else {
m_data = 0;
}
}
CAnyImage::~CAnyImage()
{
if (m_data) {
delete[] m_data;
}
}
void CAnyImage::Realloc(int size)
{
if (size == m_alloc_size) {
return;
}
// always grow, but shrink only x2
if ((size > m_alloc_size) || (size < (m_alloc_size / 2))) {
m_alloc_size = size;
if (m_data) {
delete[] m_data;
}
m_data = new unsigned char[m_alloc_size];
}
}
unsigned char *CAnyImage::RequestData(int &size)
{
size = m_size;
return m_data;
}
void CAnyImage::SetHttpType(wxString ext)
{
m_Http = "Content-Type: " + ext + "\r\n";
time_t t = time(NULL);
char tmp[255];
strftime(tmp, 255, "%a, %d %b %Y %H:%M:%S GMT", gmtime(&t));
m_Http += "Last-Modified: " + wxString(char2unicode(tmp)) + "\r\n";
m_Http += "ETag: " + MD5Sum(char2unicode(tmp)).GetHash() + "\r\n";
}
CFileImage::CFileImage(const wxString &name)
: CAnyImage(0)
{
m_size = 0;
m_name = name;
#ifdef __WINDOWS__
wxFFile fis(m_name, "rb");
#else
wxFFile fis(m_name);
#endif
// FIXME: proper logging is needed
if (fis.IsOpened()) {
size_t file_size = fis.Length();