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)
125 int fd = XrdSysFD_Socket(aInfo->family, aInfo->socktype, aInfo->protocol);
129 return CURL_SOCKET_BAD;
131 TPCLogRecord * rec = (TPCLogRecord *)clientp;
132 if (purpose == CURLSOCKTYPE_IPCXN && clientp)
133 {XrdNetAddr thePeer(&(aInfo->addr));
135 && !thePeer.isMapped());
136 std::stringstream connectErrMsg;
138 if(!rec->pmarkManager.connect(fd, &(aInfo->addr), aInfo->addrlen, CONNECT_TIMEOUT, connectErrMsg)) {
139 rec->m_log->Emsg(rec->log_prefix.c_str(),
"Unable to connect socket:", connectErrMsg.str().c_str());
140 return CURL_SOCKET_BAD;
147int TPCHandler::closesocket_callback(
void *clientp, curl_socket_t fd) {
148 TPCLogRecord * rec = (TPCLogRecord *)clientp;
153 rec->pmarkManager.endPmark(fd);
168int TPCHandler::ssl_ctx_callback(
CURL *curl,
void *ssl_ctx,
void *clientp) {
170 SSL_CTX* ctx =
static_cast<SSL_CTX*
>(ssl_ctx);
171 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_callback);
172 return CURL_SOCKOPT_OK;
175int TPCHandler::verify_callback(
int preverify_ok, X509_STORE_CTX* ctx) {
176 if (preverify_ok == 1)
return 1;
178 int err = X509_STORE_CTX_get_error(ctx);
180 if (err == X509_V_ERR_UNABLE_TO_GET_CRL) {
181 X509_STORE_CTX_set_error(ctx, X509_V_OK);
193std::string TPCHandler::prepareURL(XrdHttpExtReq &req) {
198bool TPCHandler::mismatchReprDigest(
const std::map<std::string, std::string> & passiveSrvReprDigest, XrdHttpExtReq &req,
200 if(passiveSrvReprDigest.size()) {
201 for (
const auto & [digestName, digestValue]: passiveSrvReprDigest) {
202 auto clientDigestMatch = req.
mReprDigest.find(digestName);
205 if (clientDigestMatch->second != digestValue) {
207 std::stringstream errMsg;
208 errMsg <<
"Mismatch between client-provided and remote server checksums:"
209 <<
" client = (" << clientDigestMatch->first <<
"=" << clientDigestMatch->second <<
")"
210 <<
" server = (" << digestName <<
"=" << digestValue <<
")";
211 logTransferEvent(
LogMask::Error, rec,
"REPRDIGEST_VERIFY_FAIL", errMsg.str());
213 req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(errMsg, rec, CURLcode::CURLE_OK).c_str(), 0);
233 std::stringstream parser(opaque);
234 std::string sequence;
235 std::stringstream output;
237 while (
getline(parser, sequence,
'&')) {
238 if (sequence.empty()) {
continue;}
239 size_t equal_pos = sequence.find(
'=');
241 if (equal_pos != std::string::npos)
242 val = curl_easy_escape(curl, sequence.c_str() + equal_pos + 1, sequence.size() - equal_pos - 1);
244 if (!val && equal_pos != std::string::npos) {
continue;}
246 if (!first) output <<
"&";
248 output << sequence.substr(0, equal_pos);
250 output <<
"=" << val;
262TPCHandler::ConfigureCurlCA(
CURL *curl)
264 auto ca_filename = m_ca_file ? m_ca_file->CAFilename() :
"";
265 auto crl_filename = m_ca_file ? m_ca_file->CRLFilename() :
"";
266 if (!ca_filename.empty() && !crl_filename.empty()) {
267 curl_easy_setopt(curl, CURLOPT_CAINFO, ca_filename.c_str());
271 std::ifstream in(crl_filename, std::ifstream::ate | std::ifstream::binary);
272 if(in.tellg() > 0 && m_ca_file->atLeastOneValidCRLFound()){
273 curl_easy_setopt(curl, CURLOPT_CRLFILE, crl_filename.c_str());
274 if (allowMissingCRL) {
276 curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, ssl_ctx_callback);
279 std::ostringstream oss;
280 oss <<
"No valid CRL file has been found in the file " << crl_filename <<
". Disabling CRL checking.";
281 m_log.Log(
Warning,
"TpcHandler",oss.str().c_str());
284 else if (!m_cadir.empty()) {
285 curl_easy_setopt(curl, CURLOPT_CAPATH, m_cadir.c_str());
287 if (!m_cafile.empty()) {
288 curl_easy_setopt(curl, CURLOPT_CAINFO, m_cafile.c_str());
294 return !strcmp(verb,
"COPY") || !strcmp(verb,
"OPTIONS");
302 if (!strncmp(input.c_str(),
"davs://", 7)) {
303 return "https://" + input.substr(7);
313 if (req.
verb ==
"OPTIONS") {
314 return ProcessOptionsReq(req);
317 if (header != req.
headers.end()) {
318 if (header->second !=
"none") {
319 m_log.Emsg(
"ProcessReq",
"COPY requested an unsupported credential type: ", header->second.c_str());
320 return req.
SendSimpleResp(400, NULL, NULL,
"COPY requestd an unsupported Credential type", 0);
324 if (header != req.
headers.end()) {
326 return ProcessPullReq(src, req);
329 if (header != req.
headers.end()) {
330 return ProcessPushReq(header->second, req);
332 m_log.Emsg(
"ProcessReq",
"COPY verb requested but no source or destination specified.");
333 return req.
SendSimpleResp(400, NULL, NULL,
"No Source or Destination specified", 0);
350 m_fixed_route(false),
352 m_first_timeout(120),
353 m_log(log->logger(),
"TPC_"),
356 if (!Configure(config, myEnv)) {
357 throw std::runtime_error(
"Failed to configure the HTTP third-party-copy handler.");
375 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);
385 if (authz_header != req.
headers.end()) {
386 std::stringstream ss;
387 ss <<
"authz=" <<
encode_str(authz_header->second);
397int TPCHandler::RedirectTransfer(
CURL *curl,
const std::string &redirect_resource,
398 XrdHttpExtReq &req, XrdOucErrInfo &error, TPCLogRecord &rec)
402 if ((ptr == NULL) || (*ptr ==
'\0') || (port == 0)) {
404 std::stringstream ss;
405 ss <<
"Internal error: redirect without hostname";
406 logTransferEvent(
LogMask::Error, rec,
"REDIRECT_INTERNAL_ERROR", ss.str());
407 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
411 std::string rdr_info = ptr;
412 std::string host, opaque;
413 size_t pos = rdr_info.find(
'?');
414 host = rdr_info.substr(0, pos);
416 if (pos != std::string::npos) {
417 opaque = rdr_info.substr(pos + 1);
420 std::stringstream ss;
421 ss <<
"Location: http" << (m_desthttps ?
"s" :
"") <<
"://" << host <<
":" << port <<
"/" << redirect_resource;
423 if (!opaque.empty()) {
429 return req.
SendSimpleResp(rec.status, NULL,
const_cast<char *
>(ss.str().c_str()),
437int TPCHandler::OpenWaitStall(XrdSfsFile &fh,
const std::string &resource,
438 int mode,
int openMode,
const XrdSecEntity &sec,
439 const std::string &authz)
446 size_t pos = resource.find(
'?');
448 std::string path = resource.substr(0, pos);
450 if (pos != std::string::npos) {
451 opaque = resource.substr(pos + 1);
456 opaque += (opaque.empty() ?
"" :
"&");
459 open_result = fh.
open(path.c_str(), mode, openMode, &sec, opaque.c_str());
463 if (open_result ==
SFS_STARTED) {secs_to_stall = secs_to_stall/2 + 5;}
464 std::this_thread::sleep_for (std::chrono::seconds(secs_to_stall));
480int TPCHandler::PerformHEADRequest(
CURL *curl, XrdHttpExtReq &req,
State &state,
481 bool &success, TPCLogRecord &rec,
bool shouldReturnErrorToClient) {
483 curl_easy_setopt(curl, CURLOPT_NOBODY, 1);
485 curl_easy_setopt(curl, CURLOPT_TIMEOUT, CONNECT_TIMEOUT);
487 res = curl_easy_perform(curl);
490 curl_easy_setopt(curl, CURLOPT_NOBODY, 0);
492 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 0L);
493 if (res == CURLE_HTTP_RETURNED_ERROR) {
494 std::stringstream ss;
495 ss <<
"Remote server failed request while fetching file information (HEAD)";
496 std::stringstream ss2;
497 ss2 << ss.str() <<
": " << curl_easy_strerror(res);
500 return shouldReturnErrorToClient ? req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec, res).c_str(), 0) : -1;
502 std::stringstream ss;
503 ss <<
"Remote side " << req.
clienthost <<
" failed with status code " << state.
GetStatusCode() <<
" while fetching remote file information (HEAD)";
506 return shouldReturnErrorToClient ? req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0) : -1;
508 std::stringstream ss;
509 ss <<
"Internal transfer failure while fetching remote file information (HEAD)";
510 std::stringstream ss2;
511 ss2 << ss.str() <<
" - HTTP library failed: " << curl_easy_strerror(res);
514 return shouldReturnErrorToClient ? req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec, res).c_str(), 0) : -1;
516 std::stringstream ss;
517 ss <<
"Successfully determined remote file information for pull request: "
520 unsigned int cksumIndex = 1;
521 for(
const auto & [cksumType,cksumValue]: state.
GetReprDigest()) {
522 ss <<
" chksum" << cksumIndex <<
"=(" << cksumType <<
"," << cksumValue <<
")";
531int TPCHandler::GetRemoteFileInfoTPCPull(
CURL *curl, XrdHttpExtReq &req, uint64_t &contentLength, std::map<std::string,std::string> & reprDigest,
bool & success, TPCLogRecord &rec) {
538 if ((result = PerformHEADRequest(curl, req, state, success, rec)) || !success) {
550int TPCHandler::SendPerfMarker(XrdHttpExtReq &req, TPCLogRecord &rec, TPC::State &state) {
551 std::stringstream ss;
552 const std::string crlf =
"\n";
553 ss <<
"Perf Marker" << crlf;
554 ss <<
"Timestamp: " << time(NULL) << crlf;
555 ss <<
"Stripe Index: 0" << crlf;
557 ss <<
"Total Stripe Count: 1" << crlf;
562 ss <<
"RemoteConnections: " << desc << crlf;
567 return req.
ChunkResp(ss.str().c_str(), 0);
574int TPCHandler::SendPerfMarker(XrdHttpExtReq &req, TPCLogRecord &rec, std::vector<State*> &state,
575 off_t bytes_transferred)
589 std::stringstream ss;
590 const std::string crlf =
"\n";
591 ss <<
"Perf Marker" << crlf;
592 ss <<
"Timestamp: " << time(NULL) << crlf;
593 ss <<
"Stripe Index: 0" << crlf;
594 ss <<
"Stripe Bytes Transferred: " << bytes_transferred << crlf;
595 ss <<
"Total Stripe Count: 1" << crlf;
599 std::stringstream ss2;
600 for (std::vector<State*>::const_iterator iter = state.begin();
601 iter != state.end(); iter++)
603 std::string desc = (*iter)->GetConnectionDescription();
605 ss2 << (first ?
"" :
",") << desc;
610 ss <<
"RemoteConnections: " << ss2.str() << crlf;
612 rec.bytes_transferred = bytes_transferred;
615 return req.
ChunkResp(ss.str().c_str(), 0);
622int TPCHandler::RunCurlWithUpdates(
CURL *curl, XrdHttpExtReq &req,
State &state,
626 CURLM *multi_handle = curl_multi_init();
630 "Failed to initialize a libcurl multi-handle");
631 std::stringstream ss;
632 ss <<
"Failed to initialize internal server memory";
633 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
639 mres = curl_multi_add_handle(multi_handle, curl);
642 std::stringstream ss;
643 ss <<
"Failed to add transfer to libcurl multi-handle: HTTP library failure=" << curl_multi_strerror(mres);
644 logTransferEvent(
LogMask::Error, rec,
"CURL_INIT_FAIL", ss.str());
645 curl_multi_cleanup(multi_handle);
646 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
652 curl_multi_cleanup(multi_handle);
654 "Failed to send the initial response to the TPC client");
658 "Initial transfer response sent to the TPC client");
663 int running_handles = 1;
664 time_t last_marker = 0;
666 off_t last_advance_bytes = 0;
667 time_t last_advance_time = time(NULL);
668 time_t transfer_start = last_advance_time;
669 CURLcode res =
static_cast<CURLcode
>(-1);
671 time_t now = time(NULL);
672 time_t next_marker = last_marker + m_marker_period;
673 if (now >= next_marker) {
675 if (bytes_xfer > last_advance_bytes) {
676 last_advance_bytes = bytes_xfer;
677 last_advance_time = now;
679 if (SendPerfMarker(req, rec, state)) {
680 curl_multi_remove_handle(multi_handle, curl);
681 curl_multi_cleanup(multi_handle);
683 "Failed to send a perf marker to the TPC client");
686 int timeout = (transfer_start == last_advance_time) ? m_first_timeout : m_timeout;
687 if (now > last_advance_time + timeout) {
688 const char *log_prefix = rec.log_prefix.c_str();
689 bool tpc_pull = strncmp(
"Pull", log_prefix, 4) == 0;
692 std::stringstream ss;
693 ss <<
"Transfer failed because no bytes have been "
694 << (tpc_pull ?
"received from the source (pull mode) in "
695 :
"transmitted to the destination (push mode) in ") << timeout <<
" seconds.";
697 curl_multi_remove_handle(multi_handle, curl);
698 curl_multi_cleanup(multi_handle);
704 rec.pmarkManager.startTransfer();
705 mres = curl_multi_perform(multi_handle, &running_handles);
706 if (mres == CURLM_CALL_MULTI_PERFORM) {
710 }
else if (mres != CURLM_OK) {
712 }
else if (running_handles == 0) {
716 rec.pmarkManager.beginPMarks();
723 msg = curl_multi_info_read(multi_handle, &msgq);
724 if (msg && (msg->msg == CURLMSG_DONE)) {
725 CURL *easy_handle = msg->easy_handle;
726 res = msg->data.result;
727 curl_multi_remove_handle(multi_handle, easy_handle);
731 int64_t max_sleep_time = next_marker - time(NULL);
732 if (max_sleep_time <= 0) {
736 mres = curl_multi_wait(multi_handle, NULL, 0, max_sleep_time*1000, &fd_count);
737 if (mres != CURLM_OK) {
740 }
while (running_handles);
742 if (mres != CURLM_OK) {
743 std::stringstream ss;
744 ss <<
"Internal libcurl multi-handle error: HTTP library failure=" << curl_multi_strerror(mres);
745 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_CURL_ERROR", ss.str());
747 curl_multi_remove_handle(multi_handle, curl);
748 curl_multi_cleanup(multi_handle);
750 if ((retval = req.
ChunkResp(generateClientErr(ss, rec).c_str(), 0))) {
752 "Failed to send error message to the TPC client");
762 msg = curl_multi_info_read(multi_handle, &msgq);
763 if (msg && (msg->msg == CURLMSG_DONE)) {
764 CURL *easy_handle = msg->easy_handle;
765 res = msg->data.result;
766 curl_multi_remove_handle(multi_handle, easy_handle);
770 if (!state.
GetErrorCode() && res ==
static_cast<CURLcode
>(-1)) {
771 curl_multi_remove_handle(multi_handle, curl);
772 curl_multi_cleanup(multi_handle);
773 std::stringstream ss;
774 ss <<
"Internal state error in libcurl";
775 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_CURL_ERROR", ss.str());
777 if ((retval = req.
ChunkResp(generateClientErr(ss, rec).c_str(), 0))) {
779 "Failed to send error message to the TPC client");
784 curl_multi_cleanup(multi_handle);
798 std::stringstream ss;
799 bool success =
false;
802 std::stringstream ss2;
803 ss2 <<
"Remote side failed with status code " << state.
GetStatusCode();
805 std::replace(err.begin(), err.end(),
'\n',
' ');
806 ss2 <<
"; error message: \"" << err <<
"\"";
808 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_FAIL", ss2.str());
809 ss << generateClientErr(ss2, rec);
812 if (err.empty()) {err =
"(no error message provided)";}
813 else {std::replace(err.begin(), err.end(),
'\n',
' ');}
814 std::stringstream ss2;
815 ss2 <<
"Error when interacting with local filesystem: " << err;
816 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_FAIL", ss2.str());
817 ss << generateClientErr(ss2, rec);
818 }
else if (res != CURLE_OK) {
819 std::stringstream ss2;
820 ss2 <<
"Internal transfer failure";
821 std::stringstream ss3;
822 ss3 << ss2.str() <<
": " << curl_easy_strerror(res);
823 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_FAIL", ss3.str());
824 ss << generateClientErr(ss2, rec, res);
826 ss <<
"success: Created";
830 if ((retval = req.
ChunkResp(ss.str().c_str(), 0))) {
832 "Failed to send last update to remote client");
834 }
else if (success) {
845int TPCHandler::ProcessPushReq(
const std::string & resource, XrdHttpExtReq &req) {
847 rec.log_prefix =
"PushRequest";
849 rec.remote = resource;
853 if (name) rec.name = name;
854 logTransferEvent(
LogMask::Info, rec,
"PUSH_START",
"Starting a push request");
857 auto curl = curlPtr.get();
859 std::stringstream ss;
860 ss <<
"Failed to initialize internal transfer resources";
863 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
865 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
866 curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (
long) CURL_HTTP_VERSION_1_1);
869 curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, opensocket_callback);
870 curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, &rec);
871 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETFUNCTION, closesocket_callback);
872 curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
873 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETDATA, &rec);
874 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, CONNECT_TIMEOUT);
876 std::string redirect_resource = req.
resource;
877 if (query_header != req.
headers.end()) {
878 redirect_resource = query_header->second;
882 uint64_t file_monid =
AtomicInc(m_monid);
884 std::unique_ptr<XrdSfsFile> fh(m_sfs->newFile(name, file_monid));
887 std::stringstream ss;
888 ss <<
"Failed to initialize internal transfer file handle";
891 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
893 std::string full_url = prepareURL(req);
895 std::string authz = GetAuthz(req);
897 int open_results = OpenWaitStall(*fh, full_url,
SFS_O_RDONLY, 0644,
900 int result = RedirectTransfer(curl, redirect_resource, req, fh->
error, rec);
902 }
else if (
SFS_OK != open_results) {
904 std::stringstream ss;
906 if (msg == NULL) ss <<
"Failed to open local resource";
910 int resp_result = req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
914 ConfigureCurlCA(curl);
915 curl_easy_setopt(curl, CURLOPT_URL, resource.c_str());
917 Stream stream(std::move(fh), 0, 0, m_log);
921 return RunCurlWithUpdates(curl, req, state, rec);
928int TPCHandler::ProcessPullReq(
const std::string &resource, XrdHttpExtReq &req) {
930 rec.log_prefix =
"PullRequest";
932 rec.remote = resource;
936 if (name) rec.name = name;
937 logTransferEvent(
LogMask::Info, rec,
"PULL_START",
"Starting a pull request");
940 auto curl = curlPtr.get();
942 std::stringstream ss;
943 ss <<
"Failed to initialize internal transfer resources";
946 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
963 std::string host_used;
964 if (host_header != req.
headers.end()) {
965 host_used = host_header->second;
971 ip = (
char *)malloc(ip_size-1);
974 memcpy(ip, buff+1, ip_size-2);
978 curl_easy_setopt(curl, CURLOPT_INTERFACE, ip);
980 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
981 curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (
long) CURL_HTTP_VERSION_1_1);
983 curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, opensocket_callback);
984 curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, &rec);
985 curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
986 curl_easy_setopt(curl, CURLOPT_SOCKOPTDATA , &rec);
987 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETFUNCTION, closesocket_callback);
988 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETDATA, &rec);
989 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, CONNECT_TIMEOUT);
990 std::unique_ptr<XrdSfsFile> fh(m_sfs->newFile(name, m_monid++));
992 std::stringstream ss;
993 ss <<
"Failed to initialize internal transfer file handle";
996 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
999 std::string redirect_resource = req.
resource;
1000 if (query_header != req.
headers.end()) {
1001 redirect_resource = query_header->second;
1005 if ((overwrite_header == req.
headers.end()) || (overwrite_header->second ==
"T")) {
1011 if (streams_header != req.
headers.end()) {
1012 int stream_req = -1;
1014 stream_req = std::stol(streams_header->second);
1017 if (stream_req < 0 || stream_req > 100) {
1018 std::stringstream ss;
1019 ss <<
"Invalid request for number of streams";
1021 logTransferEvent(
LogMask::Info, rec,
"INVALID_REQUEST", ss.str());
1022 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1024 streams = stream_req == 0 ? 1 : stream_req;
1027 rec.streams = streams;
1028 std::string full_url = prepareURL(req);
1029 std::string authz = GetAuthz(req);
1030 curl_easy_setopt(curl, CURLOPT_URL, resource.c_str());
1031 ConfigureCurlCA(curl);
1032 uint64_t sourceFileContentLength = 0;
1036 bool success =
false;
1037 bool mismatchDigests =
false;
1038 std::map<std::string,std::string> sourceFileReprDigest;
1039 GetRemoteFileInfoTPCPull(curl, req, sourceFileContentLength, sourceFileReprDigest, success, rec);
1043 full_url +=
"&oss.asize=" + std::to_string(sourceFileContentLength);
1044 mismatchDigests = mismatchReprDigest(sourceFileReprDigest,req,rec);
1046 if(!success || mismatchDigests) {
1053 int open_result = OpenWaitStall(*fh, full_url, mode|
SFS_O_WRONLY,
1057 int result = RedirectTransfer(curl, redirect_resource, req, fh->
error, rec);
1059 }
else if (
SFS_OK != open_result) {
1061 std::stringstream ss;
1063 if ((msg == NULL) || (*msg ==
'\0')) ss <<
"Failed to open local resource";
1068 generateClientErr(ss, rec).c_str(), 0);
1072 Stream stream(std::move(fh), streams * m_pipelining_multiplier, streams > 1 ? m_block_size : m_small_block_size, m_log);
1078 return RunCurlWithStreams(req, state, streams, rec);
1080 return RunCurlWithUpdates(curl, req, state, rec);
1088void TPCHandler::logTransferEvent(
LogMask mask,
const TPCLogRecord &rec,
1089 const std::string &event,
const std::string &message)
1091 if (!(m_log.getMsgMask() & mask)) {
return;}
1093 std::stringstream ss;
1094 ss <<
"event=" <<
event <<
", local=" << rec.local <<
", remote=" << rec.remote;
1095 if (rec.name.empty())
1096 ss <<
", user=(anonymous)";
1098 ss <<
", user=" << rec.name;
1099 if (rec.streams != 1)
1100 ss <<
", streams=" << rec.streams;
1101 if (rec.bytes_transferred >= 0)
1102 ss <<
", bytes_transferred=" << rec.bytes_transferred;
1103 if (rec.status >= 0)
1104 ss <<
", status=" << rec.status;
1105 if (rec.tpc_status >= 0)
1106 ss <<
", tpc_status=" << rec.tpc_status;
1107 if (!message.empty())
1108 ss <<
"; " << message;
1109 m_log.Log(mask, rec.log_prefix.c_str(), ss.str().c_str());
1112std::string TPCHandler::generateClientErr(std::stringstream &err_ss,
const TPCLogRecord &rec, CURLcode cCode) {
1113 std::stringstream ssret;
1114 ssret <<
"failure: " << err_ss.str() <<
", local=" << rec.local <<
", remote=" << rec.remote;
1115 if(cCode != CURLcode::CURLE_OK) {
1116 ssret <<
", HTTP library failure=" << curl_easy_strerror(cCode);
1127 if (curl_global_init(CURL_GLOBAL_DEFAULT)) {
1128 log->
Emsg(
"TPCInitialize",
"libcurl failed to initialize");
1134 log->
Emsg(
"TPCInitialize",
"TPC handler requires a config filename in order to load");
1138 log->
Emsg(
"TPCInitialize",
"Will load configuration for the TPC handler from", config);
1140 }
catch (std::runtime_error &re) {
1141 log->
Emsg(
"TPCInitialize",
"Encountered a runtime failure when loading ", re.what());
XrdHttpExtHandler * XrdHttpGetExtHandler(XrdHttpExtHandlerArgs)
static std::string PrepareURL(const std::string &input)
XrdVERSIONINFO(XrdHttpGetExtHandler, HttpTPC)
std::string encode_xrootd_opaque_to_uri(CURL *curl, const std::string &opaque)
int mapErrNoToHttp(int errNo)
Utility functions for XrdHTTP.
std::string encode_str(const std::string &str)
void getline(uchar *buff, int blen)
const std::map< std::string, std::string > & GetReprDigest() const
int GetStatusCode() const
off_t BytesTransferred() const
void SetErrorMessage(const std::string &error_msg)
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 const int noPort
Do not add port number.
int Format(char *bAddr, int bLen, fmtUse fmtType=fmtAuto, int fmtOpts=0)
@ 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