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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
|
/**
* @file llcurl.cpp
* @author Zero / Donovan
* @date 2006-10-15
* @brief Implementation of wrapper around libcurl.
*
* $LicenseInfo:firstyear=2006&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library 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;
* version 2.1 of the License only.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#if LL_WINDOWS
#define SAFE_SSL 1
#elif LL_DARWIN
#define SAFE_SSL 1
#else
#define SAFE_SSL 1
#endif
#include "linden_common.h"
#include "llcurl.h"
#include <algorithm>
#include <iomanip>
#include <curl/curl.h>
#if SAFE_SSL
#include <openssl/crypto.h>
#endif
#include "llbufferstream.h"
#include "llproxy.h"
#include "llsdserialize.h"
#include "llstl.h"
#include "llthread.h"
#include "lltimer.h"
//////////////////////////////////////////////////////////////////////////////
/*
The trick to getting curl to do keep-alives is to reuse the
same easy handle for the requests. It appears that curl
keeps a pool of connections alive for each easy handle, but
doesn't share them between easy handles. Therefore it is
important to keep a pool of easy handles and reuse them,
rather than create and destroy them with each request. This
code does this.
Furthermore, it would behoove us to keep track of which
hosts an easy handle was used for and pick an easy handle
that matches the next request. This code does not current
do this.
*/
//////////////////////////////////////////////////////////////////////////////
static const U32 EASY_HANDLE_POOL_SIZE = 5;
static const S32 MULTI_PERFORM_CALL_REPEAT = 5;
static const S32 CURL_REQUEST_TIMEOUT = 30; // seconds
static const S32 MAX_ACTIVE_REQUEST_COUNT = 100;
static
// DEBUG //
S32 gCurlEasyCount = 0;
S32 gCurlMultiCount = 0;
//////////////////////////////////////////////////////////////////////////////
//static
std::vector<LLMutex*> LLCurl::sSSLMutex;
std::string LLCurl::sCAPath;
std::string LLCurl::sCAFile;
LLCurlThread* LLCurl::sCurlThread = NULL ;
void check_curl_code(CURLcode code)
{
if (code != CURLE_OK)
{
// linux appears to throw a curl error once per session for a bad initialization
// at a pretty random time (when enabling cookies).
llinfos << "curl error detected: " << curl_easy_strerror(code) << llendl;
}
}
void check_curl_multi_code(CURLMcode code)
{
if (code != CURLM_OK)
{
// linux appears to throw a curl error once per session for a bad initialization
// at a pretty random time (when enabling cookies).
llinfos << "curl multi error detected: " << curl_multi_strerror(code) << llendl;
}
}
//static
void LLCurl::setCAPath(const std::string& path)
{
sCAPath = path;
}
//static
void LLCurl::setCAFile(const std::string& file)
{
sCAFile = file;
}
//static
std::string LLCurl::getVersionString()
{
return std::string(curl_version());
}
//////////////////////////////////////////////////////////////////////////////
LLCurl::Responder::Responder()
: mReferenceCount(0)
{
}
LLCurl::Responder::~Responder()
{
}
// virtual
void LLCurl::Responder::errorWithContent(
U32 status,
const std::string& reason,
const LLSD&)
{
error(status, reason);
}
// virtual
void LLCurl::Responder::error(U32 status, const std::string& reason)
{
llinfos << mURL << " [" << status << "]: " << reason << llendl;
}
// virtual
void LLCurl::Responder::result(const LLSD& content)
{
}
void LLCurl::Responder::setURL(const std::string& url)
{
mURL = url;
}
// virtual
void LLCurl::Responder::completedRaw(
U32 status,
const std::string& reason,
const LLChannelDescriptors& channels,
const LLIOPipe::buffer_ptr_t& buffer)
{
LLSD content;
LLBufferStream istr(channels, buffer.get());
if (!LLSDSerialize::fromXML(content, istr))
{
llinfos << "Failed to deserialize LLSD. " << mURL << " [" << status << "]: " << reason << llendl;
}
completed(status, reason, content);
}
// virtual
void LLCurl::Responder::completed(U32 status, const std::string& reason, const LLSD& content)
{
if (isGoodStatus(status))
{
result(content);
}
else
{
errorWithContent(status, reason, content);
}
}
//virtual
void LLCurl::Responder::completedHeader(U32 status, const std::string& reason, const LLSD& content)
{
}
namespace boost
{
void intrusive_ptr_add_ref(LLCurl::Responder* p)
{
++p->mReferenceCount;
}
void intrusive_ptr_release(LLCurl::Responder* p)
{
if (p && 0 == --p->mReferenceCount)
{
delete p;
}
}
};
//////////////////////////////////////////////////////////////////////////////
std::set<CURL*> LLCurl::Easy::sFreeHandles;
std::set<CURL*> LLCurl::Easy::sActiveHandles;
//static
CURL* LLCurl::Easy::allocEasyHandle()
{
CURL* ret = NULL;
if (sFreeHandles.empty())
{
ret = curl_easy_init();
}
else
{
ret = *(sFreeHandles.begin());
sFreeHandles.erase(ret);
curl_easy_reset(ret);
}
if (ret)
{
sActiveHandles.insert(ret);
}
return ret;
}
//static
void LLCurl::Easy::releaseEasyHandle(CURL* handle)
{
if (!handle)
{
llerrs << "handle cannot be NULL!" << llendl;
}
if (sActiveHandles.find(handle) != sActiveHandles.end())
{
sActiveHandles.erase(handle);
sFreeHandles.insert(handle);
}
else
{
llerrs << "Invalid handle." << llendl;
}
}
LLCurl::Easy::Easy()
: mHeaders(NULL),
mCurlEasyHandle(NULL)
{
mErrorBuffer[0] = 0;
}
LLCurl::Easy* LLCurl::Easy::getEasy()
{
Easy* easy = new Easy();
easy->mCurlEasyHandle = allocEasyHandle();
if (!easy->mCurlEasyHandle)
{
// this can happen if we have too many open files (fails in c-ares/ares_init.c)
llwarns << "allocEasyHandle() returned NULL! Easy handles: " << gCurlEasyCount << " Multi handles: " << gCurlMultiCount << llendl;
delete easy;
return NULL;
}
// set no DNS caching as default for all easy handles. This prevents them adopting a
// multi handles cache if they are added to one.
CURLcode result = curl_easy_setopt(easy->mCurlEasyHandle, CURLOPT_DNS_CACHE_TIMEOUT, 0);
check_curl_code(result);
++gCurlEasyCount;
return easy;
}
LLCurl::Easy::~Easy()
{
releaseEasyHandle(mCurlEasyHandle);
--gCurlEasyCount;
curl_slist_free_all(mHeaders);
for_each(mStrings.begin(), mStrings.end(), DeletePointerArray());
}
void LLCurl::Easy::resetState()
{
curl_easy_reset(mCurlEasyHandle);
if (mHeaders)
{
curl_slist_free_all(mHeaders);
mHeaders = NULL;
}
mRequest.str("");
mRequest.clear();
mOutput.reset();
mInput.str("");
mInput.clear();
mErrorBuffer[0] = 0;
mHeaderOutput.str("");
mHeaderOutput.clear();
}
void LLCurl::Easy::setErrorBuffer()
{
setopt(CURLOPT_ERRORBUFFER, &mErrorBuffer);
}
const char* LLCurl::Easy::getErrorBuffer()
{
return mErrorBuffer;
}
void LLCurl::Easy::setCA()
{
if (!sCAPath.empty())
{
setoptString(CURLOPT_CAPATH, sCAPath);
}
if (!sCAFile.empty())
{
setoptString(CURLOPT_CAINFO, sCAFile);
}
}
void LLCurl::Easy::setHeaders()
{
setopt(CURLOPT_HTTPHEADER, mHeaders);
}
void LLCurl::Easy::getTransferInfo(LLCurl::TransferInfo* info)
{
check_curl_code(curl_easy_getinfo(mCurlEasyHandle, CURLINFO_SIZE_DOWNLOAD, &info->mSizeDownload));
check_curl_code(curl_easy_getinfo(mCurlEasyHandle, CURLINFO_TOTAL_TIME, &info->mTotalTime));
check_curl_code(curl_easy_getinfo(mCurlEasyHandle, CURLINFO_SPEED_DOWNLOAD, &info->mSpeedDownload));
}
U32 LLCurl::Easy::report(CURLcode code)
{
U32 responseCode = 0;
std::string responseReason;
if (code == CURLE_OK)
{
check_curl_code(curl_easy_getinfo(mCurlEasyHandle, CURLINFO_RESPONSE_CODE, &responseCode));
//*TODO: get reason from first line of mHeaderOutput
}
else
{
responseCode = 499;
responseReason = strerror(code) + " : " + mErrorBuffer;
setopt(CURLOPT_FRESH_CONNECT, TRUE);
}
if (mResponder)
{
mResponder->completedRaw(responseCode, responseReason, mChannels, mOutput);
mResponder = NULL;
}
resetState();
return responseCode;
}
// Note: these all assume the caller tracks the value (i.e. keeps it persistant)
void LLCurl::Easy::setopt(CURLoption option, S32 value)
{
CURLcode result = curl_easy_setopt(mCurlEasyHandle, option, value);
check_curl_code(result);
}
void LLCurl::Easy::setopt(CURLoption option, void* value)
{
CURLcode result = curl_easy_setopt(mCurlEasyHandle, option, value);
check_curl_code(result);
}
void LLCurl::Easy::setopt(CURLoption option, char* value)
{
CURLcode result = curl_easy_setopt(mCurlEasyHandle, option, value);
check_curl_code(result);
}
// Note: this copies the string so that the caller does not have to keep it around
void LLCurl::Easy::setoptString(CURLoption option, const std::string& value)
{
char* tstring = new char[value.length()+1];
strcpy(tstring, value.c_str());
mStrings.push_back(tstring);
CURLcode result = curl_easy_setopt(mCurlEasyHandle, option, tstring);
check_curl_code(result);
}
void LLCurl::Easy::slist_append(const char* str)
{
mHeaders = curl_slist_append(mHeaders, str);
}
size_t curlReadCallback(char* data, size_t size, size_t nmemb, void* user_data)
{
LLCurl::Easy* easy = (LLCurl::Easy*)user_data;
S32 n = size * nmemb;
S32 startpos = easy->getInput().tellg();
easy->getInput().seekg(0, std::ios::end);
S32 endpos = easy->getInput().tellg();
easy->getInput().seekg(startpos, std::ios::beg);
S32 maxn = endpos - startpos;
n = llmin(n, maxn);
easy->getInput().read((char*)data, n);
return n;
}
size_t curlWriteCallback(char* data, size_t size, size_t nmemb, void* user_data)
{
LLCurl::Easy* easy = (LLCurl::Easy*)user_data;
S32 n = size * nmemb;
easy->getOutput()->append(easy->getChannels().in(), (const U8*)data, n);
return n;
}
size_t curlHeaderCallback(void* data, size_t size, size_t nmemb, void* user_data)
{
LLCurl::Easy* easy = (LLCurl::Easy*)user_data;
size_t n = size * nmemb;
easy->getHeaderOutput().write((const char*)data, n);
return n;
}
void LLCurl::Easy::prepRequest(const std::string& url,
const std::vector<std::string>& headers,
ResponderPtr responder, S32 time_out, bool post)
{
resetState();
if (post) setoptString(CURLOPT_ENCODING, "");
//setopt(CURLOPT_VERBOSE, 1); // useful for debugging
setopt(CURLOPT_NOSIGNAL, 1);
// Set the CURL options for either Socks or HTTP proxy
LLProxy::getInstance()->applyProxySettings(this);
mOutput.reset(new LLBufferArray);
setopt(CURLOPT_WRITEFUNCTION, (void*)&curlWriteCallback);
setopt(CURLOPT_WRITEDATA, (void*)this);
setopt(CURLOPT_READFUNCTION, (void*)&curlReadCallback);
setopt(CURLOPT_READDATA, (void*)this);
setopt(CURLOPT_HEADERFUNCTION, (void*)&curlHeaderCallback);
setopt(CURLOPT_HEADERDATA, (void*)this);
// Allow up to five redirects
if (responder && responder->followRedir())
{
setopt(CURLOPT_FOLLOWLOCATION, 1);
setopt(CURLOPT_MAXREDIRS, MAX_REDIRECTS);
}
setErrorBuffer();
setCA();
setopt(CURLOPT_SSL_VERIFYPEER, true);
//don't verify host name so urls with scrubbed host names will work (improves DNS performance)
setopt(CURLOPT_SSL_VERIFYHOST, 0);
setopt(CURLOPT_TIMEOUT, llmax(time_out, CURL_REQUEST_TIMEOUT));
setoptString(CURLOPT_URL, url);
mResponder = responder;
if (!post)
{
slist_append("Connection: keep-alive");
slist_append("Keep-alive: 300");
// Accept and other headers
for (std::vector<std::string>::const_iterator iter = headers.begin();
iter != headers.end(); ++iter)
{
slist_append((*iter).c_str());
}
}
}
////////////////////////////////////////////////////////////////////////////
LLCurl::Multi::Multi()
: mQueued(0),
mErrorCount(0),
mState(STATE_READY),
mDead(FALSE),
mMutexp(NULL),
mDeletionMutexp(NULL)
{
mCurlMultiHandle = curl_multi_init();
if (!mCurlMultiHandle)
{
llwarns << "curl_multi_init() returned NULL! Easy handles: " << gCurlEasyCount << " Multi handles: " << gCurlMultiCount << llendl;
mCurlMultiHandle = curl_multi_init();
}
llassert_always(mCurlMultiHandle);
if(LLCurl::getCurlThread()->getThreaded())
{
mMutexp = new LLMutex(NULL) ;
mDeletionMutexp = new LLMutex(NULL) ;
}
LLCurl::getCurlThread()->addMulti(this) ;
++gCurlMultiCount;
}
LLCurl::Multi::~Multi()
{
// Clean up active
for(easy_active_list_t::iterator iter = mEasyActiveList.begin();
iter != mEasyActiveList.end(); ++iter)
{
Easy* easy = *iter;
check_curl_multi_code(curl_multi_remove_handle(mCurlMultiHandle, easy->getCurlHandle()));
delete easy;
}
mEasyActiveList.clear();
mEasyActiveMap.clear();
// Clean up freed
for_each(mEasyFreeList.begin(), mEasyFreeList.end(), DeletePointer());
mEasyFreeList.clear();
check_curl_multi_code(curl_multi_cleanup(mCurlMultiHandle));
delete mMutexp ;
mMutexp = NULL ;
delete mDeletionMutexp ;
mDeletionMutexp = NULL ;
--gCurlMultiCount;
}
void LLCurl::Multi::lock()
{
if(mMutexp)
{
mMutexp->lock() ;
}
}
void LLCurl::Multi::unlock()
{
if(mMutexp)
{
mMutexp->unlock() ;
}
}
void LLCurl::Multi::markDead()
{
LLMutexLock lock(mDeletionMutexp) ;
mDead = TRUE ;
}
void LLCurl::Multi::setState(LLCurl::Multi::ePerformState state)
{
LLMutexLock lock(mMutexp) ;
mState = state ;
if(mState == STATE_READY)
{
LLCurl::getCurlThread()->setPriority(mHandle, LLQueuedThread::PRIORITY_NORMAL) ;
}
}
LLCurl::Multi::ePerformState LLCurl::Multi::getState()
{
ePerformState state ;
{
LLMutexLock lock(mMutexp) ;
state = mState ;
}
return state ;
}
bool LLCurl::Multi::isCompleted()
{
return STATE_COMPLETED == getState() ;
}
bool LLCurl::Multi::waitToComplete()
{
if(!mMutexp) //not threaded
{
doPerform() ;
return true ;
}
bool completed ;
{
LLMutexLock lock(mMutexp) ;
completed = (STATE_COMPLETED == mState) ;
if(!completed)
{
LLCurl::getCurlThread()->setPriority(mHandle, LLQueuedThread::PRIORITY_URGENT) ;
}
}
return completed;
}
CURLMsg* LLCurl::Multi::info_read(S32* msgs_in_queue)
{
CURLMsg* curlmsg = curl_multi_info_read(mCurlMultiHandle, msgs_in_queue);
return curlmsg;
}
//return true if dead
bool LLCurl::Multi::doPerform()
{
LLMutexLock lock(mDeletionMutexp) ;
bool dead = mDead ;
if(mDead)
{
setState(STATE_COMPLETED);
mQueued = 0 ;
}
else if(getState() != STATE_COMPLETED)
{
setState(STATE_PERFORMING);
S32 q = 0;
for (S32 call_count = 0;
call_count < MULTI_PERFORM_CALL_REPEAT;
call_count++)
{
LLMutexLock lock(mMutexp) ;
CURLMcode code = curl_multi_perform(mCurlMultiHandle, &q);
if (CURLM_CALL_MULTI_PERFORM != code || q == 0)
{
check_curl_multi_code(code);
break;
}
}
mQueued = q;
setState(STATE_COMPLETED) ;
}
return dead ;
}
S32 LLCurl::Multi::process()
{
waitToComplete() ;
if (getState() != STATE_COMPLETED)
{
return 0;
}
CURLMsg* msg;
int msgs_in_queue;
S32 processed = 0;
while ((msg = info_read(&msgs_in_queue)))
{
++processed;
if (msg->msg == CURLMSG_DONE)
{
U32 response = 0;
easy_active_map_t::iterator iter = mEasyActiveMap.find(msg->easy_handle);
if (iter != mEasyActiveMap.end())
{
Easy* easy = iter->second;
response = easy->report(msg->data.result);
removeEasy(easy);
}
else
{
response = 499;
//*TODO: change to llwarns
llerrs << "cleaned up curl request completed!" << llendl;
}
if (response >= 400)
{
// failure of some sort, inc mErrorCount for debugging and flagging multi for destruction
++mErrorCount;
}
}
}
setState(STATE_READY);
return processed;
}
LLCurl::Easy* LLCurl::Multi::allocEasy()
{
Easy* easy = 0;
if (mEasyFreeList.empty())
{
easy = Easy::getEasy();
}
else
{
easy = *(mEasyFreeList.begin());
mEasyFreeList.erase(easy);
}
if (easy)
{
mEasyActiveList.insert(easy);
mEasyActiveMap[easy->getCurlHandle()] = easy;
}
return easy;
}
bool LLCurl::Multi::addEasy(Easy* easy)
{
LLMutexLock lock(mMutexp) ;
CURLMcode mcode = curl_multi_add_handle(mCurlMultiHandle, easy->getCurlHandle());
check_curl_multi_code(mcode);
//if (mcode != CURLM_OK)
//{
// llwarns << "Curl Error: " << curl_multi_strerror(mcode) << llendl;
// return false;
//}
return true;
}
void LLCurl::Multi::easyFree(Easy* easy)
{
LLMutexLock lock(mMutexp) ;
mEasyActiveList.erase(easy);
mEasyActiveMap.erase(easy->getCurlHandle());
if (mEasyFreeList.size() < EASY_HANDLE_POOL_SIZE)
{
easy->resetState();
mEasyFreeList.insert(easy);
}
else
{
delete easy;
}
}
void LLCurl::Multi::removeEasy(Easy* easy)
{
LLMutexLock lock(mMutexp) ;
check_curl_multi_code(curl_multi_remove_handle(mCurlMultiHandle, easy->getCurlHandle()));
easyFree(easy);
}
//------------------------------------------------------------
//LLCurlThread
LLCurlThread::CurlRequest::CurlRequest(handle_t handle, LLCurl::Multi* multi, LLCurlThread* curl_thread) :
LLQueuedThread::QueuedRequest(handle, LLQueuedThread::PRIORITY_NORMAL, FLAG_AUTO_COMPLETE),
mMulti(multi),
mCurlThread(curl_thread)
{
}
LLCurlThread::CurlRequest::~CurlRequest()
{
if(mMulti)
{
mCurlThread->deleteMulti(mMulti) ;
mMulti = NULL ;
}
}
bool LLCurlThread::CurlRequest::processRequest()
{
bool completed = true ;
if(mMulti)
{
completed = mCurlThread->doMultiPerform(mMulti) ;
setPriority(LLQueuedThread::PRIORITY_LOW) ;
}
return completed ;
}
void LLCurlThread::CurlRequest::finishRequest(bool completed)
{
mCurlThread->deleteMulti(mMulti) ;
mMulti = NULL ;
}
LLCurlThread::LLCurlThread(bool threaded) :
LLQueuedThread("curlthread", threaded)
{
}
//virtual
LLCurlThread::~LLCurlThread()
{
}
S32 LLCurlThread::update(F32 max_time_ms)
{
return LLQueuedThread::update(max_time_ms);
}
void LLCurlThread::addMulti(LLCurl::Multi* multi)
{
multi->mHandle = generateHandle() ;
CurlRequest* req = new CurlRequest(multi->mHandle, multi, this) ;
if (!addRequest(req))
{
llwarns << "curl request added when the thread is quitted" << llendl;
}
}
void LLCurlThread::killMulti(LLCurl::Multi* multi)
{
multi->markDead() ;
}
//private
bool LLCurlThread::doMultiPerform(LLCurl::Multi* multi)
{
return multi->doPerform() ;
}
//private
void LLCurlThread::deleteMulti(LLCurl::Multi* multi)
{
delete multi ;
}
//------------------------------------------------------------
//static
std::string LLCurl::strerror(CURLcode errorcode)
{
return std::string(curl_easy_strerror(errorcode));
}
////////////////////////////////////////////////////////////////////////////
// For generating a simple request for data
// using one multi and one easy per request
LLCurlRequest::LLCurlRequest() :
mActiveMulti(NULL),
mActiveRequestCount(0)
{
mProcessing = FALSE;
}
LLCurlRequest::~LLCurlRequest()
{
//stop all Multi handle background threads
for (curlmulti_set_t::iterator iter = mMultiSet.begin(); iter != mMultiSet.end(); ++iter)
{
LLCurl::getCurlThread()->killMulti(*iter) ;
}
mMultiSet.clear() ;
}
void LLCurlRequest::addMulti()
{
LLCurl::Multi* multi = new LLCurl::Multi();
mMultiSet.insert(multi);
mActiveMulti = multi;
mActiveRequestCount = 0;
}
LLCurl::Easy* LLCurlRequest::allocEasy()
{
if (!mActiveMulti ||
mActiveRequestCount >= MAX_ACTIVE_REQUEST_COUNT ||
mActiveMulti->mErrorCount > 0)
{
addMulti();
}
llassert_always(mActiveMulti);
++mActiveRequestCount;
LLCurl::Easy* easy = mActiveMulti->allocEasy();
return easy;
}
bool LLCurlRequest::addEasy(LLCurl::Easy* easy)
{
llassert_always(mActiveMulti);
if (mProcessing)
{
llerrs << "Posting to a LLCurlRequest instance from within a responder is not allowed (causes DNS timeouts)." << llendl;
}
bool res = mActiveMulti->addEasy(easy);
return res;
}
void LLCurlRequest::get(const std::string& url, LLCurl::ResponderPtr responder)
{
getByteRange(url, headers_t(), 0, -1, responder);
}
bool LLCurlRequest::getByteRange(const std::string& url,
const headers_t& headers,
S32 offset, S32 length,
LLCurl::ResponderPtr responder)
{
LLCurl::Easy* easy = allocEasy();
if (!easy)
{
return false;
}
easy->prepRequest(url, headers, responder);
easy->setopt(CURLOPT_HTTPGET, 1);
if (length > 0)
{
std::string range = llformat("Range: bytes=%d-%d", offset,offset+length-1);
easy->slist_append(range.c_str());
}
easy->setHeaders();
bool res = addEasy(easy);
return res;
}
bool LLCurlRequest::post(const std::string& url,
const headers_t& headers,
const LLSD& data,
LLCurl::ResponderPtr responder, S32 time_out)
{
LLCurl::Easy* easy = allocEasy();
if (!easy)
{
return false;
}
easy->prepRequest(url, headers, responder, time_out);
LLSDSerialize::toXML(data, easy->getInput());
S32 bytes = easy->getInput().str().length();
easy->setopt(CURLOPT_POST, 1);
easy->setopt(CURLOPT_POSTFIELDS, (void*)NULL);
easy->setopt(CURLOPT_POSTFIELDSIZE, bytes);
easy->slist_append("Content-Type: application/llsd+xml");
easy->setHeaders();
lldebugs << "POSTING: " << bytes << " bytes." << llendl;
bool res = addEasy(easy);
return res;
}
bool LLCurlRequest::post(const std::string& url,
const headers_t& headers,
const std::string& data,
LLCurl::ResponderPtr responder, S32 time_out)
{
LLCurl::Easy* easy = allocEasy();
if (!easy)
{
return false;
}
easy->prepRequest(url, headers, responder, time_out);
easy->getInput().write(data.data(), data.size());
S32 bytes = easy->getInput().str().length();
easy->setopt(CURLOPT_POST, 1);
easy->setopt(CURLOPT_POSTFIELDS, (void*)NULL);
easy->setopt(CURLOPT_POSTFIELDSIZE, bytes);
easy->slist_append("Content-Type: application/octet-stream");
easy->setHeaders();
lldebugs << "POSTING: " << bytes << " bytes." << llendl;
bool res = addEasy(easy);
return res;
}
// Note: call once per frame
S32 LLCurlRequest::process()
{
S32 res = 0;
mProcessing = TRUE;
for (curlmulti_set_t::iterator iter = mMultiSet.begin();
iter != mMultiSet.end(); )
{
curlmulti_set_t::iterator curiter = iter++;
LLCurl::Multi* multi = *curiter;
S32 tres = multi->process();
res += tres;
if (multi != mActiveMulti && tres == 0 && multi->mQueued == 0)
{
mMultiSet.erase(curiter);
LLCurl::getCurlThread()->killMulti(multi);
}
}
mProcessing = FALSE;
return res;
}
S32 LLCurlRequest::getQueued()
{
S32 queued = 0;
for (curlmulti_set_t::iterator iter = mMultiSet.begin();
iter != mMultiSet.end(); )
{
curlmulti_set_t::iterator curiter = iter++;
LLCurl::Multi* multi = *curiter;
queued += multi->mQueued;
if (multi->getState() != LLCurl::Multi::STATE_READY)
{
++queued;
}
}
return queued;
}
////////////////////////////////////////////////////////////////////////////
// For generating one easy request
// associated with a single multi request
LLCurlEasyRequest::LLCurlEasyRequest()
: mRequestSent(false),
mResultReturned(false)
{
mMulti = new LLCurl::Multi();
mEasy = mMulti->allocEasy();
if (mEasy)
{
mEasy->setErrorBuffer();
mEasy->setCA();
// Set proxy settings if configured to do so.
LLProxy::getInstance()->applyProxySettings(mEasy);
}
}
LLCurlEasyRequest::~LLCurlEasyRequest()
{
LLCurl::getCurlThread()->killMulti(mMulti) ;
}
void LLCurlEasyRequest::setopt(CURLoption option, S32 value)
{
if (mEasy)
{
mEasy->setopt(option, value);
}
}
void LLCurlEasyRequest::setoptString(CURLoption option, const std::string& value)
{
if (mEasy)
{
mEasy->setoptString(option, value);
}
}
void LLCurlEasyRequest::setPost(char* postdata, S32 size)
{
if (mEasy)
{
mEasy->setopt(CURLOPT_POST, 1);
mEasy->setopt(CURLOPT_POSTFIELDS, postdata);
mEasy->setopt(CURLOPT_POSTFIELDSIZE, size);
}
}
void LLCurlEasyRequest::setHeaderCallback(curl_header_callback callback, void* userdata)
{
if (mEasy)
{
mEasy->setopt(CURLOPT_HEADERFUNCTION, (void*)callback);
mEasy->setopt(CURLOPT_HEADERDATA, userdata); // aka CURLOPT_WRITEHEADER
}
}
void LLCurlEasyRequest::setWriteCallback(curl_write_callback callback, void* userdata)
{
if (mEasy)
{
mEasy->setopt(CURLOPT_WRITEFUNCTION, (void*)callback);
mEasy->setopt(CURLOPT_WRITEDATA, userdata);
}
}
void LLCurlEasyRequest::setReadCallback(curl_read_callback callback, void* userdata)
{
if (mEasy)
{
mEasy->setopt(CURLOPT_READFUNCTION, (void*)callback);
mEasy->setopt(CURLOPT_READDATA, userdata);
}
}
void LLCurlEasyRequest::setSSLCtxCallback(curl_ssl_ctx_callback callback, void* userdata)
{
if (mEasy)
{
mEasy->setopt(CURLOPT_SSL_CTX_FUNCTION, (void*)callback);
mEasy->setopt(CURLOPT_SSL_CTX_DATA, userdata);
}
}
void LLCurlEasyRequest::slist_append(const char* str)
{
if (mEasy)
{
mEasy->slist_append(str);
}
}
void LLCurlEasyRequest::sendRequest(const std::string& url)
{
llassert_always(!mRequestSent);
mRequestSent = true;
lldebugs << url << llendl;
if (mEasy)
{
mEasy->setHeaders();
mEasy->setoptString(CURLOPT_URL, url);
mMulti->addEasy(mEasy);
}
}
void LLCurlEasyRequest::requestComplete()
{
llassert_always(mRequestSent);
mRequestSent = false;
if (mEasy)
{
mMulti->removeEasy(mEasy);
}
}
// Usage: Call getRestult until it returns false (no more messages)
bool LLCurlEasyRequest::getResult(CURLcode* result, LLCurl::TransferInfo* info)
{
if (!mMulti->isCompleted())
{ //we're busy, try again later
return false;
}
mMulti->setState(LLCurl::Multi::STATE_READY) ;
if (!mEasy)
{
// Special case - we failed to initialize a curl_easy (can happen if too many open files)
// Act as though the request failed to connect
if (mResultReturned)
{
return false;
}
else
{
*result = CURLE_FAILED_INIT;
mResultReturned = true;
return true;
}
}
// In theory, info_read might return a message with a status other than CURLMSG_DONE
// In practice for all messages returned, msg == CURLMSG_DONE
// Ignore other messages just in case
while(1)
{
S32 q;
CURLMsg* curlmsg = info_read(&q, info);
if (curlmsg)
{
if (curlmsg->msg == CURLMSG_DONE)
{
*result = curlmsg->data.result;
return true;
}
// else continue
}
else
{
return false;
}
}
}
// private
CURLMsg* LLCurlEasyRequest::info_read(S32* q, LLCurl::TransferInfo* info)
{
if (mEasy)
{
CURLMsg* curlmsg = mMulti->info_read(q);
if (curlmsg && curlmsg->msg == CURLMSG_DONE)
{
if (info)
{
mEasy->getTransferInfo(info);
}
}
return curlmsg;
}
return NULL;
}
std::string LLCurlEasyRequest::getErrorString()
{
return mEasy ? std::string(mEasy->getErrorBuffer()) : std::string();
}
////////////////////////////////////////////////////////////////////////////
#if SAFE_SSL
//static
void LLCurl::ssl_locking_callback(int mode, int type, const char *file, int line)
{
if (mode & CRYPTO_LOCK)
{
LLCurl::sSSLMutex[type]->lock();
}
else
{
LLCurl::sSSLMutex[type]->unlock();
}
}
//static
unsigned long LLCurl::ssl_thread_id(void)
{
return LLThread::currentID();
}
#endif
void LLCurl::initClass(bool multi_threaded)
{
// Do not change this "unless you are familiar with and mean to control
// internal operations of libcurl"
// - http://curl.haxx.se/libcurl/c/curl_global_init.html
CURLcode code = curl_global_init(CURL_GLOBAL_ALL);
check_curl_code(code);
#if SAFE_SSL
S32 mutex_count = CRYPTO_num_locks();
for (S32 i=0; i<mutex_count; i++)
{
sSSLMutex.push_back(new LLMutex(NULL));
}
CRYPTO_set_id_callback(&LLCurl::ssl_thread_id);
CRYPTO_set_locking_callback(&LLCurl::ssl_locking_callback);
#endif
sCurlThread = new LLCurlThread(multi_threaded) ;
}
void LLCurl::cleanupClass()
{
//shut down curl thread
while(1)
{
if(!sCurlThread->update(1)) //finish all tasks
{
break ;
}
}
sCurlThread->shutdown() ;
delete sCurlThread ;
sCurlThread = NULL ;
#if SAFE_SSL
CRYPTO_set_locking_callback(NULL);
for_each(sSSLMutex.begin(), sSSLMutex.end(), DeletePointer());
#endif
for (std::set<CURL*>::iterator iter = Easy::sFreeHandles.begin(); iter != Easy::sFreeHandles.end(); ++iter)
{
CURL* curl = *iter;
curl_easy_cleanup(curl);
}
Easy::sFreeHandles.clear();
llassert(Easy::sActiveHandles.empty());
}
const unsigned int LLCurl::MAX_REDIRECTS = 5;
// Provide access to LLCurl free functions outside of llcurl.cpp without polluting the global namespace.
void LLCurlFF::check_easy_code(CURLcode code)
{
check_curl_code(code);
}
void LLCurlFF::check_multi_code(CURLMcode code)
{
check_curl_multi_code(code);
}
|