9#include "XrdVersion.hh"
36uint64_t TPCHandler::m_monid{0};
37int TPCHandler::m_marker_period = 5;
38size_t TPCHandler::m_block_size = 16*1024*1024;
39size_t TPCHandler::m_small_block_size = 1*1024*1024;
41bool TPCHandler::allowMissingCRL =
false;
49TPCHandler::TPCLogRecord::~TPCLogRecord()
56 monInfo.
clID = clID.c_str();
58 gettimeofday(&monInfo.
endT, 0);
61 {monInfo.
dstURL = local.c_str();
62 monInfo.
srcURL = remote.c_str();
64 monInfo.
dstURL = remote.c_str();
65 monInfo.
srcURL = local.c_str();
69 if (!status) monInfo.
endRC = 0;
70 else if (tpc_status > 0) monInfo.
endRC = tpc_status;
71 else monInfo.
endRC = 1;
72 monInfo.
strm =
static_cast<unsigned char>(streams);
73 monInfo.
fSize = (bytes_transferred < 0 ? 0 : bytes_transferred);
76 tpcMonitor->Report(monInfo);
86 if (curl) curl_easy_cleanup(curl);
101int TPCHandler::sockopt_callback(
void *clientp, curl_socket_t curlfd, curlsocktype purpose) {
102 TPCLogRecord * rec = (TPCLogRecord *)clientp;
103 if (purpose == CURLSOCKTYPE_IPCXN && rec && rec->pmarkManager.isEnabled()) {
106 return CURL_SOCKOPT_ALREADY_CONNECTED;
108 return CURL_SOCKOPT_OK;
120int TPCHandler::opensocket_callback(
void *clientp,
121 curlsocktype purpose,
122 struct curl_sockaddr *aInfo)
126 if (purpose != CURLSOCKTYPE_IPCXN)
127 return CURL_SOCKET_BAD;
130 return CURL_SOCKET_BAD;
133 int fd = XrdSysFD_Socket(aInfo->family, aInfo->socktype, aInfo->protocol);
136 return CURL_SOCKET_BAD;
142 XrdNetAddr thePeer(&(aInfo->addr));
143 TPCLogRecord *rec =
static_cast<TPCLogRecord*
>(clientp);
146 if ((!rec->allow_private && thePeer.isPrivate()) || (!rec->allow_local && thePeer.isLocal())) {
147 rec->tpc_status = 403;
148 rec->m_log->Emsg(rec->log_prefix.c_str(),
149 "Connection to local/private address is forbidden");
151 return CURL_SOCKET_BAD;
156 std::stringstream connectErrMsg;
157 if(!rec->pmarkManager.connect(fd, &(aInfo->addr), aInfo->addrlen, CONNECT_TIMEOUT, connectErrMsg)) {
158 rec->m_log->Emsg(rec->log_prefix.c_str(),
"Unable to connect socket: ", connectErrMsg.str().c_str());
160 return CURL_SOCKET_BAD;
166int TPCHandler::closesocket_callback(
void *clientp, curl_socket_t fd) {
167 TPCLogRecord * rec = (TPCLogRecord *)clientp;
172 rec->pmarkManager.endPmark(fd);
187int TPCHandler::ssl_ctx_callback(
CURL *curl,
void *ssl_ctx,
void *clientp) {
188 TPCLogRecord * rec = (TPCLogRecord *)clientp;
189 SSL_CTX* ctx =
static_cast<SSL_CTX*
>(ssl_ctx);
191 if (rec && rec->ca_store) {
195 SSL_CTX_set1_cert_store(ctx, rec->ca_store.get());
197 if (allowMissingCRL) {
201 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_callback);
206int TPCHandler::verify_callback(
int preverify_ok, X509_STORE_CTX* ctx) {
207 if (preverify_ok == 1)
return 1;
209 int err = X509_STORE_CTX_get_error(ctx);
211 if (err == X509_V_ERR_UNABLE_TO_GET_CRL) {
212 X509_STORE_CTX_set_error(ctx, X509_V_OK);
224std::string TPCHandler::prepareURL(XrdHttpExtReq &req) {
239 std::stringstream parser(opaque);
240 std::string sequence;
241 std::stringstream output;
243 while (
getline(parser, sequence,
'&')) {
244 if (sequence.empty()) {
continue;}
245 size_t equal_pos = sequence.find(
'=');
247 if (equal_pos != std::string::npos)
248 val = curl_easy_escape(curl, sequence.c_str() + equal_pos + 1, sequence.size() - equal_pos - 1);
250 if (!val && equal_pos != std::string::npos) {
continue;}
252 if (!first) output <<
"&";
254 output << sequence.substr(0, equal_pos);
256 output <<
"=" << val;
268TPCHandler::ConfigureCurlCA(
CURL *curl, TPCLogRecord &rec)
278 if (m_ca_file && m_sslctx_supported && m_cafile.empty()) {
279 rec.ca_store = m_ca_file->CAStore();
281 m_log.Log(
Error,
"TpcHandler",
"No CA store is available; refusing to "
282 "fall back to libcurl's default CA bundle");
287 curl_easy_setopt(curl, CURLOPT_CAINFO,
static_cast<char *
>(
nullptr));
288 curl_easy_setopt(curl, CURLOPT_CAPATH,
static_cast<char *
>(
nullptr));
289 curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, ssl_ctx_callback);
290 curl_easy_setopt(curl, CURLOPT_SSL_CTX_DATA, &rec);
294 auto ca_filename = m_ca_file ? m_ca_file->CAFilename() :
"";
295 auto crl_filename = m_ca_file ? m_ca_file->CRLFilename() :
"";
296 if (!ca_filename.empty() && !crl_filename.empty()) {
297 curl_easy_setopt(curl, CURLOPT_CAINFO, ca_filename.c_str());
301 std::ifstream in(crl_filename, std::ifstream::ate | std::ifstream::binary);
302 if(in.tellg() > 0 && m_ca_file->atLeastOneValidCRLFound()){
303 curl_easy_setopt(curl, CURLOPT_CRLFILE, crl_filename.c_str());
304 if (allowMissingCRL) {
306 curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, ssl_ctx_callback);
309 std::ostringstream oss;
310 oss <<
"No valid CRL file has been found in the file " << crl_filename <<
". Disabling CRL checking.";
311 m_log.Log(
Warning,
"TpcHandler",oss.str().c_str());
314 else if (!m_cadir.empty()) {
315 curl_easy_setopt(curl, CURLOPT_CAPATH, m_cadir.c_str());
317 if (!m_cafile.empty()) {
318 curl_easy_setopt(curl, CURLOPT_CAINFO, m_cafile.c_str());
324TPCHandler::ConfigureCurlLowSpeed(
CURL *curl)
328 curl_version_info_data *curl_ver = curl_version_info(CURLVERSION_NOW);
329 if (m_low_speed_limit > 0 && curl_ver && curl_ver->age > 0 &&
330 curl_ver->version_num >= 0x072600) {
331 curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, m_low_speed_time);
332 curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, m_low_speed_limit);
338 return !strcmp(verb,
"COPY") || !strcmp(verb,
"OPTIONS");
347 const std::string replace_schemes[] = {
"davs://",
"s3://",
"s3s://" };
349 for (
const auto& s : replace_schemes)
350 if (url.compare(0, s.size(), s) == 0)
351 return "https://" + url.substr(s.size());
358 const std::string allowed_schemes[] = {
"https://",
"http://" };
360 for (
const auto& s : allowed_schemes)
361 if (url.compare(0, s.size(), s) == 0)
372 if (req.
verb ==
"OPTIONS") {
373 return ProcessOptionsReq(req);
376 if (header != req.
headers.end()) {
377 if (header->second !=
"none") {
378 m_log.Emsg(
"ProcessReq",
"COPY requested an unsupported credential type: ", header->second.c_str());
379 return req.
SendSimpleResp(400, NULL, NULL,
"COPY requestd an unsupported Credential type", 0);
383 if (header != req.
headers.end()) {
386 const char *error_src =
"COPY rejected: disallowed scheme in source URL";
387 m_log.Emsg(
"ProcessReq", error_src, src.c_str());
390 return ProcessPullReq(src, req);
393 if (header != req.
headers.end()) {
394 const std::string& dst = header->second;
396 const char *error_dst =
"COPY rejected: disallowed scheme in destination URL";
397 m_log.Emsg(
"ProcessReq", error_dst, dst.c_str());
400 return ProcessPushReq(header->second, req);
402 m_log.Emsg(
"ProcessReq",
"COPY verb requested but no source or destination specified.");
403 return req.
SendSimpleResp(400, NULL, NULL,
"No Source or Destination specified", 0);
419 m_allow_local(false),
420 m_allow_private(true),
422 m_fixed_route(false),
423 m_low_speed_limit(10*1024),
424 m_low_speed_time(2*60),
426 m_first_timeout(120),
427 m_log(log->logger(),
"TPC_"),
430 if (!Configure(config, myEnv)) {
431 throw std::runtime_error(
"Failed to configure the HTTP third-party-copy handler.");
449 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);
459 if (authz_header != req.
headers.end()) {
460 std::stringstream ss;
461 ss <<
"authz=" <<
encode_str(authz_header->second);
471int TPCHandler::RedirectTransfer(
CURL *curl,
const std::string &redirect_resource,
472 XrdHttpExtReq &req, XrdOucErrInfo &error, TPCLogRecord &rec)
476 if ((ptr == NULL) || (*ptr ==
'\0') || (port == 0)) {
478 std::stringstream ss;
479 ss <<
"Internal error: redirect without hostname";
480 logTransferEvent(
LogMask::Error, rec,
"REDIRECT_INTERNAL_ERROR", ss.str());
481 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
485 std::string rdr_info = ptr;
486 std::string host, opaque;
487 size_t pos = rdr_info.find(
'?');
488 host = rdr_info.substr(0, pos);
490 if (pos != std::string::npos) {
491 opaque = rdr_info.substr(pos + 1);
494 std::stringstream ss;
495 ss <<
"Location: http" << (m_desthttps ?
"s" :
"") <<
"://" << host <<
":" << port <<
"/" << redirect_resource;
497 if (!opaque.empty()) {
503 return req.
SendSimpleResp(rec.status, NULL,
const_cast<char *
>(ss.str().c_str()),
511int TPCHandler::OpenWaitStall(XrdSfsFile &fh,
const std::string &resource,
512 int mode,
int openMode,
const XrdSecEntity &sec,
513 const std::string &authz)
520 size_t pos = resource.find(
'?');
522 std::string path = resource.substr(0, pos);
524 if (pos != std::string::npos) {
525 opaque = resource.substr(pos + 1);
530 opaque += (opaque.empty() ?
"" :
"&");
533 open_result = fh.
open(path.c_str(), mode, openMode, &sec, opaque.c_str());
537 if (open_result ==
SFS_STARTED) {secs_to_stall = secs_to_stall/2 + 5;}
538 std::this_thread::sleep_for (std::chrono::seconds(secs_to_stall));
554int TPCHandler::DetermineXferSize(
CURL *curl, XrdHttpExtReq &req,
State &state,
555 bool &success, TPCLogRecord &rec,
bool shouldReturnErrorToClient) {
557 curl_easy_setopt(curl, CURLOPT_NOBODY, 1);
559 curl_easy_setopt(curl, CURLOPT_TIMEOUT, CONNECT_TIMEOUT);
561 res = curl_easy_perform(curl);
564 curl_easy_setopt(curl, CURLOPT_NOBODY, 0);
566 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 0L);
567 curl_easy_setopt(curl, CURLOPT_FAILONERROR,
true);
569 std::stringstream ss;
572 res = CURLE_HTTP_RETURNED_ERROR;
574 if (res != CURLE_OK) {
575 ss << curl_easy_strerror(res);
577 case CURLE_HTTP_RETURNED_ERROR:
579 ss <<
": remote host returned '" << rec.tpc_status <<
" "
582 case CURLE_COULDNT_CONNECT:
583 switch (rec.tpc_status) {
585 ss <<
": connection to local/private addresses is forbidden";
588 ss <<
": internal server failure";
589 rec.tpc_status = 500;
593 rec.tpc_status = 500;
598 if (rec.tpc_status >= 400) {
600 return shouldReturnErrorToClient ? req.
SendSimpleResp(rec.tpc_status, NULL, NULL, generateClientErr(ss, rec, res).c_str(), 0) : -1;
604 ss <<
"Successfully determined remote size for pull request: " << state.
GetContentLength();
609int TPCHandler::GetContentLengthTPCPull(
CURL *curl, XrdHttpExtReq &req, uint64_t &contentLength,
bool & success, TPCLogRecord &rec) {
616 if ((result = DetermineXferSize(curl, req, state, success, rec)) || !success) {
627int TPCHandler::SendPerfMarker(XrdHttpExtReq &req, TPCLogRecord &rec, TPC::State &state) {
628 std::stringstream ss;
629 const std::string crlf =
"\n";
630 ss <<
"Perf Marker" << crlf;
631 ss <<
"Timestamp: " << time(NULL) << crlf;
632 ss <<
"Stripe Index: 0" << crlf;
634 ss <<
"Total Stripe Count: 1" << crlf;
639 ss <<
"RemoteConnections: " << desc << crlf;
644 return req.
ChunkResp(ss.str().c_str(), 0);
651int TPCHandler::SendPerfMarker(XrdHttpExtReq &req, TPCLogRecord &rec, std::vector<State*> &state,
652 off_t bytes_transferred)
666 std::stringstream ss;
667 const std::string crlf =
"\n";
668 ss <<
"Perf Marker" << crlf;
669 ss <<
"Timestamp: " << time(NULL) << crlf;
670 ss <<
"Stripe Index: 0" << crlf;
671 ss <<
"Stripe Bytes Transferred: " << bytes_transferred << crlf;
672 ss <<
"Total Stripe Count: 1" << crlf;
676 std::stringstream ss2;
677 for (std::vector<State*>::const_iterator iter = state.begin();
678 iter != state.end(); iter++)
680 std::string desc = (*iter)->GetConnectionDescription();
682 ss2 << (first ?
"" :
",") << desc;
687 ss <<
"RemoteConnections: " << ss2.str() << crlf;
689 rec.bytes_transferred = bytes_transferred;
692 return req.
ChunkResp(ss.str().c_str(), 0);
699int TPCHandler::RunCurlWithUpdates(
CURL *curl, XrdHttpExtReq &req,
State &state,
703 CURLM *multi_handle = curl_multi_init();
707 "Failed to initialize a libcurl multi-handle");
708 std::stringstream ss;
709 ss <<
"Failed to initialize internal server memory";
710 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
716 mres = curl_multi_add_handle(multi_handle, curl);
719 std::stringstream ss;
720 ss <<
"Failed to add transfer to libcurl multi-handle: HTTP library failure=" << curl_multi_strerror(mres);
721 logTransferEvent(
LogMask::Error, rec,
"CURL_INIT_FAIL", ss.str());
722 curl_multi_cleanup(multi_handle);
723 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
727 int retval = req.
StartChunkedResp(201,
"Created",
"Content-Type: text/plain");
729 curl_multi_cleanup(multi_handle);
731 "Failed to send the initial response to the TPC client");
735 "Initial transfer response sent to the TPC client");
740 int running_handles = 1;
741 time_t last_marker = 0;
743 off_t last_advance_bytes = 0;
744 time_t last_advance_time = time(NULL);
745 time_t transfer_start = last_advance_time;
746 CURLcode res =
static_cast<CURLcode
>(-1);
748 time_t now = time(NULL);
749 time_t next_marker = last_marker + m_marker_period;
750 if (now >= next_marker) {
752 if (bytes_xfer > last_advance_bytes) {
753 last_advance_bytes = bytes_xfer;
754 last_advance_time = now;
756 if (SendPerfMarker(req, rec, state)) {
757 curl_multi_remove_handle(multi_handle, curl);
758 curl_multi_cleanup(multi_handle);
760 "Failed to send a perf marker to the TPC client");
763 int timeout = (transfer_start == last_advance_time) ? m_first_timeout : m_timeout;
764 if (now > last_advance_time + timeout) {
765 const char *log_prefix = rec.log_prefix.c_str();
766 bool tpc_pull = strncmp(
"Pull", log_prefix, 4) == 0;
769 std::stringstream ss;
770 ss <<
"Transfer failed because no bytes have been "
771 << (tpc_pull ?
"received from the source (pull mode) in "
772 :
"transmitted to the destination (push mode) in ") << timeout <<
" seconds.";
774 curl_multi_remove_handle(multi_handle, curl);
775 curl_multi_cleanup(multi_handle);
781 rec.pmarkManager.startTransfer();
782 mres = curl_multi_perform(multi_handle, &running_handles);
783 if (mres == CURLM_CALL_MULTI_PERFORM) {
787 }
else if (mres != CURLM_OK) {
789 }
else if (running_handles == 0) {
793 rec.pmarkManager.beginPMarks();
800 msg = curl_multi_info_read(multi_handle, &msgq);
801 if (msg && (msg->msg == CURLMSG_DONE)) {
802 CURL *easy_handle = msg->easy_handle;
803 res = msg->data.result;
804 curl_multi_remove_handle(multi_handle, easy_handle);
808 int64_t max_sleep_time = next_marker - time(NULL);
809 if (max_sleep_time <= 0) {
813 mres = curl_multi_wait(multi_handle, NULL, 0, max_sleep_time*1000, &fd_count);
814 if (mres != CURLM_OK) {
817 }
while (running_handles);
819 if (mres != CURLM_OK) {
820 std::stringstream ss;
821 ss <<
"Internal libcurl multi-handle error: HTTP library failure=" << curl_multi_strerror(mres);
822 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_CURL_ERROR", ss.str());
824 curl_multi_remove_handle(multi_handle, curl);
825 curl_multi_cleanup(multi_handle);
827 if ((retval = req.
ChunkResp(generateClientErr(ss, rec).c_str(), 0))) {
829 "Failed to send error message to the TPC client");
839 msg = curl_multi_info_read(multi_handle, &msgq);
840 if (msg && (msg->msg == CURLMSG_DONE)) {
841 CURL *easy_handle = msg->easy_handle;
842 res = msg->data.result;
843 curl_multi_remove_handle(multi_handle, easy_handle);
847 if (!state.
GetErrorCode() && res ==
static_cast<CURLcode
>(-1)) {
848 curl_multi_remove_handle(multi_handle, curl);
849 curl_multi_cleanup(multi_handle);
850 std::stringstream ss;
851 ss <<
"Internal state error in libcurl";
852 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_CURL_ERROR", ss.str());
854 if ((retval = req.
ChunkResp(generateClientErr(ss, rec).c_str(), 0))) {
856 "Failed to send error message to the TPC client");
861 curl_multi_cleanup(multi_handle);
885 std::string finalizeErrorMsg, finalizeErrorSuffix;
887 std::stringstream ss2;
889 ?
"Failed to flush the file to the local filesystem."
890 :
"Failed to finalize and close file handle.");
893 std::replace(err.begin(), err.end(),
'\n',
' ');
896 finalizeErrorMsg = ss2.str();
897 logTransferEvent(
LogMask::Error, rec,
"CLOSE_FAIL", finalizeErrorMsg);
898 finalizeErrorSuffix =
"; " + finalizeErrorMsg;
902 std::stringstream ss;
903 bool success =
false;
906 std::stringstream ss2;
907 ss2 <<
"Remote side failed with status code " << state.
GetStatusCode();
909 std::replace(err.begin(), err.end(),
'\n',
' ');
910 ss2 <<
"; error message: \"" << err <<
"\"";
912 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_FAIL", ss2.str());
913 ss2 << finalizeErrorSuffix;
914 ss << generateClientErr(ss2, rec);
918 std::stringstream ss2;
919 ss2 << transferErrorMsg;
920 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_FAIL", ss2.str());
921 ss2 << finalizeErrorSuffix;
922 ss << generateClientErr(ss2, rec);
923 }
else if (transferErrorCode) {
924 if (transferErrorMsg.empty()) {transferErrorMsg =
"(no error message provided)";}
925 else {std::replace(transferErrorMsg.begin(), transferErrorMsg.end(),
'\n',
' ');}
926 std::stringstream ss2;
927 ss2 <<
"Error when interacting with local filesystem: " << transferErrorMsg;
928 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_FAIL", ss2.str());
929 ss2 << finalizeErrorSuffix;
930 ss << generateClientErr(ss2, rec);
931 }
else if (res != CURLE_OK) {
932 std::stringstream ss2;
933 ss2 <<
"Internal transfer failure";
934 std::stringstream ss3;
935 ss3 << ss2.str() <<
": " << curl_easy_strerror(res);
936 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_FAIL", ss3.str());
937 ss2 << finalizeErrorSuffix;
938 ss << generateClientErr(ss2, rec, res);
939 }
else if (!finalizeErrorMsg.empty()) {
941 std::stringstream ss2;
942 ss2 << finalizeErrorMsg;
943 ss << generateClientErr(ss2, rec);
945 ss <<
"success: Created";
949 if ((retval = req.
ChunkResp(ss.str().c_str(), 0))) {
951 "Failed to send last update to remote client");
953 }
else if (success) {
964int TPCHandler::ProcessPushReq(
const std::string & resource, XrdHttpExtReq &req) {
966 rec.allow_local = m_allow_local;
967 rec.allow_private = m_allow_private;
968 rec.log_prefix =
"PushRequest";
970 rec.remote = resource;
974 if (name) rec.name = name;
975 logTransferEvent(
LogMask::Info, rec,
"PUSH_START",
"Starting a push request");
978 auto curl = curlPtr.get();
980 std::stringstream ss;
981 ss <<
"Failed to initialize internal transfer resources";
984 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
986 ConfigureCurlLowSpeed(curl);
987 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
988 curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
989 curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (
long) CURL_HTTP_VERSION_1_1);
990#if CURL_AT_LEAST_VERSION(7, 85, 0)
991 curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR,
"https,http");
992 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR,
"https,http");
994 long protocols = CURLPROTO_HTTP | CURLPROTO_HTTPS;
995 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
996 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
998 curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, opensocket_callback);
999 curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, &rec);
1000 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETFUNCTION, closesocket_callback);
1001 curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
1002 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETDATA, &rec);
1003 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, CONNECT_TIMEOUT);
1006 std::string redirect_resource = req.
resource;
1007 if (query_header != req.
headers.end()) {
1008 redirect_resource = query_header->second;
1012 uint64_t file_monid =
AtomicInc(m_monid);
1014 std::unique_ptr<XrdSfsFile> fh(m_sfs->newFile(name, file_monid));
1017 std::stringstream ss;
1018 ss <<
"Failed to initialize internal transfer file handle";
1021 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1023 std::string full_url = prepareURL(req);
1025 std::string authz = GetAuthz(req);
1027 int open_results = OpenWaitStall(*fh, full_url,
SFS_O_RDONLY, 0644,
1030 int result = RedirectTransfer(curl, redirect_resource, req, fh->
error, rec);
1032 }
else if (
SFS_OK != open_results) {
1034 std::stringstream ss;
1036 if (msg == NULL) ss <<
"Failed to open local resource";
1040 int resp_result = req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1044 if (!ConfigureCurlCA(curl, rec)) {
1045 std::stringstream ss;
1046 ss <<
"Failed to configure the certificate authorities for the transfer";
1049 int resp_result = req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1053 curl_easy_setopt(curl, CURLOPT_URL, resource.c_str());
1055 Stream stream(std::move(fh), 0, 0, m_log);
1059 return RunCurlWithUpdates(curl, req, state, rec);
1066int TPCHandler::ProcessPullReq(
const std::string &resource, XrdHttpExtReq &req) {
1068 rec.allow_local = m_allow_local;
1069 rec.allow_private = m_allow_private;
1070 rec.log_prefix =
"PullRequest";
1072 rec.remote = resource;
1076 if (name) rec.name = name;
1077 logTransferEvent(
LogMask::Info, rec,
"PULL_START",
"Starting a pull request");
1080 auto curl = curlPtr.get();
1082 std::stringstream ss;
1083 ss <<
"Failed to initialize internal transfer resources";
1086 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1088 ConfigureCurlLowSpeed(curl);
1097 if (m_fixed_route) {
1102 if (host_header != req.
headers.end()) {
1103 host = host_header->second;
1108 std::vector<XrdNetAddr> addresses;
1111 if (eText || addresses.empty() ||
1113 std::stringstream ss;
1114 ss <<
"Failed to determine host address of incoming request";
1117 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1121 curl_easy_setopt(curl, CURLOPT_INTERFACE, ip);
1123 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
1124 curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
1125 curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (
long) CURL_HTTP_VERSION_1_1);
1126#if CURL_AT_LEAST_VERSION(7, 85, 0)
1127 curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR,
"https,http");
1128 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR,
"https,http");
1130 long protocols = CURLPROTO_HTTP | CURLPROTO_HTTPS;
1131 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
1132 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
1134 curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, opensocket_callback);
1135 curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, &rec);
1136 curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
1137 curl_easy_setopt(curl, CURLOPT_SOCKOPTDATA , &rec);
1138 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETFUNCTION, closesocket_callback);
1139 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETDATA, &rec);
1140 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, CONNECT_TIMEOUT);
1141 std::unique_ptr<XrdSfsFile> fh(m_sfs->newFile(name, m_monid++));
1143 std::stringstream ss;
1144 ss <<
"Failed to initialize internal transfer file handle";
1147 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1150 std::string redirect_resource = req.
resource;
1151 if (query_header != req.
headers.end()) {
1152 redirect_resource = query_header->second;
1156 if ((overwrite_header == req.
headers.end()) || (overwrite_header->second ==
"T")) {
1162 if (streams_header != req.
headers.end()) {
1163 int stream_req = -1;
1165 stream_req = std::stol(streams_header->second);
1168 if (stream_req < 0 || stream_req > 100) {
1169 std::stringstream ss;
1170 ss <<
"Invalid request for number of streams";
1172 logTransferEvent(
LogMask::Info, rec,
"INVALID_REQUEST", ss.str());
1173 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1175 streams = stream_req == 0 ? 1 : stream_req;
1178 rec.streams = streams;
1179 std::string full_url = prepareURL(req);
1180 std::string authz = GetAuthz(req);
1181 curl_easy_setopt(curl, CURLOPT_URL, resource.c_str());
1182 if (!ConfigureCurlCA(curl, rec)) {
1183 std::stringstream ss;
1184 ss <<
"Failed to configure the certificate authorities for the transfer";
1187 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1189 uint64_t sourceFileContentLength = 0;
1194 GetContentLengthTPCPull(curl, req, sourceFileContentLength, success, rec);
1198 full_url +=
"&oss.asize=" + std::to_string(sourceFileContentLength);
1205 int open_result = OpenWaitStall(*fh, full_url, mode|
SFS_O_WRONLY,
1209 int result = RedirectTransfer(curl, redirect_resource, req, fh->
error, rec);
1211 }
else if (
SFS_OK != open_result) {
1213 std::stringstream ss;
1215 if ((msg == NULL) || (*msg ==
'\0')) ss <<
"Failed to open local resource";
1220 generateClientErr(ss, rec).c_str(), 0);
1224 Stream stream(std::move(fh), streams * m_pipelining_multiplier, streams > 1 ? m_block_size : m_small_block_size, m_log);
1230 return RunCurlWithStreams(req, state, streams, rec);
1232 return RunCurlWithUpdates(curl, req, state, rec);
1240void TPCHandler::logTransferEvent(
LogMask mask,
const TPCLogRecord &rec,
1241 const std::string &event,
const std::string &message)
1243 if (!(m_log.getMsgMask() & mask)) {
return;}
1245 std::stringstream ss;
1246 ss <<
"event=" <<
event <<
", local=" << rec.local <<
", remote=" << rec.remote;
1247 if (rec.name.empty())
1248 ss <<
", user=(anonymous)";
1250 ss <<
", user=" << rec.name;
1251 if (rec.streams != 1)
1252 ss <<
", streams=" << rec.streams;
1253 if (rec.bytes_transferred >= 0)
1254 ss <<
", bytes_transferred=" << rec.bytes_transferred;
1255 if (rec.status >= 0)
1256 ss <<
", status=" << rec.status;
1257 if (rec.tpc_status >= 0)
1258 ss <<
", tpc_status=" << rec.tpc_status;
1259 if (!message.empty())
1260 ss <<
"; " << message;
1261 m_log.Log(mask, rec.log_prefix.c_str(), ss.str().c_str());
1264std::string TPCHandler::generateClientErr(std::stringstream &err_ss,
const TPCLogRecord &rec, CURLcode cCode) {
1265 std::stringstream ssret;
1266 ssret <<
"failure: " << err_ss.str() <<
", local=" << rec.local <<
", remote=" << rec.remote;
1267 if(cCode != CURLcode::CURLE_OK) {
1268 ssret <<
", HTTP library failure=" << curl_easy_strerror(cCode);
1279 if (curl_global_init(CURL_GLOBAL_DEFAULT)) {
1280 log->
Emsg(
"TPCInitialize",
"libcurl failed to initialize");
1286 log->
Emsg(
"TPCInitialize",
"TPC handler requires a config filename in order to load");
1290 log->
Emsg(
"TPCInitialize",
"Will load configuration for the TPC handler from", config);
1292 }
catch (std::runtime_error &re) {
1293 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 getline(uchar *buff, int blen)
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)
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
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(const std::string &reqResource, std::map< std::string, std::string > &reqHeaders, const std::map< std::string, std::string > &hdr2cgimap)
static const int noPortRaw
Use raw address format (no port)
@ fmtAddr
Address using suitable ipv4 or ipv6 format.
static const char * GetAddrs(const char *hSpec, XrdNetAddr *aListP[], int &aListN, AddrOpts opts=allIPMap, int pNum=PortInSpec)
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)
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)
std::unique_ptr< CURL, CurlDeleter > ManagedCurlHandle
void operator()(CURL *curl)
static const int uIPv64
ucap: Supports only IPv4 info