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;
48TPCHandler::TPCLogRecord::~TPCLogRecord()
55 monInfo.
clID = clID.c_str();
57 gettimeofday(&monInfo.
endT, 0);
60 {monInfo.
dstURL = local.c_str();
61 monInfo.
srcURL = remote.c_str();
63 monInfo.
dstURL = remote.c_str();
64 monInfo.
srcURL = local.c_str();
68 if (!status) monInfo.
endRC = 0;
69 else if (tpc_status > 0) monInfo.
endRC = tpc_status;
70 else monInfo.
endRC = 1;
71 monInfo.
strm =
static_cast<unsigned char>(streams);
72 monInfo.
fSize = (bytes_transferred < 0 ? 0 : bytes_transferred);
75 tpcMonitor->Report(monInfo);
85 if (curl) curl_easy_cleanup(curl);
100int TPCHandler::sockopt_callback(
void *clientp, curl_socket_t curlfd, curlsocktype purpose) {
101 TPCLogRecord * rec = (TPCLogRecord *)clientp;
102 if (purpose == CURLSOCKTYPE_IPCXN && rec && rec->pmarkManager.isEnabled()) {
105 return CURL_SOCKOPT_ALREADY_CONNECTED;
107 return CURL_SOCKOPT_OK;
119int TPCHandler::opensocket_callback(
void *clientp,
120 curlsocktype purpose,
121 struct curl_sockaddr *aInfo)
125 if (purpose != CURLSOCKTYPE_IPCXN)
126 return CURL_SOCKET_BAD;
129 return CURL_SOCKET_BAD;
132 int fd = XrdSysFD_Socket(aInfo->family, aInfo->socktype, aInfo->protocol);
135 return CURL_SOCKET_BAD;
141 XrdNetAddr thePeer(&(aInfo->addr));
142 TPCLogRecord *rec =
static_cast<TPCLogRecord*
>(clientp);
145 if ((!rec->allow_private && thePeer.isPrivate()) || (!rec->allow_local && thePeer.isLocal())) {
146 rec->tpc_status = 403;
147 rec->m_log->Emsg(rec->log_prefix.c_str(),
148 "Connection to local/private address is forbidden");
150 return CURL_SOCKET_BAD;
155 std::stringstream connectErrMsg;
156 if(!rec->pmarkManager.connect(fd, &(aInfo->addr), aInfo->addrlen, CONNECT_TIMEOUT, connectErrMsg)) {
157 rec->m_log->Emsg(rec->log_prefix.c_str(),
"Unable to connect socket: ", connectErrMsg.str().c_str());
159 return CURL_SOCKET_BAD;
165int TPCHandler::closesocket_callback(
void *clientp, curl_socket_t fd) {
166 TPCLogRecord * rec = (TPCLogRecord *)clientp;
171 rec->pmarkManager.endPmark(fd);
181std::string TPCHandler::prepareURL(XrdHttpExtReq &req) {
196 std::stringstream parser(opaque);
197 std::string sequence;
198 std::stringstream output;
200 while (
getline(parser, sequence,
'&')) {
201 if (sequence.empty()) {
continue;}
202 size_t equal_pos = sequence.find(
'=');
204 if (equal_pos != std::string::npos)
205 val = curl_easy_escape(curl, sequence.c_str() + equal_pos + 1, sequence.size() - equal_pos - 1);
207 if (!val && equal_pos != std::string::npos) {
continue;}
209 if (!first) output <<
"&";
211 output << sequence.substr(0, equal_pos);
213 output <<
"=" << val;
225TPCHandler::ConfigureCurlCA(
CURL *curl)
227 auto ca_filename = m_ca_file ? m_ca_file->CAFilename() :
"";
228 auto crl_filename = m_ca_file ? m_ca_file->CRLFilename() :
"";
229 if (!ca_filename.empty() && !crl_filename.empty()) {
230 curl_easy_setopt(curl, CURLOPT_CAINFO, ca_filename.c_str());
234 std::ifstream in(crl_filename, std::ifstream::ate | std::ifstream::binary);
235 if(in.tellg() > 0 && m_ca_file->atLeastOneValidCRLFound()){
236 curl_easy_setopt(curl, CURLOPT_CRLFILE, crl_filename.c_str());
238 std::ostringstream oss;
239 oss <<
"No valid CRL file has been found in the file " << crl_filename <<
". Disabling CRL checking.";
240 m_log.Log(
Warning,
"TpcHandler",oss.str().c_str());
243 else if (!m_cadir.empty()) {
244 curl_easy_setopt(curl, CURLOPT_CAPATH, m_cadir.c_str());
246 if (!m_cafile.empty()) {
247 curl_easy_setopt(curl, CURLOPT_CAINFO, m_cafile.c_str());
253 return !strcmp(verb,
"COPY") || !strcmp(verb,
"OPTIONS");
262 const std::string replace_schemes[] = {
"davs://",
"s3://",
"s3s://" };
264 for (
const auto& s : replace_schemes)
265 if (url.compare(0, s.size(), s) == 0)
266 return "https://" + url.substr(s.size());
273 const std::string allowed_schemes[] = {
"https://",
"http://" };
275 for (
const auto& s : allowed_schemes)
276 if (url.compare(0, s.size(), s) == 0)
287 if (req.
verb ==
"OPTIONS") {
288 return ProcessOptionsReq(req);
291 if (header != req.
headers.end()) {
292 if (header->second !=
"none") {
293 m_log.Emsg(
"ProcessReq",
"COPY requested an unsupported credential type: ", header->second.c_str());
294 return req.
SendSimpleResp(400, NULL, NULL,
"COPY requestd an unsupported Credential type", 0);
298 if (header != req.
headers.end()) {
301 const char *error_src =
"COPY rejected: disallowed scheme in source URL";
302 m_log.Emsg(
"ProcessReq", error_src, src.c_str());
305 return ProcessPullReq(src, req);
308 if (header != req.
headers.end()) {
309 const std::string& dst = header->second;
311 const char *error_dst =
"COPY rejected: disallowed scheme in destination URL";
312 m_log.Emsg(
"ProcessReq", error_dst, dst.c_str());
315 return ProcessPushReq(header->second, req);
317 m_log.Emsg(
"ProcessReq",
"COPY verb requested but no source or destination specified.");
318 return req.
SendSimpleResp(400, NULL, NULL,
"No Source or Destination specified", 0);
334 m_allow_local(false),
335 m_allow_private(true),
337 m_fixed_route(false),
339 m_first_timeout(120),
340 m_log(log->logger(),
"TPC_"),
343 if (!Configure(config, myEnv)) {
344 throw std::runtime_error(
"Failed to configure the HTTP third-party-copy handler.");
362 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);
372 if (authz_header != req.
headers.end()) {
373 std::stringstream ss;
374 ss <<
"authz=" <<
encode_str(authz_header->second);
384int TPCHandler::RedirectTransfer(
CURL *curl,
const std::string &redirect_resource,
385 XrdHttpExtReq &req, XrdOucErrInfo &error, TPCLogRecord &rec)
389 if ((ptr == NULL) || (*ptr ==
'\0') || (port == 0)) {
391 std::stringstream ss;
392 ss <<
"Internal error: redirect without hostname";
393 logTransferEvent(
LogMask::Error, rec,
"REDIRECT_INTERNAL_ERROR", ss.str());
394 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
398 std::string rdr_info = ptr;
399 std::string host, opaque;
400 size_t pos = rdr_info.find(
'?');
401 host = rdr_info.substr(0, pos);
403 if (pos != std::string::npos) {
404 opaque = rdr_info.substr(pos + 1);
407 std::stringstream ss;
408 ss <<
"Location: http" << (m_desthttps ?
"s" :
"") <<
"://" << host <<
":" << port <<
"/" << redirect_resource;
410 if (!opaque.empty()) {
416 return req.
SendSimpleResp(rec.status, NULL,
const_cast<char *
>(ss.str().c_str()),
424int TPCHandler::OpenWaitStall(XrdSfsFile &fh,
const std::string &resource,
425 int mode,
int openMode,
const XrdSecEntity &sec,
426 const std::string &authz)
433 size_t pos = resource.find(
'?');
435 std::string path = resource.substr(0, pos);
437 if (pos != std::string::npos) {
438 opaque = resource.substr(pos + 1);
443 opaque += (opaque.empty() ?
"" :
"&");
446 open_result = fh.
open(path.c_str(), mode, openMode, &sec, opaque.c_str());
450 if (open_result ==
SFS_STARTED) {secs_to_stall = secs_to_stall/2 + 5;}
451 std::this_thread::sleep_for (std::chrono::seconds(secs_to_stall));
467int TPCHandler::DetermineXferSize(
CURL *curl, XrdHttpExtReq &req,
State &state,
468 bool &success, TPCLogRecord &rec,
bool shouldReturnErrorToClient) {
470 curl_easy_setopt(curl, CURLOPT_NOBODY, 1);
472 curl_easy_setopt(curl, CURLOPT_TIMEOUT, CONNECT_TIMEOUT);
474 res = curl_easy_perform(curl);
477 curl_easy_setopt(curl, CURLOPT_NOBODY, 0);
479 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 0L);
480 curl_easy_setopt(curl, CURLOPT_FAILONERROR,
true);
482 std::stringstream ss;
485 res = CURLE_HTTP_RETURNED_ERROR;
487 if (res != CURLE_OK) {
488 ss << curl_easy_strerror(res);
490 case CURLE_HTTP_RETURNED_ERROR:
492 ss <<
": remote host returned '" << rec.tpc_status <<
" "
495 case CURLE_COULDNT_CONNECT:
496 switch (rec.tpc_status) {
498 ss <<
": connection to local/private addresses is forbidden";
501 ss <<
": internal server failure";
502 rec.tpc_status = 500;
506 rec.tpc_status = 500;
511 if (rec.tpc_status >= 400) {
513 return shouldReturnErrorToClient ? req.
SendSimpleResp(rec.tpc_status, NULL, NULL, generateClientErr(ss, rec, res).c_str(), 0) : -1;
517 ss <<
"Successfully determined remote size for pull request: " << state.
GetContentLength();
522int TPCHandler::GetContentLengthTPCPull(
CURL *curl, XrdHttpExtReq &req, uint64_t &contentLength,
bool & success, TPCLogRecord &rec) {
529 if ((result = DetermineXferSize(curl, req, state, success, rec)) || !success) {
540int TPCHandler::SendPerfMarker(XrdHttpExtReq &req, TPCLogRecord &rec, TPC::State &state) {
541 std::stringstream ss;
542 const std::string crlf =
"\n";
543 ss <<
"Perf Marker" << crlf;
544 ss <<
"Timestamp: " << time(NULL) << crlf;
545 ss <<
"Stripe Index: 0" << crlf;
547 ss <<
"Total Stripe Count: 1" << crlf;
552 ss <<
"RemoteConnections: " << desc << crlf;
557 return req.
ChunkResp(ss.str().c_str(), 0);
564int TPCHandler::SendPerfMarker(XrdHttpExtReq &req, TPCLogRecord &rec, std::vector<State*> &state,
565 off_t bytes_transferred)
579 std::stringstream ss;
580 const std::string crlf =
"\n";
581 ss <<
"Perf Marker" << crlf;
582 ss <<
"Timestamp: " << time(NULL) << crlf;
583 ss <<
"Stripe Index: 0" << crlf;
584 ss <<
"Stripe Bytes Transferred: " << bytes_transferred << crlf;
585 ss <<
"Total Stripe Count: 1" << crlf;
589 std::stringstream ss2;
590 for (std::vector<State*>::const_iterator iter = state.begin();
591 iter != state.end(); iter++)
593 std::string desc = (*iter)->GetConnectionDescription();
595 ss2 << (first ?
"" :
",") << desc;
600 ss <<
"RemoteConnections: " << ss2.str() << crlf;
602 rec.bytes_transferred = bytes_transferred;
605 return req.
ChunkResp(ss.str().c_str(), 0);
612int TPCHandler::RunCurlWithUpdates(
CURL *curl, XrdHttpExtReq &req,
State &state,
616 CURLM *multi_handle = curl_multi_init();
620 "Failed to initialize a libcurl multi-handle");
621 std::stringstream ss;
622 ss <<
"Failed to initialize internal server memory";
623 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
629 mres = curl_multi_add_handle(multi_handle, curl);
632 std::stringstream ss;
633 ss <<
"Failed to add transfer to libcurl multi-handle: HTTP library failure=" << curl_multi_strerror(mres);
634 logTransferEvent(
LogMask::Error, rec,
"CURL_INIT_FAIL", ss.str());
635 curl_multi_cleanup(multi_handle);
636 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
640 int retval = req.
StartChunkedResp(201,
"Created",
"Content-Type: text/plain");
642 curl_multi_cleanup(multi_handle);
644 "Failed to send the initial response to the TPC client");
648 "Initial transfer response sent to the TPC client");
653 int running_handles = 1;
654 time_t last_marker = 0;
656 off_t last_advance_bytes = 0;
657 time_t last_advance_time = time(NULL);
658 time_t transfer_start = last_advance_time;
659 CURLcode res =
static_cast<CURLcode
>(-1);
661 time_t now = time(NULL);
662 time_t next_marker = last_marker + m_marker_period;
663 if (now >= next_marker) {
665 if (bytes_xfer > last_advance_bytes) {
666 last_advance_bytes = bytes_xfer;
667 last_advance_time = now;
669 if (SendPerfMarker(req, rec, state)) {
670 curl_multi_remove_handle(multi_handle, curl);
671 curl_multi_cleanup(multi_handle);
673 "Failed to send a perf marker to the TPC client");
676 int timeout = (transfer_start == last_advance_time) ? m_first_timeout : m_timeout;
677 if (now > last_advance_time + timeout) {
678 const char *log_prefix = rec.log_prefix.c_str();
679 bool tpc_pull = strncmp(
"Pull", log_prefix, 4) == 0;
682 std::stringstream ss;
683 ss <<
"Transfer failed because no bytes have been "
684 << (tpc_pull ?
"received from the source (pull mode) in "
685 :
"transmitted to the destination (push mode) in ") << timeout <<
" seconds.";
687 curl_multi_remove_handle(multi_handle, curl);
688 curl_multi_cleanup(multi_handle);
694 rec.pmarkManager.startTransfer();
695 mres = curl_multi_perform(multi_handle, &running_handles);
696 if (mres == CURLM_CALL_MULTI_PERFORM) {
700 }
else if (mres != CURLM_OK) {
702 }
else if (running_handles == 0) {
706 rec.pmarkManager.beginPMarks();
713 msg = curl_multi_info_read(multi_handle, &msgq);
714 if (msg && (msg->msg == CURLMSG_DONE)) {
715 CURL *easy_handle = msg->easy_handle;
716 res = msg->data.result;
717 curl_multi_remove_handle(multi_handle, easy_handle);
721 int64_t max_sleep_time = next_marker - time(NULL);
722 if (max_sleep_time <= 0) {
726 mres = curl_multi_wait(multi_handle, NULL, 0, max_sleep_time*1000, &fd_count);
727 if (mres != CURLM_OK) {
730 }
while (running_handles);
732 if (mres != CURLM_OK) {
733 std::stringstream ss;
734 ss <<
"Internal libcurl multi-handle error: HTTP library failure=" << curl_multi_strerror(mres);
735 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_CURL_ERROR", ss.str());
737 curl_multi_remove_handle(multi_handle, curl);
738 curl_multi_cleanup(multi_handle);
740 if ((retval = req.
ChunkResp(generateClientErr(ss, rec).c_str(), 0))) {
742 "Failed to send error message to the TPC client");
752 msg = curl_multi_info_read(multi_handle, &msgq);
753 if (msg && (msg->msg == CURLMSG_DONE)) {
754 CURL *easy_handle = msg->easy_handle;
755 res = msg->data.result;
756 curl_multi_remove_handle(multi_handle, easy_handle);
760 if (!state.
GetErrorCode() && res ==
static_cast<CURLcode
>(-1)) {
761 curl_multi_remove_handle(multi_handle, curl);
762 curl_multi_cleanup(multi_handle);
763 std::stringstream ss;
764 ss <<
"Internal state error in libcurl";
765 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_CURL_ERROR", ss.str());
767 if ((retval = req.
ChunkResp(generateClientErr(ss, rec).c_str(), 0))) {
769 "Failed to send error message to the TPC client");
774 curl_multi_cleanup(multi_handle);
788 std::stringstream ss;
789 bool success =
false;
792 std::stringstream ss2;
793 ss2 <<
"Remote side failed with status code " << state.
GetStatusCode();
795 std::replace(err.begin(), err.end(),
'\n',
' ');
796 ss2 <<
"; error message: \"" << err <<
"\"";
798 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_FAIL", ss2.str());
799 ss << generateClientErr(ss2, rec);
802 if (err.empty()) {err =
"(no error message provided)";}
803 else {std::replace(err.begin(), err.end(),
'\n',
' ');}
804 std::stringstream ss2;
805 ss2 <<
"Error when interacting with local filesystem: " << err;
806 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_FAIL", ss2.str());
807 ss << generateClientErr(ss2, rec);
808 }
else if (res != CURLE_OK) {
809 std::stringstream ss2;
810 ss2 <<
"Internal transfer failure";
811 std::stringstream ss3;
812 ss3 << ss2.str() <<
": " << curl_easy_strerror(res);
813 logTransferEvent(
LogMask::Error, rec,
"TRANSFER_FAIL", ss3.str());
814 ss << generateClientErr(ss2, rec, res);
816 ss <<
"success: Created";
820 if ((retval = req.
ChunkResp(ss.str().c_str(), 0))) {
822 "Failed to send last update to remote client");
824 }
else if (success) {
835int TPCHandler::ProcessPushReq(
const std::string & resource, XrdHttpExtReq &req) {
837 rec.allow_local = m_allow_local;
838 rec.allow_private = m_allow_private;
839 rec.log_prefix =
"PushRequest";
841 rec.remote = resource;
845 if (name) rec.name = name;
846 logTransferEvent(
LogMask::Info, rec,
"PUSH_START",
"Starting a push request");
849 auto curl = curlPtr.get();
851 std::stringstream ss;
852 ss <<
"Failed to initialize internal transfer resources";
855 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
857 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
858 curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (
long) CURL_HTTP_VERSION_1_1);
859#if CURL_AT_LEAST_VERSION(7, 85, 0)
860 curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR,
"https,http");
861 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR,
"https,http");
863 long protocols = CURLPROTO_HTTP | CURLPROTO_HTTPS;
864 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
865 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
867 curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, opensocket_callback);
868 curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, &rec);
869 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETFUNCTION, closesocket_callback);
870 curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
871 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETDATA, &rec);
872 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, CONNECT_TIMEOUT);
875 std::string redirect_resource = req.
resource;
876 if (query_header != req.
headers.end()) {
877 redirect_resource = query_header->second;
881 uint64_t file_monid =
AtomicInc(m_monid);
883 std::unique_ptr<XrdSfsFile> fh(m_sfs->newFile(name, file_monid));
886 std::stringstream ss;
887 ss <<
"Failed to initialize internal transfer file handle";
890 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
892 std::string full_url = prepareURL(req);
894 std::string authz = GetAuthz(req);
896 int open_results = OpenWaitStall(*fh, full_url,
SFS_O_RDONLY, 0644,
899 int result = RedirectTransfer(curl, redirect_resource, req, fh->
error, rec);
901 }
else if (
SFS_OK != open_results) {
903 std::stringstream ss;
905 if (msg == NULL) ss <<
"Failed to open local resource";
909 int resp_result = req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
913 ConfigureCurlCA(curl);
914 curl_easy_setopt(curl, CURLOPT_URL, resource.c_str());
916 Stream stream(std::move(fh), 0, 0, m_log);
920 return RunCurlWithUpdates(curl, req, state, rec);
927int TPCHandler::ProcessPullReq(
const std::string &resource, XrdHttpExtReq &req) {
929 rec.allow_local = m_allow_local;
930 rec.allow_private = m_allow_private;
931 rec.log_prefix =
"PullRequest";
933 rec.remote = resource;
937 if (name) rec.name = name;
938 logTransferEvent(
LogMask::Info, rec,
"PULL_START",
"Starting a pull request");
941 auto curl = curlPtr.get();
943 std::stringstream ss;
944 ss <<
"Failed to initialize internal transfer resources";
947 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
965 std::string host_used;
966 if (host_header != req.
headers.end()) {
967 host_used = host_header->second;
973 ip = (
char *)malloc(ip_size-1);
976 memcpy(ip, buff+1, ip_size-2);
980 curl_easy_setopt(curl, CURLOPT_INTERFACE, ip);
982 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
983 curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (
long) CURL_HTTP_VERSION_1_1);
984#if CURL_AT_LEAST_VERSION(7, 85, 0)
985 curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR,
"https,http");
986 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR,
"https,http");
988 long protocols = CURLPROTO_HTTP | CURLPROTO_HTTPS;
989 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
990 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
992 curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, opensocket_callback);
993 curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, &rec);
994 curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
995 curl_easy_setopt(curl, CURLOPT_SOCKOPTDATA , &rec);
996 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETFUNCTION, closesocket_callback);
997 curl_easy_setopt(curl, CURLOPT_CLOSESOCKETDATA, &rec);
998 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, CONNECT_TIMEOUT);
999 std::unique_ptr<XrdSfsFile> fh(m_sfs->newFile(name, m_monid++));
1001 std::stringstream ss;
1002 ss <<
"Failed to initialize internal transfer file handle";
1005 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1008 std::string redirect_resource = req.
resource;
1009 if (query_header != req.
headers.end()) {
1010 redirect_resource = query_header->second;
1014 if ((overwrite_header == req.
headers.end()) || (overwrite_header->second ==
"T")) {
1020 if (streams_header != req.
headers.end()) {
1021 int stream_req = -1;
1023 stream_req = std::stol(streams_header->second);
1026 if (stream_req < 0 || stream_req > 100) {
1027 std::stringstream ss;
1028 ss <<
"Invalid request for number of streams";
1030 logTransferEvent(
LogMask::Info, rec,
"INVALID_REQUEST", ss.str());
1031 return req.
SendSimpleResp(rec.status, NULL, NULL, generateClientErr(ss, rec).c_str(), 0);
1033 streams = stream_req == 0 ? 1 : stream_req;
1036 rec.streams = streams;
1037 std::string full_url = prepareURL(req);
1038 std::string authz = GetAuthz(req);
1039 curl_easy_setopt(curl, CURLOPT_URL, resource.c_str());
1040 ConfigureCurlCA(curl);
1041 uint64_t sourceFileContentLength = 0;
1046 GetContentLengthTPCPull(curl, req, sourceFileContentLength, success, rec);
1050 full_url +=
"&oss.asize=" + std::to_string(sourceFileContentLength);
1057 int open_result = OpenWaitStall(*fh, full_url, mode|
SFS_O_WRONLY,
1061 int result = RedirectTransfer(curl, redirect_resource, req, fh->
error, rec);
1063 }
else if (
SFS_OK != open_result) {
1065 std::stringstream ss;
1067 if ((msg == NULL) || (*msg ==
'\0')) ss <<
"Failed to open local resource";
1072 generateClientErr(ss, rec).c_str(), 0);
1076 Stream stream(std::move(fh), streams * m_pipelining_multiplier, streams > 1 ? m_block_size : m_small_block_size, m_log);
1082 return RunCurlWithStreams(req, state, streams, rec);
1084 return RunCurlWithUpdates(curl, req, state, rec);
1092void TPCHandler::logTransferEvent(
LogMask mask,
const TPCLogRecord &rec,
1093 const std::string &event,
const std::string &message)
1095 if (!(m_log.getMsgMask() & mask)) {
return;}
1097 std::stringstream ss;
1098 ss <<
"event=" <<
event <<
", local=" << rec.local <<
", remote=" << rec.remote;
1099 if (rec.name.empty())
1100 ss <<
", user=(anonymous)";
1102 ss <<
", user=" << rec.name;
1103 if (rec.streams != 1)
1104 ss <<
", streams=" << rec.streams;
1105 if (rec.bytes_transferred >= 0)
1106 ss <<
", bytes_transferred=" << rec.bytes_transferred;
1107 if (rec.status >= 0)
1108 ss <<
", status=" << rec.status;
1109 if (rec.tpc_status >= 0)
1110 ss <<
", tpc_status=" << rec.tpc_status;
1111 if (!message.empty())
1112 ss <<
"; " << message;
1113 m_log.Log(mask, rec.log_prefix.c_str(), ss.str().c_str());
1116std::string TPCHandler::generateClientErr(std::stringstream &err_ss,
const TPCLogRecord &rec, CURLcode cCode) {
1117 std::stringstream ssret;
1118 ssret <<
"failure: " << err_ss.str() <<
", local=" << rec.local <<
", remote=" << rec.remote;
1119 if(cCode != CURLcode::CURLE_OK) {
1120 ssret <<
", HTTP library failure=" << curl_easy_strerror(cCode);
1131 if (curl_global_init(CURL_GLOBAL_DEFAULT)) {
1132 log->
Emsg(
"TPCInitialize",
"libcurl failed to initialize");
1138 log->
Emsg(
"TPCInitialize",
"TPC handler requires a config filename in order to load");
1142 log->
Emsg(
"TPCInitialize",
"Will load configuration for the TPC handler from", config);
1144 }
catch (std::runtime_error &re) {
1145 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 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)
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 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