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)) {
159 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);
387 if (srcHeader != req.
headers.end() && dstHeader != req.
headers.end()) {
388 const char *error_both =
"COPY rejected: both a Source and a Destination header were specified";
389 m_log.Emsg(
"ProcessReq", error_both);
392 if (srcHeader != req.
headers.end()) {
393 std::string src =
PrepareURL(srcHeader->second);
395 const char *error_src =
"COPY rejected: disallowed scheme in source URL";
396 m_log.Emsg(
"ProcessReq", error_src, src.c_str());
399 return ProcessPullReq(src, req);
401 if (dstHeader != req.
headers.end()) {
402 const std::string& dst = dstHeader->second;
404 const char *error_dst =
"COPY rejected: disallowed scheme in destination URL";
405 m_log.Emsg(
"ProcessReq", error_dst, dst.c_str());
408 return ProcessPushReq(dst, req);
410 m_log.Emsg(
"ProcessReq",
"COPY verb requested but no source or destination specified.");
411 return req.
SendSimpleResp(400, NULL, NULL,
"No Source or Destination specified", 0);
427 m_allow_local(false),
428 m_allow_private(true),
430 m_fixed_route(false),
431 m_low_speed_limit(10*1024),
432 m_low_speed_time(2*60),
434 m_first_timeout(120),
435 m_log(log->logger(),
"TPC_"),
438 if (!Configure(config, myEnv)) {
439 throw std::runtime_error(
"Failed to configure the HTTP third-party-copy handler.");
457 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);
467 if (authz_header != req.
headers.end()) {
468 std::stringstream ss;
469 ss <<
"authz=" <<
encode_str(authz_header->second);
479int TPCHandler::RedirectTransfer(
CURL *curl,
const std::string &redirect_resource,
480 XrdHttpExtReq &req, XrdOucErrInfo &error, TPCLogRecord &rec)
484 if ((ptr == NULL) || (*ptr ==
'\0') || (port == 0)) {
486 std::stringstream ss;
487 ss <<
"Internal error: redirect without hostname";
488 logTransferEvent(
LogMask::Error, rec,
"REDIRECT_INTERNAL_ERROR", ss.str());
489 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
493 std::string rdr_info = ptr;
494 std::string host, opaque;
495 size_t pos = rdr_info.find(
'?');
496 host = rdr_info.substr(0, pos);
498 if (pos != std::string::npos) {
499 opaque = rdr_info.substr(pos + 1);
502 std::stringstream ss;
503 ss <<
"Location: http" << (m_desthttps ?
"s" :
"") <<
"://" << host <<
":" << port <<
"/" << redirect_resource;
505 if (!opaque.empty()) {
511 return req.
SendSimpleResp(rec.status, NULL,
const_cast<char *
>(ss.str().c_str()),
519int TPCHandler::OpenWaitStall(XrdSfsFile &fh,
const std::string &resource,
520 int mode,
int openMode,
const XrdSecEntity &sec,
521 const std::string &authz)
528 size_t pos = resource.find(
'?');
530 std::string path = resource.substr(0, pos);
532 if (pos != std::string::npos) {
533 opaque = resource.substr(pos + 1);
538 opaque += (opaque.empty() ?
"" :
"&");
541 open_result = fh.
open(path.c_str(), mode, openMode, &sec, opaque.c_str());
545 if (open_result ==
SFS_STARTED) {secs_to_stall = secs_to_stall/2 + 5;}
546 std::this_thread::sleep_for (std::chrono::seconds(secs_to_stall));
562int TPCHandler::DetermineXferSize(
CURL *curl, XrdHttpExtReq &req,
State &state,
563 bool &success, TPCLogRecord &rec,
bool shouldReturnErrorToClient) {
565 curl_easy_setopt(curl, CURLOPT_NOBODY, 1);
567 curl_easy_setopt(curl, CURLOPT_TIMEOUT, CONNECT_TIMEOUT);
569 res = curl_easy_perform(curl);
572 curl_easy_setopt(curl, CURLOPT_NOBODY, 0);
574 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 0L);
575 curl_easy_setopt(curl, CURLOPT_FAILONERROR,
true);
577 std::stringstream ss;
580 res = CURLE_HTTP_RETURNED_ERROR;
582 if (res != CURLE_OK) {
583 ss << curl_easy_strerror(res);
585 case CURLE_HTTP_RETURNED_ERROR:
587 ss <<
": remote host returned '" << rec.tpc_status <<
" "
590 case CURLE_COULDNT_CONNECT:
591 switch (rec.tpc_status) {
593 ss <<
": connection to local/private addresses is forbidden";
596 ss <<
": internal server failure";
597 rec.tpc_status = 500;
601 rec.tpc_status = 500;
606 if (rec.tpc_status >= 400) {
608 return shouldReturnErrorToClient ? req.
SendSimpleResp(rec.tpc_status, NULL, NULL, generateClientErr(ss, rec, res).c_str(), 0) : -1;
612 ss <<
"Successfully determined remote size for pull request: " << state.
GetContentLength();
617int TPCHandler::GetContentLengthTPCPull(
CURL *curl, XrdHttpExtReq &req, uint64_t &contentLength,
bool & success, TPCLogRecord &rec) {
624 if ((result = DetermineXferSize(curl, req, state, success, rec)) || !success) {
635int TPCHandler::SendPerfMarker(XrdHttpExtReq &req, TPCLogRecord &rec, TPC::State &state) {
636 std::stringstream ss;
637 const std::string crlf =
"\n";
638 ss <<
"Perf Marker" << crlf;
639 ss <<
"Timestamp: " << time(NULL) << crlf;
640 ss <<
"Stripe Index: 0" << crlf;
642 ss <<
"Total Stripe Count: 1" << crlf;
647 ss <<
"RemoteConnections: " << desc << crlf;
652 return req.
ChunkResp(ss.str().c_str(), 0);
659int TPCHandler::SendPerfMarker(XrdHttpExtReq &req, TPCLogRecord &rec, std::vector<State*> &state,
660 off_t bytes_transferred)
674 std::stringstream ss;
675 const std::string crlf =
"\n";
676 ss <<
"Perf Marker" << crlf;
677 ss <<
"Timestamp: " << time(NULL) << crlf;
678 ss <<
"Stripe Index: 0" << crlf;
679 ss <<
"Stripe Bytes Transferred: " << bytes_transferred << crlf;
680 ss <<
"Total Stripe Count: 1" << crlf;
684 std::stringstream ss2;
685 for (std::vector<State*>::const_iterator iter = state.begin();
686 iter != state.end(); iter++)
688 std::string desc = (*iter)->GetConnectionDescription();
690 ss2 << (first ?
"" :
",") << desc;
695 ss <<
"RemoteConnections: " << ss2.str() << crlf;
697 rec.bytes_transferred = bytes_transferred;
700 return req.
ChunkResp(ss.str().c_str(), 0);
707int TPCHandler::RunCurlWithUpdates(
CURL *curl, XrdHttpExtReq &req,
State &state,
711 CURLM *multi_handle = curl_multi_init();
715 "Failed to initialize a libcurl multi-handle");
716 std::stringstream ss;
717 ss <<
"Failed to initialize internal server memory";
718 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
724 mres = curl_multi_add_handle(multi_handle, curl);
727 std::stringstream ss;
728 ss <<
"Failed to add transfer to libcurl multi-handle: HTTP library failure=" << curl_multi_strerror(mres);
729 logTransferEvent(
LogMask::Error, rec,
"CURL_INIT_FAIL", ss.str());
730 curl_multi_cleanup(multi_handle);
731 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
735 int retval = req.
StartChunkedResp(201,
"Created",
"Content-Type: text/plain");
737 curl_multi_cleanup(multi_handle);
739 "Failed to send the initial response to the TPC client");
743 "Initial transfer response sent to the TPC client");
748 int running_handles = 1;
749 time_t last_marker = 0;
751 off_t last_advance_bytes = 0;
752 time_t last_advance_time = time(NULL);
753 time_t transfer_start = last_advance_time;
754 CURLcode res =
static_cast<CURLcode
>(-1);
756 time_t now = time(NULL);
757 time_t next_marker = last_marker + m_marker_period;
758 if (now >= next_marker) {
760 if (bytes_xfer > last_advance_bytes) {
761 last_advance_bytes = bytes_xfer;
762 last_advance_time = now;
764 if (SendPerfMarker(req, rec, state)) {
765 curl_multi_remove_handle(multi_handle, curl);
766 curl_multi_cleanup(multi_handle);
768 "Failed to send a perf marker to the TPC client");
771 int timeout = (transfer_start == last_advance_time) ? m_first_timeout : m_timeout;
772 if (now > last_advance_time + timeout) {
773 const char *log_prefix = rec.log_prefix.c_str();
774 bool tpc_pull = strncmp(
"Pull", log_prefix, 4) == 0;
777 std::stringstream ss;
778 ss <<
"Transfer failed because no bytes have been "
779 << (tpc_pull ?
"received from the source (pull mode) in "
780 :
"transmitted to the destination (push mode) in ") << timeout <<
" seconds.";
782 curl_multi_remove_handle(multi_handle, curl);
783 curl_multi_cleanup(multi_handle);
789 rec.pmarkManager.startTransfer();
790 mres = curl_multi_perform(multi_handle, &running_handles);
791 if (mres == CURLM_CALL_MULTI_PERFORM) {
795 }
else if (mres != CURLM_OK) {
797 }
else if (running_handles == 0) {
801 rec.pmarkManager.beginPMarks();
808 msg = curl_multi_info_read(multi_handle, &msgq);
809 if (msg && (msg->msg == CURLMSG_DONE)) {
810 CURL *easy_handle = msg->easy_handle;
811 res = msg->data.result;
812 curl_multi_remove_handle(multi_handle, easy_handle);
816 int64_t max_sleep_time = next_marker - time(NULL);
817 if (max_sleep_time <= 0) {
821 mres = curl_multi_wait(multi_handle, NULL, 0, max_sleep_time*1000, &fd_count);
822 if (mres != CURLM_OK) {
825 }
while (running_handles);
827 if (mres != CURLM_OK) {
828 std::stringstream ss;
829 ss <<
"Internal libcurl multi-handle error: HTTP library failure=" << curl_multi_strerror(mres);
830 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_CURL_ERROR", ss.str());
832 curl_multi_remove_handle(multi_handle, curl);
833 curl_multi_cleanup(multi_handle);
835 if ((retval = req.
ChunkResp(generateClientErr(ss, rec).c_str(), 0))) {
837 "Failed to send error message to the TPC client");
847 msg = curl_multi_info_read(multi_handle, &msgq);
848 if (msg && (msg->msg == CURLMSG_DONE)) {
849 CURL *easy_handle = msg->easy_handle;
850 res = msg->data.result;
851 curl_multi_remove_handle(multi_handle, easy_handle);
855 if (!state.
GetErrorCode() && res ==
static_cast<CURLcode
>(-1)) {
856 curl_multi_remove_handle(multi_handle, curl);
857 curl_multi_cleanup(multi_handle);
858 std::stringstream ss;
859 ss <<
"Internal state error in libcurl";
860 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_CURL_ERROR", ss.str());
862 if ((retval = req.
ChunkResp(generateClientErr(ss, rec).c_str(), 0))) {
864 "Failed to send error message to the TPC client");
869 curl_multi_cleanup(multi_handle);
893 std::string finalizeErrorMsg, finalizeErrorSuffix;
895 std::stringstream ss2;
897 ?
"Failed to flush the file to the local filesystem."
898 :
"Failed to finalize and close file handle.");
901 std::replace(err.begin(), err.end(),
'\n',
' ');
904 finalizeErrorMsg = ss2.str();
905 logTransferEvent(
LogMask::Error, rec,
"CLOSE_FAIL", finalizeErrorMsg);
906 finalizeErrorSuffix =
"; " + finalizeErrorMsg;
910 std::stringstream ss;
911 bool success =
false;
914 std::stringstream ss2;
915 ss2 <<
"Remote side failed with status code " << state.
GetStatusCode();
917 std::replace(err.begin(), err.end(),
'\n',
' ');
918 ss2 <<
"; error message: \"" << err <<
"\"";
920 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_FAIL", ss2.str());
921 ss2 << finalizeErrorSuffix;
922 ss << generateClientErr(ss2, rec);
926 std::stringstream ss2;
927 ss2 << transferErrorMsg;
928 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_FAIL", ss2.str());
929 ss2 << finalizeErrorSuffix;
930 ss << generateClientErr(ss2, rec);
931 }
else if (transferErrorCode) {
932 if (transferErrorMsg.empty()) {transferErrorMsg =
"(no error message provided)";}
933 else {std::replace(transferErrorMsg.begin(), transferErrorMsg.end(),
'\n',
' ');}
934 std::stringstream ss2;
935 ss2 <<
"Error when interacting with local filesystem: " << transferErrorMsg;
936 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_FAIL", ss2.str());
937 ss2 << finalizeErrorSuffix;
938 ss << generateClientErr(ss2, rec);
939 }
else if (res != CURLE_OK) {
940 std::stringstream ss2;
941 ss2 <<
"Internal transfer failure";
942 std::stringstream ss3;
943 ss3 << ss2.str() <<
": " << curl_easy_strerror(res);
944 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_FAIL", ss3.str());
945 ss2 << finalizeErrorSuffix;
946 ss << generateClientErr(ss2, rec, res);
947 }
else if (!finalizeErrorMsg.empty()) {
949 std::stringstream ss2;
950 ss2 << finalizeErrorMsg;
951 ss << generateClientErr(ss2, rec);
953 ss <<
"success: Created";
957 if ((retval = req.
ChunkResp(ss.str().c_str(), 0))) {
959 "Failed to send last update to remote client");
961 }
else if (success) {
972int TPCHandler::ProcessPushReq(
const std::string & resource, XrdHttpExtReq &req) {
974 rec.allow_local = m_allow_local;
975 rec.allow_private = m_allow_private;
976 rec.log_prefix =
"PushRequest";
978 rec.remote = resource;
982 if (name) rec.name = name;
983 logTransferEvent(
LogMask::Info, rec,
"PUSH_START",
"Starting a push request");
986 auto curl = curlPtr.get();
988 std::stringstream ss;
989 ss <<
"Failed to initialize internal transfer resources";
992 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
994 ConfigureCurlLowSpeed(curl);
995 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
996 curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
997 curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (
long) CURL_HTTP_VERSION_1_1);
998#if CURL_AT_LEAST_VERSION(7, 85, 0)
999 curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR,
"https,http");
1000 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR,
"https,http");
1002 long protocols = CURLPROTO_HTTP | CURLPROTO_HTTPS;
1003 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
1004 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
1006 curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, opensocket_callback);
1007 curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, &rec);
1008 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETFUNCTION, closesocket_callback);
1009 curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
1010 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETDATA, &rec);
1011 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, CONNECT_TIMEOUT);
1014 std::string redirect_resource = req.
resource;
1015 if (query_header != req.
headers.end()) {
1016 redirect_resource = query_header->second;
1020 uint64_t file_monid =
AtomicInc(m_monid);
1022 std::unique_ptr<XrdSfsFile> fh(m_sfs->newFile(name, file_monid));
1025 std::stringstream ss;
1026 ss <<
"Failed to initialize internal transfer file handle";
1029 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1031 std::string full_url = prepareURL(req);
1033 std::string authz = GetAuthz(req);
1035 int open_results = OpenWaitStall(*fh, full_url,
SFS_O_RDONLY, 0644,
1038 int result = RedirectTransfer(curl, redirect_resource, req, fh->
error, rec);
1040 }
else if (
SFS_OK != open_results) {
1042 std::stringstream ss;
1044 if (msg == NULL) ss <<
"Failed to open local resource";
1048 int resp_result = req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1052 if (!ConfigureCurlCA(curl, rec)) {
1053 std::stringstream ss;
1054 ss <<
"Failed to configure the certificate authorities for the transfer";
1057 int resp_result = req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1061 curl_easy_setopt(curl, CURLOPT_URL, resource.c_str());
1063 Stream stream(std::move(fh), 0, 0, m_log);
1067 return RunCurlWithUpdates(curl, req, state, rec);
1074int TPCHandler::ProcessPullReq(
const std::string &resource, XrdHttpExtReq &req) {
1076 rec.allow_local = m_allow_local;
1077 rec.allow_private = m_allow_private;
1078 rec.log_prefix =
"PullRequest";
1080 rec.remote = resource;
1084 if (name) rec.name = name;
1085 logTransferEvent(
LogMask::Info, rec,
"PULL_START",
"Starting a pull request");
1088 auto curl = curlPtr.get();
1090 std::stringstream ss;
1091 ss <<
"Failed to initialize internal transfer resources";
1094 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1096 ConfigureCurlLowSpeed(curl);
1105 if (m_fixed_route) {
1110 if (host_header != req.
headers.end()) {
1111 host = host_header->second;
1116 std::vector<XrdNetAddr> addresses;
1119 if (eText || addresses.empty() ||
1121 std::stringstream ss;
1122 ss <<
"Failed to determine host address of incoming request";
1125 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1129 curl_easy_setopt(curl, CURLOPT_INTERFACE, ip);
1131 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
1132 curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
1133 curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (
long) CURL_HTTP_VERSION_1_1);
1134#if CURL_AT_LEAST_VERSION(7, 85, 0)
1135 curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR,
"https,http");
1136 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR,
"https,http");
1138 long protocols = CURLPROTO_HTTP | CURLPROTO_HTTPS;
1139 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
1140 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
1142 curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, opensocket_callback);
1143 curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, &rec);
1144 curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
1145 curl_easy_setopt(curl, CURLOPT_SOCKOPTDATA , &rec);
1146 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETFUNCTION, closesocket_callback);
1147 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETDATA, &rec);
1148 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, CONNECT_TIMEOUT);
1149 std::unique_ptr<XrdSfsFile> fh(m_sfs->newFile(name, m_monid++));
1151 std::stringstream ss;
1152 ss <<
"Failed to initialize internal transfer file handle";
1155 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1158 std::string redirect_resource = req.
resource;
1159 if (query_header != req.
headers.end()) {
1160 redirect_resource = query_header->second;
1164 if ((overwrite_header == req.
headers.end()) || (overwrite_header->second ==
"T")) {
1170 if (streams_header != req.
headers.end()) {
1171 int stream_req = -1;
1173 stream_req = std::stol(streams_header->second);
1176 if (stream_req < 0 || stream_req > 100) {
1177 std::stringstream ss;
1178 ss <<
"Invalid request for number of streams";
1180 logTransferEvent(
LogMask::Info, rec,
"INVALID_REQUEST", ss.str());
1181 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1183 streams = stream_req == 0 ? 1 : stream_req;
1186 rec.streams = streams;
1187 std::string full_url = prepareURL(req);
1188 std::string authz = GetAuthz(req);
1189 curl_easy_setopt(curl, CURLOPT_URL, resource.c_str());
1190 if (!ConfigureCurlCA(curl, rec)) {
1191 std::stringstream ss;
1192 ss <<
"Failed to configure the certificate authorities for the transfer";
1195 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1197 uint64_t sourceFileContentLength = 0;
1202 GetContentLengthTPCPull(curl, req, sourceFileContentLength, success, rec);
1206 full_url +=
"&oss.asize=" + std::to_string(sourceFileContentLength);
1213 int open_result = OpenWaitStall(*fh, full_url, mode|
SFS_O_WRONLY,
1217 int result = RedirectTransfer(curl, redirect_resource, req, fh->
error, rec);
1219 }
else if (
SFS_OK != open_result) {
1221 std::stringstream ss;
1223 if ((msg == NULL) || (*msg ==
'\0')) ss <<
"Failed to open local resource";
1228 generateClientErr(ss, rec).c_str(), 0);
1232 Stream stream(std::move(fh), streams * m_pipelining_multiplier, streams > 1 ? m_block_size : m_small_block_size, m_log);
1238 return RunCurlWithStreams(req, state, streams, rec);
1240 return RunCurlWithUpdates(curl, req, state, rec);
1248void TPCHandler::logTransferEvent(
LogMask mask,
const TPCLogRecord &rec,
1249 const std::string &event,
const std::string &message)
1251 if (!(m_log.getMsgMask() & mask)) {
return;}
1253 std::stringstream ss;
1254 ss <<
"event=" <<
event <<
", local=" << rec.local <<
", remote=" << rec.remote;
1255 if (rec.name.empty())
1256 ss <<
", user=(anonymous)";
1258 ss <<
", user=" << rec.name;
1259 if (rec.streams != 1)
1260 ss <<
", streams=" << rec.streams;
1261 if (rec.bytes_transferred >= 0)
1262 ss <<
", bytes_transferred=" << rec.bytes_transferred;
1263 if (rec.status >= 0)
1264 ss <<
", status=" << rec.status;
1265 if (rec.tpc_status >= 0)
1266 ss <<
", tpc_status=" << rec.tpc_status;
1267 if (!message.empty())
1268 ss <<
"; " << message;
1269 m_log.Log(mask, rec.log_prefix.c_str(), ss.str().c_str());
1272std::string TPCHandler::generateClientErr(std::stringstream &err_ss,
const TPCLogRecord &rec, CURLcode cCode) {
1273 std::stringstream ssret;
1274 ssret <<
"failure: " << err_ss.str() <<
", local=" << rec.local <<
", remote=" << rec.remote;
1275 if(cCode != CURLcode::CURLE_OK) {
1276 ssret <<
", HTTP library failure=" << curl_easy_strerror(cCode);
1287 if (curl_global_init(CURL_GLOBAL_DEFAULT)) {
1288 log->
Emsg(
"TPCInitialize",
"libcurl failed to initialize");
1294 log->
Emsg(
"TPCInitialize",
"TPC handler requires a config filename in order to load");
1298 log->
Emsg(
"TPCInitialize",
"Will load configuration for the TPC handler from", config);
1300 }
catch (std::runtime_error &re) {
1301 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