9#include "XrdVersion.hh"
38uint64_t TPCHandler::m_monid{0};
39int TPCHandler::m_marker_period = 5;
40size_t TPCHandler::m_block_size = 16*1024*1024;
41size_t TPCHandler::m_small_block_size = 1*1024*1024;
43bool TPCHandler::allowMissingCRL =
false;
51TPCHandler::TPCLogRecord::~TPCLogRecord()
58 monInfo.
clID = clID.c_str();
60 gettimeofday(&monInfo.
endT, 0);
63 {monInfo.
dstURL = local.c_str();
64 monInfo.
srcURL = remote.c_str();
66 monInfo.
dstURL = remote.c_str();
67 monInfo.
srcURL = local.c_str();
71 if (!status) monInfo.
endRC = 0;
72 else if (tpc_status > 0) monInfo.
endRC = tpc_status;
73 else monInfo.
endRC = 1;
74 monInfo.
strm =
static_cast<unsigned char>(streams);
75 monInfo.
fSize = (bytes_transferred < 0 ? 0 : bytes_transferred);
78 tpcMonitor->Report(monInfo);
88 if (curl) curl_easy_cleanup(curl);
103int TPCHandler::sockopt_callback(
void *clientp, curl_socket_t curlfd, curlsocktype purpose) {
104 TPCLogRecord * rec = (TPCLogRecord *)clientp;
105 if (purpose == CURLSOCKTYPE_IPCXN && rec && rec->pmarkManager.isEnabled()) {
108 return CURL_SOCKOPT_ALREADY_CONNECTED;
110 return CURL_SOCKOPT_OK;
122int TPCHandler::opensocket_callback(
void *clientp,
123 curlsocktype purpose,
124 struct curl_sockaddr *aInfo)
128 if (purpose != CURLSOCKTYPE_IPCXN)
129 return CURL_SOCKET_BAD;
132 return CURL_SOCKET_BAD;
135 int fd = XrdSysFD_Socket(aInfo->family, aInfo->socktype, aInfo->protocol);
138 return CURL_SOCKET_BAD;
144 XrdNetAddr thePeer(&(aInfo->addr));
145 TPCLogRecord *rec =
static_cast<TPCLogRecord*
>(clientp);
148 if ((!rec->allow_private && thePeer.isPrivate()) || (!rec->allow_local && thePeer.isLocal())) {
149 rec->tpc_status = 403;
150 rec->m_log->Emsg(rec->log_prefix.c_str(),
151 "Connection to local/private address is forbidden");
153 return CURL_SOCKET_BAD;
158 std::stringstream connectErrMsg;
159 if(!rec->pmarkManager.connect(fd, &(aInfo->addr), aInfo->addrlen, CONNECT_TIMEOUT, connectErrMsg)) {
161 rec->m_log->Emsg(rec->log_prefix.c_str(),
"Unable to connect socket: ", connectErrMsg.str().c_str());
162 return CURL_SOCKET_BAD;
168int TPCHandler::closesocket_callback(
void *clientp, curl_socket_t fd) {
169 TPCLogRecord * rec = (TPCLogRecord *)clientp;
174 rec->pmarkManager.endPmark(fd);
189int TPCHandler::ssl_ctx_callback(
CURL *curl,
void *ssl_ctx,
void *clientp) {
190 TPCLogRecord * rec = (TPCLogRecord *)clientp;
191 SSL_CTX* ctx =
static_cast<SSL_CTX*
>(ssl_ctx);
193 if (rec && rec->ca_store) {
197 SSL_CTX_set1_cert_store(ctx, rec->ca_store.get());
199 if (allowMissingCRL) {
203 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_callback);
208int TPCHandler::verify_callback(
int preverify_ok, X509_STORE_CTX* ctx) {
209 if (preverify_ok == 1)
return 1;
211 int err = X509_STORE_CTX_get_error(ctx);
213 if (err == X509_V_ERR_UNABLE_TO_GET_CRL) {
214 X509_STORE_CTX_set_error(ctx, X509_V_OK);
226std::string TPCHandler::prepareURL(XrdHttpExtReq &req) {
231bool TPCHandler::mismatchReprDigest(
const std::map<std::string, std::string> & passiveSrvReprDigest, XrdHttpExtReq &req,
233 if(passiveSrvReprDigest.size()) {
234 for (
const auto & [digestName, digestValue]: passiveSrvReprDigest) {
235 auto clientDigestMatch = req.
mReprDigest.find(digestName);
238 if (clientDigestMatch->second != digestValue) {
240 std::stringstream errMsg;
241 errMsg <<
"Mismatch between client-provided and remote server checksums:"
242 <<
" client = (" << clientDigestMatch->first <<
"=" << clientDigestMatch->second <<
")"
243 <<
" server = (" << digestName <<
"=" << digestValue <<
")";
244 logTransferEvent(
LogMask::Error, rec,
"REPRDIGEST_VERIFY_FAIL", errMsg.str());
246 req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(errMsg, rec, CURLcode::CURLE_OK).c_str(), 0);
266 std::stringstream parser(opaque);
267 std::string sequence;
268 std::stringstream output;
270 while (
getline(parser, sequence,
'&')) {
271 if (sequence.empty()) {
continue;}
272 size_t equal_pos = sequence.find(
'=');
274 if (equal_pos != std::string::npos)
275 val = curl_easy_escape(curl, sequence.c_str() + equal_pos + 1, sequence.size() - equal_pos - 1);
277 if (!val && equal_pos != std::string::npos) {
continue;}
279 if (!first) output <<
"&";
281 output << sequence.substr(0, equal_pos);
283 output <<
"=" << val;
295TPCHandler::ConfigureCurlCA(
CURL *curl, TPCLogRecord &rec)
305 if (m_ca_file && m_sslctx_supported && m_cafile.empty()) {
306 rec.ca_store = m_ca_file->CAStore();
308 m_log.Log(
Error,
"TpcHandler",
"No CA store is available; refusing to "
309 "fall back to libcurl's default CA bundle");
314 curl_easy_setopt(curl, CURLOPT_CAINFO,
static_cast<char *
>(
nullptr));
315 curl_easy_setopt(curl, CURLOPT_CAPATH,
static_cast<char *
>(
nullptr));
316 curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, ssl_ctx_callback);
317 curl_easy_setopt(curl, CURLOPT_SSL_CTX_DATA, &rec);
321 auto ca_filename = m_ca_file ? m_ca_file->CAFilename() :
"";
322 auto crl_filename = m_ca_file ? m_ca_file->CRLFilename() :
"";
323 if (!ca_filename.empty() && !crl_filename.empty()) {
324 curl_easy_setopt(curl, CURLOPT_CAINFO, ca_filename.c_str());
328 std::ifstream in(crl_filename, std::ifstream::ate | std::ifstream::binary);
329 if(in.tellg() > 0 && m_ca_file->atLeastOneValidCRLFound()){
330 curl_easy_setopt(curl, CURLOPT_CRLFILE, crl_filename.c_str());
331 if (allowMissingCRL) {
333 curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, ssl_ctx_callback);
336 std::ostringstream oss;
337 oss <<
"No valid CRL file has been found in the file " << crl_filename <<
". Disabling CRL checking.";
338 m_log.Log(
Warning,
"TpcHandler",oss.str().c_str());
341 else if (!m_cadir.empty()) {
342 curl_easy_setopt(curl, CURLOPT_CAPATH, m_cadir.c_str());
344 if (!m_cafile.empty()) {
345 curl_easy_setopt(curl, CURLOPT_CAINFO, m_cafile.c_str());
351TPCHandler::ConfigureCurlLowSpeed(
CURL *curl)
355 curl_version_info_data *curl_ver = curl_version_info(CURLVERSION_NOW);
356 if (m_low_speed_limit > 0 && curl_ver && curl_ver->age > 0 &&
357 curl_ver->version_num >= 0x072600) {
358 curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, m_low_speed_time);
359 curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, m_low_speed_limit);
365 return !strcmp(verb,
"COPY") || !strcmp(verb,
"OPTIONS");
374 const std::string replace_schemes[] = {
"davs://",
"s3://",
"s3s://" };
376 for (
const auto& s : replace_schemes)
377 if (url.compare(0, s.size(), s) == 0)
378 return "https://" + url.substr(s.size());
385 const std::string allowed_schemes[] = {
"https://",
"http://" };
387 for (
const auto& s : allowed_schemes)
388 if (url.compare(0, s.size(), s) == 0)
399 if (req.
verb ==
"OPTIONS") {
400 return ProcessOptionsReq(req);
403 if (header != req.
headers.end()) {
404 if (header->second !=
"none") {
405 m_log.Emsg(
"ProcessReq",
"COPY requested an unsupported credential type: ", header->second.c_str());
406 return req.
SendSimpleResp(400, NULL, NULL,
"COPY requestd an unsupported Credential type", 0);
410 if (header != req.
headers.end()) {
413 const char *error_src =
"COPY rejected: disallowed scheme in source URL";
414 m_log.Emsg(
"ProcessReq", error_src, src.c_str());
417 return ProcessPullReq(src, req);
420 if (header != req.
headers.end()) {
421 const std::string& dst = header->second;
423 const char *error_dst =
"COPY rejected: disallowed scheme in destination URL";
424 m_log.Emsg(
"ProcessReq", error_dst, dst.c_str());
427 return ProcessPushReq(header->second, req);
429 m_log.Emsg(
"ProcessReq",
"COPY verb requested but no source or destination specified.");
430 return req.
SendSimpleResp(400, NULL, NULL,
"No Source or Destination specified", 0);
446 m_allow_local(false),
447 m_allow_private(true),
449 m_fixed_route(false),
450 m_low_speed_limit(10*1024),
451 m_low_speed_time(2*60),
453 m_first_timeout(120),
454 m_log(log->logger(),
"TPC_"),
457 if (!Configure(config, myEnv)) {
458 throw std::runtime_error(
"Failed to configure the HTTP third-party-copy handler.");
476 return req.
SendSimpleResp(200, NULL, (
char *)
"DAV: 1\r\nDAV: <http://apache.org/dav/propset/fs/1>\r\nAllow: HEAD,GET,PUT,PROPFIND,DELETE,OPTIONS,COPY", NULL, 0);
486 if (authz_header != req.
headers.end()) {
487 std::stringstream ss;
488 ss <<
"authz=" <<
encode_str(authz_header->second);
498int TPCHandler::RedirectTransfer(
CURL *curl,
const std::string &redirect_resource,
499 XrdHttpExtReq &req, XrdOucErrInfo &error, TPCLogRecord &rec)
503 if ((ptr == NULL) || (*ptr ==
'\0') || (port == 0)) {
505 std::stringstream ss;
506 ss <<
"Internal error: redirect without hostname";
507 logTransferEvent(
LogMask::Error, rec,
"REDIRECT_INTERNAL_ERROR", ss.str());
508 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
514 std::string finalTarget = ptr;
526 std::string newTarget;
531 finalTarget = std::move(newTarget);
533 logTransferEvent(
LogMask::Info, rec,
"REDIRECT_PLUGIN_REWRITE",
537 std::stringstream ess;
538 ess <<
"Redirect plugin error: " << errMsg;
542 generateClientErr(ess, rec).c_str(), 0);
554 std::string opaque = cgi.empty() ? std::string() : cgi.substr(1);
556 std::stringstream ss;
557 ss <<
"Location: http" << (m_desthttps ?
"s" :
"") <<
"://" << host <<
":" << port <<
"/" << redirect_resource;
559 if (!opaque.empty()) {
563 char sep = (redirect_resource.find(
'?') == std::string::npos) ?
'?' :
'&';
564 ss << sep << encode_xrootd_opaque_to_uri(curl, opaque);
569 return req.
SendSimpleResp(rec.status, NULL,
const_cast<char *
>(ss.str().c_str()),
577int TPCHandler::OpenWaitStall(XrdSfsFile &fh,
const std::string &resource,
578 int mode,
int openMode,
const XrdSecEntity &sec,
579 const std::string &authz)
586 size_t pos = resource.find(
'?');
588 std::string path = resource.substr(0, pos);
590 if (pos != std::string::npos) {
591 opaque = resource.substr(pos + 1);
596 opaque += (opaque.empty() ?
"" :
"&");
599 open_result = fh.
open(path.c_str(), mode, openMode, &sec, opaque.c_str());
603 if (open_result ==
SFS_STARTED) {secs_to_stall = secs_to_stall/2 + 5;}
604 std::this_thread::sleep_for (std::chrono::seconds(secs_to_stall));
620int TPCHandler::PerformHEADRequest(
CURL *curl, XrdHttpExtReq &req,
State &state,
621 bool &success, TPCLogRecord &rec,
bool shouldReturnErrorToClient) {
623 curl_easy_setopt(curl, CURLOPT_NOBODY, 1);
625 curl_easy_setopt(curl, CURLOPT_TIMEOUT, CONNECT_TIMEOUT);
627 res = curl_easy_perform(curl);
630 curl_easy_setopt(curl, CURLOPT_NOBODY, 0);
632 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 0L);
633 curl_easy_setopt(curl, CURLOPT_FAILONERROR,
true);
635 std::stringstream ss;
638 res = CURLE_HTTP_RETURNED_ERROR;
640 if (res != CURLE_OK) {
641 ss << curl_easy_strerror(res);
643 case CURLE_HTTP_RETURNED_ERROR:
645 ss <<
": remote host returned '" << rec.tpc_status <<
" "
648 case CURLE_COULDNT_CONNECT:
649 switch (rec.tpc_status) {
651 ss <<
": connection to local/private addresses is forbidden";
654 ss <<
": internal server failure";
655 rec.tpc_status = 500;
659 rec.tpc_status = 500;
664 if (rec.tpc_status >= 400) {
666 return shouldReturnErrorToClient ? req.
SendSimpleResp(rec.tpc_status, NULL, NULL, generateClientErr(ss, rec, res).c_str(), 0) : -1;
670 ss <<
"Successfully determined remote file information for pull request: "
673 unsigned int cksumIndex = 1;
674 for(
const auto & [cksumType,cksumValue]: state.
GetReprDigest()) {
675 ss <<
" chksum" << cksumIndex <<
"=(" << cksumType <<
"," << cksumValue <<
")";
683int TPCHandler::GetRemoteFileInfoTPCPull(
CURL *curl, XrdHttpExtReq &req, uint64_t &contentLength, std::map<std::string,std::string> & reprDigest,
bool & success, TPCLogRecord &rec) {
690 if ((result = PerformHEADRequest(curl, req, state, success, rec)) || !success) {
702int TPCHandler::SendPerfMarker(XrdHttpExtReq &req, TPCLogRecord &rec, TPC::State &state) {
703 std::stringstream ss;
704 const std::string crlf =
"\n";
705 ss <<
"Perf Marker" << crlf;
706 ss <<
"Timestamp: " << time(NULL) << crlf;
707 ss <<
"Stripe Index: 0" << crlf;
709 ss <<
"Total Stripe Count: 1" << crlf;
714 ss <<
"RemoteConnections: " << desc << crlf;
719 return req.
ChunkResp(ss.str().c_str(), 0);
726int TPCHandler::SendPerfMarker(XrdHttpExtReq &req, TPCLogRecord &rec, std::vector<State*> &state,
727 off_t bytes_transferred)
741 std::stringstream ss;
742 const std::string crlf =
"\n";
743 ss <<
"Perf Marker" << crlf;
744 ss <<
"Timestamp: " << time(NULL) << crlf;
745 ss <<
"Stripe Index: 0" << crlf;
746 ss <<
"Stripe Bytes Transferred: " << bytes_transferred << crlf;
747 ss <<
"Total Stripe Count: 1" << crlf;
751 std::stringstream ss2;
752 for (std::vector<State*>::const_iterator iter = state.begin();
753 iter != state.end(); iter++)
755 std::string desc = (*iter)->GetConnectionDescription();
757 ss2 << (first ?
"" :
",") << desc;
762 ss <<
"RemoteConnections: " << ss2.str() << crlf;
764 rec.bytes_transferred = bytes_transferred;
767 return req.
ChunkResp(ss.str().c_str(), 0);
774int TPCHandler::RunCurlWithUpdates(
CURL *curl, XrdHttpExtReq &req,
State &state,
778 CURLM *multi_handle = curl_multi_init();
782 "Failed to initialize a libcurl multi-handle");
783 std::stringstream ss;
784 ss <<
"Failed to initialize internal server memory";
785 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
791 mres = curl_multi_add_handle(multi_handle, curl);
794 std::stringstream ss;
795 ss <<
"Failed to add transfer to libcurl multi-handle: HTTP library failure=" << curl_multi_strerror(mres);
796 logTransferEvent(
LogMask::Error, rec,
"CURL_INIT_FAIL", ss.str());
797 curl_multi_cleanup(multi_handle);
798 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
804 curl_multi_cleanup(multi_handle);
806 "Failed to send the initial response to the TPC client");
810 "Initial transfer response sent to the TPC client");
815 int running_handles = 1;
816 time_t last_marker = 0;
818 off_t last_advance_bytes = 0;
819 time_t last_advance_time = time(NULL);
820 time_t transfer_start = last_advance_time;
821 CURLcode res =
static_cast<CURLcode
>(-1);
823 time_t now = time(NULL);
824 time_t next_marker = last_marker + m_marker_period;
825 if (now >= next_marker) {
827 if (bytes_xfer > last_advance_bytes) {
828 last_advance_bytes = bytes_xfer;
829 last_advance_time = now;
831 if (SendPerfMarker(req, rec, state)) {
832 curl_multi_remove_handle(multi_handle, curl);
833 curl_multi_cleanup(multi_handle);
835 "Failed to send a perf marker to the TPC client");
838 int timeout = (transfer_start == last_advance_time) ? m_first_timeout : m_timeout;
839 if (now > last_advance_time + timeout) {
840 const char *log_prefix = rec.log_prefix.c_str();
841 bool tpc_pull = strncmp(
"Pull", log_prefix, 4) == 0;
844 std::stringstream ss;
845 ss <<
"Transfer failed because no bytes have been "
846 << (tpc_pull ?
"received from the source (pull mode) in "
847 :
"transmitted to the destination (push mode) in ") << timeout <<
" seconds.";
849 curl_multi_remove_handle(multi_handle, curl);
850 curl_multi_cleanup(multi_handle);
856 rec.pmarkManager.startTransfer();
857 mres = curl_multi_perform(multi_handle, &running_handles);
858 if (mres == CURLM_CALL_MULTI_PERFORM) {
862 }
else if (mres != CURLM_OK) {
864 }
else if (running_handles == 0) {
868 rec.pmarkManager.beginPMarks();
875 msg = curl_multi_info_read(multi_handle, &msgq);
876 if (msg && (msg->msg == CURLMSG_DONE)) {
877 CURL *easy_handle = msg->easy_handle;
878 res = msg->data.result;
879 curl_multi_remove_handle(multi_handle, easy_handle);
883 int64_t max_sleep_time = next_marker - time(NULL);
884 if (max_sleep_time <= 0) {
888 mres = curl_multi_wait(multi_handle, NULL, 0, max_sleep_time*1000, &fd_count);
889 if (mres != CURLM_OK) {
892 }
while (running_handles);
894 if (mres != CURLM_OK) {
895 std::stringstream ss;
896 ss <<
"Internal libcurl multi-handle error: HTTP library failure=" << curl_multi_strerror(mres);
897 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_CURL_ERROR", ss.str());
899 curl_multi_remove_handle(multi_handle, curl);
900 curl_multi_cleanup(multi_handle);
902 if ((retval = req.
ChunkResp(generateClientErr(ss, rec).c_str(), 0))) {
904 "Failed to send error message to the TPC client");
914 msg = curl_multi_info_read(multi_handle, &msgq);
915 if (msg && (msg->msg == CURLMSG_DONE)) {
916 CURL *easy_handle = msg->easy_handle;
917 res = msg->data.result;
918 curl_multi_remove_handle(multi_handle, easy_handle);
922 if (!state.
GetErrorCode() && res ==
static_cast<CURLcode
>(-1)) {
923 curl_multi_remove_handle(multi_handle, curl);
924 curl_multi_cleanup(multi_handle);
925 std::stringstream ss;
926 ss <<
"Internal state error in libcurl";
927 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_CURL_ERROR", ss.str());
929 if ((retval = req.
ChunkResp(generateClientErr(ss, rec).c_str(), 0))) {
931 "Failed to send error message to the TPC client");
936 curl_multi_cleanup(multi_handle);
960 std::string finalizeErrorMsg, finalizeErrorSuffix;
962 std::stringstream ss2;
964 ?
"Failed to flush the file to the local filesystem."
965 :
"Failed to finalize and close file handle.");
968 std::replace(err.begin(), err.end(),
'\n',
' ');
971 finalizeErrorMsg = ss2.str();
972 logTransferEvent(
LogMask::Error, rec,
"CLOSE_FAIL", finalizeErrorMsg);
973 finalizeErrorSuffix =
"; " + finalizeErrorMsg;
977 std::stringstream ss;
978 bool success =
false;
981 std::stringstream ss2;
982 ss2 <<
"Remote side failed with status code " << state.
GetStatusCode();
984 std::replace(err.begin(), err.end(),
'\n',
' ');
985 ss2 <<
"; error message: \"" << err <<
"\"";
987 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_FAIL", ss2.str());
988 ss2 << finalizeErrorSuffix;
989 ss << generateClientErr(ss2, rec);
993 std::stringstream ss2;
994 ss2 << transferErrorMsg;
995 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_FAIL", ss2.str());
996 ss2 << finalizeErrorSuffix;
997 ss << generateClientErr(ss2, rec);
998 }
else if (transferErrorCode) {
999 if (transferErrorMsg.empty()) {transferErrorMsg =
"(no error message provided)";}
1000 else {std::replace(transferErrorMsg.begin(), transferErrorMsg.end(),
'\n',
' ');}
1001 std::stringstream ss2;
1002 ss2 <<
"Error when interacting with local filesystem: " << transferErrorMsg;
1003 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_FAIL", ss2.str());
1004 ss2 << finalizeErrorSuffix;
1005 ss << generateClientErr(ss2, rec);
1006 }
else if (res != CURLE_OK) {
1007 std::stringstream ss2;
1008 ss2 <<
"Internal transfer failure";
1009 std::stringstream ss3;
1010 ss3 << ss2.str() <<
": " << curl_easy_strerror(res);
1011 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_FAIL", ss3.str());
1012 ss2 << finalizeErrorSuffix;
1013 ss << generateClientErr(ss2, rec, res);
1014 }
else if (!finalizeErrorMsg.empty()) {
1016 std::stringstream ss2;
1017 ss2 << finalizeErrorMsg;
1018 ss << generateClientErr(ss2, rec);
1020 ss <<
"success: Created";
1024 if ((retval = req.
ChunkResp(ss.str().c_str(), 0))) {
1026 "Failed to send last update to remote client");
1028 }
else if (success) {
1039int TPCHandler::ProcessPushReq(
const std::string & resource, XrdHttpExtReq &req) {
1041 rec.allow_local = m_allow_local;
1042 rec.allow_private = m_allow_private;
1043 rec.log_prefix =
"PushRequest";
1045 rec.remote = resource;
1049 if (name) rec.name = name;
1050 logTransferEvent(
LogMask::Info, rec,
"PUSH_START",
"Starting a push request");
1053 auto curl = curlPtr.get();
1055 std::stringstream ss;
1056 ss <<
"Failed to initialize internal transfer resources";
1059 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1061 ConfigureCurlLowSpeed(curl);
1062 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
1063 curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
1064 curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (
long) CURL_HTTP_VERSION_1_1);
1065#if CURL_AT_LEAST_VERSION(7, 85, 0)
1066 curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR,
"https,http");
1067 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR,
"https,http");
1069 long protocols = CURLPROTO_HTTP | CURLPROTO_HTTPS;
1070 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
1071 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
1073 curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, opensocket_callback);
1074 curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, &rec);
1075 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETFUNCTION, closesocket_callback);
1076 curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
1077 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETDATA, &rec);
1078 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, CONNECT_TIMEOUT);
1081 std::string redirect_resource = req.
resource;
1082 if (query_header != req.
headers.end()) {
1083 redirect_resource = query_header->second;
1087 uint64_t file_monid =
AtomicInc(m_monid);
1089 std::unique_ptr<XrdSfsFile> fh(m_sfs->newFile(name, file_monid));
1092 std::stringstream ss;
1093 ss <<
"Failed to initialize internal transfer file handle";
1096 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1098 std::string full_url = prepareURL(req);
1100 std::string authz = GetAuthz(req);
1102 int open_results = OpenWaitStall(*fh, full_url,
SFS_O_RDONLY, 0644,
1105 int result = RedirectTransfer(curl, redirect_resource, req, fh->
error, rec);
1107 }
else if (
SFS_OK != open_results) {
1109 std::stringstream ss;
1111 if (msg == NULL) ss <<
"Failed to open local resource";
1115 int resp_result = req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1119 if (!ConfigureCurlCA(curl, rec)) {
1120 std::stringstream ss;
1121 ss <<
"Failed to configure the certificate authorities for the transfer";
1124 int resp_result = req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1128 curl_easy_setopt(curl, CURLOPT_URL, resource.c_str());
1130 Stream stream(std::move(fh), 0, 0, m_log);
1134 return RunCurlWithUpdates(curl, req, state, rec);
1141int TPCHandler::ProcessPullReq(
const std::string &resource, XrdHttpExtReq &req) {
1143 rec.allow_local = m_allow_local;
1144 rec.allow_private = m_allow_private;
1145 rec.log_prefix =
"PullRequest";
1147 rec.remote = resource;
1151 if (name) rec.name = name;
1152 logTransferEvent(
LogMask::Info, rec,
"PULL_START",
"Starting a pull request");
1155 auto curl = curlPtr.get();
1157 std::stringstream ss;
1158 ss <<
"Failed to initialize internal transfer resources";
1161 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1163 ConfigureCurlLowSpeed(curl);
1172 if (m_fixed_route) {
1177 int sockFD = addrInfo ? addrInfo->
SockFD() : -1;
1182 logTransferEvent(
LogMask::Error, rec,
"FIXED_ROUTE_ERR",
"Failed to determine local address of incoming fixed route request");
1185 curl_easy_setopt(curl, CURLOPT_INTERFACE, ip);
1188 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
1189 curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
1190 curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (
long) CURL_HTTP_VERSION_1_1);
1191#if CURL_AT_LEAST_VERSION(7, 85, 0)
1192 curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR,
"https,http");
1193 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR,
"https,http");
1195 long protocols = CURLPROTO_HTTP | CURLPROTO_HTTPS;
1196 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
1197 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
1199 curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, opensocket_callback);
1200 curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, &rec);
1201 curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
1202 curl_easy_setopt(curl, CURLOPT_SOCKOPTDATA , &rec);
1203 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETFUNCTION, closesocket_callback);
1204 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETDATA, &rec);
1205 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, CONNECT_TIMEOUT);
1206 std::unique_ptr<XrdSfsFile> fh(m_sfs->newFile(name, m_monid++));
1208 std::stringstream ss;
1209 ss <<
"Failed to initialize internal transfer file handle";
1212 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1215 std::string redirect_resource = req.
resource;
1216 if (query_header != req.
headers.end()) {
1217 redirect_resource = query_header->second;
1221 if ((overwrite_header == req.
headers.end()) || (overwrite_header->second ==
"T")) {
1227 if (streams_header != req.
headers.end()) {
1228 int stream_req = -1;
1230 stream_req = std::stol(streams_header->second);
1233 if (stream_req < 0 || stream_req > 100) {
1234 std::stringstream ss;
1235 ss <<
"Invalid request for number of streams";
1237 logTransferEvent(
LogMask::Info, rec,
"INVALID_REQUEST", ss.str());
1238 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1240 streams = stream_req == 0 ? 1 : stream_req;
1243 rec.streams = streams;
1244 std::string full_url = prepareURL(req);
1245 std::string authz = GetAuthz(req);
1246 curl_easy_setopt(curl, CURLOPT_URL, resource.c_str());
1247 if (!ConfigureCurlCA(curl, rec)) {
1248 std::stringstream ss;
1249 ss <<
"Failed to configure the certificate authorities for the transfer";
1252 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1254 uint64_t sourceFileContentLength = 0;
1258 bool success =
false;
1259 bool mismatchDigests =
false;
1260 std::map<std::string,std::string> sourceFileReprDigest;
1261 GetRemoteFileInfoTPCPull(curl, req, sourceFileContentLength, sourceFileReprDigest, success, rec);
1265 full_url +=
"&oss.asize=" + std::to_string(sourceFileContentLength);
1266 mismatchDigests = mismatchReprDigest(sourceFileReprDigest,req,rec);
1268 if(!success || mismatchDigests) {
1275 int open_result = OpenWaitStall(*fh, full_url, mode|
SFS_O_WRONLY,
1279 int result = RedirectTransfer(curl, redirect_resource, req, fh->
error, rec);
1281 }
else if (
SFS_OK != open_result) {
1283 std::stringstream ss;
1285 if ((msg == NULL) || (*msg ==
'\0')) ss <<
"Failed to open local resource";
1290 generateClientErr(ss, rec).c_str(), 0);
1294 Stream stream(std::move(fh), streams * m_pipelining_multiplier, streams > 1 ? m_block_size : m_small_block_size, m_log);
1300 return RunCurlWithStreams(req, state, streams, rec);
1302 return RunCurlWithUpdates(curl, req, state, rec);
1310void TPCHandler::logTransferEvent(
LogMask mask,
const TPCLogRecord &rec,
1311 const std::string &event,
const std::string &message)
1313 if (!(m_log.getMsgMask() & mask)) {
return;}
1315 std::stringstream ss;
1316 ss <<
"event=" <<
event <<
", local=" << rec.local <<
", remote=" << rec.remote;
1317 if (rec.name.empty())
1318 ss <<
", user=(anonymous)";
1320 ss <<
", user=" << rec.name;
1321 if (rec.streams != 1)
1322 ss <<
", streams=" << rec.streams;
1323 if (rec.bytes_transferred >= 0)
1324 ss <<
", bytes_transferred=" << rec.bytes_transferred;
1325 if (rec.status >= 0)
1326 ss <<
", status=" << rec.status;
1327 if (rec.tpc_status >= 0)
1328 ss <<
", tpc_status=" << rec.tpc_status;
1329 if (!message.empty())
1330 ss <<
"; " << message;
1331 m_log.Log(mask, rec.log_prefix.c_str(), ss.str().c_str());
1334std::string TPCHandler::generateClientErr(std::stringstream &err_ss,
const TPCLogRecord &rec, CURLcode cCode) {
1335 std::stringstream ssret;
1336 ssret <<
"failure: " << err_ss.str() <<
", local=" << rec.local <<
", remote=" << rec.remote;
1337 if(cCode != CURLcode::CURLE_OK) {
1338 ssret <<
", HTTP library failure=" << curl_easy_strerror(cCode);
1349 if (curl_global_init(CURL_GLOBAL_DEFAULT)) {
1350 log->
Emsg(
"TPCInitialize",
"libcurl failed to initialize");
1356 log->
Emsg(
"TPCInitialize",
"TPC handler requires a config filename in order to load");
1360 log->
Emsg(
"TPCInitialize",
"Will load configuration for the TPC handler from", config);
1362 }
catch (std::runtime_error &re) {
1363 log->
Emsg(
"TPCInitialize",
"Encountered a runtime failure when loading ", re.what());
XrdHttpExtHandler * XrdHttpGetExtHandler(XrdHttpExtHandlerArgs)
XrdVERSIONINFO(XrdHttpGetExtHandler, HttpTPC)
static std::string PrepareURL(const std::string &url)
std::string encode_xrootd_opaque_to_uri(CURL *curl, const std::string &opaque)
static bool IsAllowedScheme(const std::string &url)
int mapErrNoToHttp(int errNo)
std::string httpStatusToString(int status)
Utility functions for XrdHTTP.
std::string encode_str(const std::string &str)
void splitHostCgi(std::string_view target, std::string &host, std::string &cgi)
void getline(uchar *buff, int blen)
const std::map< std::string, std::string > & GetReprDigest() const
int GetFinalizeErrorCode() const
int GetStatusCode() const
off_t BytesTransferred() const
void SetErrorMessage(const std::string &error_msg)
std::string GetFinalizeErrorMessage() const
std::string GetErrorMessage() const
std::string GetConnectionDescription()
void SetupHeaders(XrdHttpExtReq &req)
void SetContentLength(const off_t content_length)
off_t GetContentLength() const
void SetErrorCode(int error_code)
void SetupHeadersForHEAD(XrdHttpExtReq &req)
TPCHandler(XrdSysError *log, const char *config, XrdOucEnv *myEnv)
virtual int ProcessReq(XrdHttpExtReq &req)
virtual bool MatchesPath(const char *verb, const char *path)
Tells if the incoming path is recognized as one of the paths that have to be processed.
int ChunkResp(const char *body, long long bodylen)
Send a (potentially partial) body in a chunked response; invoking with NULL body.
void GetClientID(std::string &clid)
std::map< std::string, std::string > & headers
std::map< std::string, std::string > mReprDigest
Repr-Digest map where the key is the digest name and the value is the base64 encoded digest value.
int StartChunkedResp(int code, const char *desc, const char *header_to_add)
Starts a chunked response; body of request is sent over multiple parts using the SendChunkResp.
const XrdSecEntity & GetSecEntity() const
int SendSimpleResp(int code, const char *desc, const char *header_to_add, const char *body, long long bodylen)
Sends a basic response. If the length is < 0 then it is calculated internally.
static std::string prepareOpenURL(PrepareOpenURLParams ¶ms)
static int GetSokInfo(int fd, char *theAddr, int theALen, char &theType)
void * GetPtr(const char *varname)
const char * getErrText()
void setUCap(int ucval)
Set user capabilties.
static std::map< std::string, T >::const_iterator caseInsensitiveFind(const std::map< std::string, T > &m, const std::string &lowerCaseSearchKey)
XrdNetAddrInfo * addrInfo
Entity's connection details.
char * name
Entity's name.
virtual int open(const char *fileName, XrdSfsFileOpenMode openMode, mode_t createMode, const XrdSecEntity *client=0, const char *opaque=0)=0
int Emsg(const char *esfx, int ecode, const char *text1, const char *text2=0)
XrdSysLogger * logger(XrdSysLogger *lp=0)
static Outcome Redirect(const char *trg, int &port, XrdNetAddrInfo &clientAddr, std::string &outTarget, std::string &errMsg)
std::unique_ptr< CURL, CurlDeleter > ManagedCurlHandle
void operator()(CURL *curl)
static const int uIPv64
ucap: Supports only IPv4 info