/
XrdHttpProtocol.cc
1963 lines (1388 loc) · 47.4 KB
/
XrdHttpProtocol.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** @file XrdHttpProtocol.cc
* @brief A pragmatic implementation of the HTTP/DAV protocol for the Xrd framework
* @author Fabrizio Furano
* @date Nov 2012
*
*
*
*/
#include "XrdVersion.hh"
#include "Xrd/XrdBuffer.hh"
#include "Xrd/XrdLink.hh"
#include "XProtocol/XProtocol.hh"
#include "XrdOuc/XrdOucStream.hh"
#include "XrdOuc/XrdOucEnv.hh"
#include "XrdSys/XrdSysTimer.hh"
#include "XrdSys/XrdSysPlugin.hh"
#include "XrdHttpTrace.hh"
#include "XrdHttpProtocol.hh"
//#include "XrdXrootd/XrdXrootdStats.hh"
#include <boost/lexical_cast.hpp>
#include <sys/stat.h>
#include "XrdHttpUtils.hh"
#include "XrdHttpSecXtractor.hh"
#include <openssl/err.h>
#include <vector>
#include <arpa/inet.h>
#define XRHTTP_TK_GRACETIME 600
/******************************************************************************/
/* G l o b a l s */
/******************************************************************************/
//
// Static stuff
//
int XrdHttpProtocol::hailWait = 0;
int XrdHttpProtocol::readWait = 0;
int XrdHttpProtocol::Port = 1094;
char *XrdHttpProtocol::Port_str = 0;
char *XrdHttpProtocol::Addr_str = 0;
int XrdHttpProtocol::Window = 0;
char *XrdHttpProtocol::SecLib = 0;
//XrdXrootdStats *XrdHttpProtocol::SI = 0;
char *XrdHttpProtocol::sslcert = 0;
char *XrdHttpProtocol::sslkey = 0;
char *XrdHttpProtocol::sslcadir = 0;
char *XrdHttpProtocol::listredir = 0;
bool XrdHttpProtocol::listdeny = false;
bool XrdHttpProtocol::embeddedstatic = true;
kXR_int32 XrdHttpProtocol::myRole = kXR_isManager;
bool XrdHttpProtocol::selfhttps2http = false;
bool XrdHttpProtocol::isdesthttps = false;
char *XrdHttpProtocol::sslcafile = 0;
char *XrdHttpProtocol::secretkey = 0;
int XrdHttpProtocol::sslverifydepth = 9;
SSL_CTX *XrdHttpProtocol::sslctx = 0;
BIO *XrdHttpProtocol::sslbio_err = 0;
XrdHttpSecXtractor *XrdHttpProtocol::secxtractor = 0;
static const unsigned char *s_server_session_id_context = (const unsigned char *) "XrdHTTPSessionCtx";
static int s_server_session_id_context_len = 18;
XrdScheduler *XrdHttpProtocol::Sched = 0; // System scheduler
XrdBuffManager *XrdHttpProtocol::BPool = 0; // Buffer manager
XrdSysError XrdHttpProtocol::eDest = 0; // Error message handler
XrdSecService *XrdHttpProtocol::CIA = 0; // Authentication Server
/******************************************************************************/
/* P r o t o c o l M a n a g e m e n t S t a c k s */
/******************************************************************************/
XrdObjectQ<XrdHttpProtocol>
XrdHttpProtocol::ProtStack("ProtStack",
"xrootd protocol anchor");
/******************************************************************************/
/* P r o t o c o l L o a d e r */
/* X r d g e t P r o t o c o l */
/******************************************************************************/
// This protocol can live in a shared library. The interface below is used by
// the protocol driver to obtain a copy of the protocol object that can be used
// to decide whether or not a link is talking a particular protocol.
//
XrdVERSIONINFO(XrdgetProtocol, xrootd);
extern "C" {
XrdProtocol *XrdgetProtocol(const char *pname, char *parms,
XrdProtocol_Config *pi) {
XrdProtocol *pp = 0;
const char *txt = "completed.";
// Put up the banner
//
pi->eDest->Say("Copr. 2012 CERN IT, an HTTP implementation for the XROOTD framework.");
pi->eDest->Say("++++++ HTTP protocol initialization started.");
// Return the protocol object to be used if static init succeeds
//
if (XrdHttpProtocol::Configure(parms, pi))
pp = (XrdProtocol *)new XrdHttpProtocol(false);
else txt = "failed.";
pi->eDest->Say("------ HTTP protocol initialization ", txt);
return pp;
}
}
/******************************************************************************/
/* */
/* P r o t o c o l P o r t D e t e r m i n a t i o n */
/* X r d g e t P r o t o c o l P o r t */
/******************************************************************************/
// This function is called early on to determine the port we need to use. The
// default is ostensibly 1094 but can be overidden; which we allow.
//
XrdVERSIONINFO(XrdgetProtocolPort, xrootd);
extern "C" {
int XrdgetProtocolPort(const char *pname, char *parms, XrdProtocol_Config *pi) {
// Figure out what port number we should return. In practice only one port
// number is allowed. However, we could potentially have a clustered port
// and several unclustered ports. So, we let this practicality slide.
//
if (pi->Port < 0) return 1094;
return pi->Port;
}
}
/******************************************************************************/
/* X r d H T T P P r o t o c o l C l a s s */
/******************************************************************************/
/******************************************************************************/
/* C o n s t r u c t o r */
/******************************************************************************/
XrdHttpProtocol::XrdHttpProtocol(bool imhttps)
: XrdProtocol("HTTP protocol handler"), ProtLink(this),
SecEntity(""), CurrentReq(this) {
myBuff = 0;
Reset();
ishttps = imhttps;
}
/******************************************************************************/
/* A s s i g n m e n t O p e r a t o r */
/******************************************************************************/
XrdHttpProtocol XrdHttpProtocol::operator =(const XrdHttpProtocol &rhs) {
return *this;
}
/******************************************************************************/
/* M a t c h */
/******************************************************************************/
#define TRACELINK lp
XrdProtocol *XrdHttpProtocol::Match(XrdLink *lp) {
char mybuf[16], mybuf2[1024];
XrdHttpProtocol *hp;
int dlen;
bool myishttps = false;
// Peek at the first 20 bytes of data
//
if ((dlen = lp->Peek(mybuf, (int) sizeof (mybuf), hailWait)) < (int) sizeof (mybuf)) {
if (dlen <= 0) lp->setEtext("handshake not received");
return (XrdProtocol *) 0;
}
mybuf[dlen - 1] = '\0';
// Trace the data
//
TRACEI(DEBUG, "received dlen: " << dlen);
//TRACEI(REQ, "received buf: " << mybuf);
mybuf2[0] = '\0';
for (int i = 0; i < dlen; i++) {
char mybuf3[16];
sprintf(mybuf3, "%.02d ", mybuf[i]);
strcat(mybuf2, mybuf3);
}
TRACEI(DEBUG, "received dump: " << mybuf2);
// Decide if it looks http or not. For now we are happy if all the received characters are alphanumeric
bool ismine = true;
for (int i = 0; i < dlen - 1; i++)
if (!isprint(mybuf[i]) && (mybuf[i] != '\r') && (mybuf[i] != '\n')) {
ismine = false;
TRACEI(DEBUG, "This does not look like http at pos " << i);
break;
}
// If it does not look http then look if it looks like https
if ((!ismine) && (dlen >= 4)) {
char check[4] = {00, 00, 00, 00};
if (memcmp(mybuf, check, 4)) {
if (sslcert) {
ismine = true;
myishttps = true;
TRACEI(DEBUG, "This may look like https");
} else {
TRACEI(ALL, "This may look like https, but https is not configured");
}
}
}
if (!ismine) {
TRACEI(DEBUG, "This does not look like https. Protocol not matched.");
return (XrdProtocol *) 0;
}
// It does look http or https...
// Get a protocol object off the stack (if none, allocate a new one)
//
TRACEI(REQ, "Protocol matched. https: " << myishttps);
if (!(hp = ProtStack.Pop())) hp = new XrdHttpProtocol(myishttps);
else
hp->ishttps = myishttps;
// Bind the protocol to the link and return the protocol
//
hp->Link = lp;
return (XrdProtocol *) hp;
}
/******************************************************************************/
/* G e t V O M S D a t a */
/******************************************************************************/
int XrdHttpProtocol::GetVOMSData(XrdLink *lp) {
SecEntity.host = GetClientIPStr();
// Invoke our instance of the Security exctractor plugin
// This will fill the XrdSec thing with VOMS info, if VOMS is
// installed. If we have no sec extractor then do nothing, just plain https
// will work.
if (secxtractor) secxtractor->GetSecData(lp, SecEntity, ssl);
else {
X509 *peer_cert;
// No external plugin, hence we fill our XrdSec with what we can do here
peer_cert = SSL_get_peer_certificate(ssl);
TRACEI(DEBUG, " SSL_get_peer_certificate returned :" << peer_cert);
if (peer_cert && peer_cert->name) {
TRACEI(DEBUG, " Setting Username :" << peer_cert->name);
lp->setID(peer_cert->name, 0);
// Here we should fill the SecEntity instance with the DN and the voms stuff
SecEntity.name = strdup((char *) peer_cert->name);
}
if (peer_cert) X509_free(peer_cert);
}
return 0;
}
char *XrdHttpProtocol::GetClientIPStr() {
char buf[256];
buf[0] = '\0';
if (!Link) return strdup("unknown");
XrdNetAddrInfo *ai = Link->AddrInfo();
if (!ai) return strdup("unknown");
if (!Link->AddrInfo()->Format(buf, 255, XrdNetAddrInfo::fmtAddr)) return strdup("unknown");
return strdup(buf);
}
/******************************************************************************/
/* P r o c e s s */
/******************************************************************************/
#undef TRACELINK
#define TRACELINK Link
int XrdHttpProtocol::Process(XrdLink *lp) // We ignore the argument here
{
int rc = 0;
TRACEI(DEBUG, " Process. lp:" << lp << " reqstate: " << CurrentReq.reqstate);
if (!myBuff || !myBuff->buff || !myBuff->bsize) {
TRACE(ALL, " Process. No buffer available. Internal error.");
return -1;
}
if (!SecEntity.host) {
char *nfo = GetClientIPStr();
if (nfo) {
TRACEI(REQ, " Setting host: " << nfo);
SecEntity.host = nfo;
}
}
// If https then check independently for the ssl handshake
if (ishttps && !ssldone) {
ssl = SSL_new(sslctx);
if (!ssl) {
TRACEI(DEBUG, " SSL_new returned NULL");
ERR_print_errors(sslbio_err);
return -1;
}
SSL_set_fd(ssl, Link->FDnum());
struct timeval tv;
tv.tv_sec = readWait;
tv.tv_usec = 0;
setsockopt(Link->FDnum(), SOL_SOCKET, SO_RCVTIMEO, (struct timeval *)&tv, sizeof(struct timeval));
setsockopt(Link->FDnum(), SOL_SOCKET, SO_SNDTIMEO, (struct timeval *)&tv, sizeof(struct timeval));
int res = SSL_accept(ssl);
TRACEI(DEBUG, " SSL_accept returned :" << res);
ERR_print_errors(sslbio_err);
if (res < 0) {
SSL_free(ssl);
ssl = 0;
return -1;
}
// Get the voms string and auth information
GetVOMSData(Link);
ERR_print_errors(sslbio_err);
res = SSL_get_verify_result(ssl);
TRACEI(DEBUG, " SSL_get_verify_result returned :" << res);
ERR_print_errors(sslbio_err);
if (res != X509_V_OK) return -1;
ssldone = true;
}
if (!DoingLogin) {
// Re-invocations triggered by the bridge have lp==0
// In this case we keep track of a different request state
if (lp) {
// This is an invocation that was triggered by a socket event
// Read all the data that is available, throw it into the buffer
if ((rc = getDataOneShot(BuffAvailable())) < 0) {
// Error -> exit
return -1;
}
// If we need more bytes, let's wait for another invokation
if (BuffUsed() < ResumeBytes) return 1;
} else
CurrentReq.reqstate++;
}
DoingLogin = false;
// Read the next request header, that is, read until a double CRLF is found
if (!CurrentReq.headerok) {
// Read as many lines as possible into the buffer. An empty line breaks
while ((rc = BuffgetLine(tmpline)) > 0) {
TRACE(DEBUG, " rc:" << rc << " got hdr line: " << tmpline);
if ((rc == 2) && (tmpline[rc - 1] == '\n')) {
CurrentReq.headerok = true;
TRACE(DEBUG, " rc:" << rc << " detected header end.");
break;
}
if (CurrentReq.request == CurrentReq.rtUnknown)
CurrentReq.parseFirstLine((char *)tmpline.c_str(), rc);
else
CurrentReq.parseLine((char *)tmpline.c_str(), rc);
}
// Here we have CurrentReq loaded with the header, or its relevant fields
if (!CurrentReq.headerok) {
TRACEI(REQ, " rc:" << rc << "Header not yet complete.");
// Waiting for more data
return 1;
}
}
// If we are in self-redirect mode, then let's do it
if (ishttps && ssldone && selfhttps2http) {
char hash[512];
time_t timenow = time(0);
calcHashes(hash, CurrentReq.resource.c_str(), (kXR_int16) CurrentReq.request,
&SecEntity,
timenow,
secretkey);
if (hash[0]) {
// Workaround... delete the previous opaque information
if (CurrentReq.opaque) {
delete CurrentReq.opaque;
CurrentReq.opaque = 0;
}
TRACEI(REQ, " rc:" << rc << " self-redirecting to http with security token.");
XrdOucString dest = "Location: http://";
// Here I should put the IP addr of the server
Link->Host();
dest += Addr_str;
dest += ":";
dest += Port_str;
dest += CurrentReq.resource.c_str();
CurrentReq.appendOpaque(dest, &SecEntity, hash, timenow);
SendSimpleResp(302, NULL, (char *) dest.c_str(), 0, 0);
CurrentReq.reset();
return 1;
}
}
// If this is not https, then extract the signed information from the url
// and fill the SecEntity structure as if we were using https
if (!ishttps && !ssldone) {
if (CurrentReq.opaque) {
char * tk = CurrentReq.opaque->Get("xrdhttptk");
// If there is a hash then we use it as authn info
if (tk) {
time_t tim = 0;
char * t = CurrentReq.opaque->Get("xrdhttptime");
if (t) tim = atoi(t);
if (!t) {
TRACEI(REQ, " xrdhttptime not specified. Authentication failed.");
return -1;
}
if (abs((time(0) - tim) > XRHTTP_TK_GRACETIME)) {
TRACEI(REQ, " Token expired. Authentication failed.");
return -1;
}
// Fill the Secentity from the fields in the URL:name, vo, host
char *nfo;
nfo = CurrentReq.opaque->Get("xrdhttpvorg");
if (nfo) {
TRACEI(REQ, " Setting vorg: " << nfo);
SecEntity.vorg = strdup(nfo);
}
nfo = CurrentReq.opaque->Get("xrdhttpname");
if (nfo) {
TRACEI(REQ, " Setting name: " << nfo);
SecEntity.name = unquote(nfo);
}
//nfo = CurrentReq.opaque->Get("xrdhttphost");
// TODO: compare the xrdhttphost with the real client IP
// If they are different then reject
char hash[512];
calcHashes(hash, CurrentReq.resource.c_str(), (kXR_int16) CurrentReq.request,
&SecEntity,
tim,
secretkey);
if (compareHash(hash, tk)) {
TRACEI(REQ, " Invalid tk. Authentication failed.");
return -1;
}
} else {
// Client is plain http. If we have a secret key then we reject it
if (secretkey) {
TRACEI(ALL, " Rejecting plain http with no valid token as we have a secretkey.");
return -1;
}
}
} else {
// Client is plain http. If we have a secret key then we reject it
if (secretkey) {
TRACEI(ALL, " Rejecting plain http with no valid token as we have a secretkey.");
return -1;
}
}
ssldone = true;
}
// Now we have everything that is needed to try the login
if (!Bridge) {
Bridge = XrdXrootd::Bridge::Login(&CurrentReq, Link, &SecEntity, "unnamed", "XrdHttp");
if (!Bridge) {
TRACEI(REQ, " Autorization failed.");
return -1;
}
// Let the bridge process the login, and then reinvoke us
DoingLogin = true;
return 0;
}
// Compute and send the response. This may involve further reading from the socket
rc = CurrentReq.ProcessHTTPReq();
if (rc < 0)
CurrentReq.reset();
TRACEI(REQ, "Process is exiting rc:" << rc);
return rc;
}
/******************************************************************************/
/* R e c y c l e */
/******************************************************************************/
#undef TRACELINK
#define TRACELINK Link
void XrdHttpProtocol::Recycle(XrdLink *lp, int csec, const char *reason) {
// Release all appendages
//
Cleanup();
// Set fields to starting point (debugging mostly)
//
Reset();
// Push ourselves on the stack
//
ProtStack.Push(&ProtLink);
}
int XrdHttpProtocol::Stats(char *buff, int blen, int do_sync) {
// Synchronize statistics if need be
//
// if (do_sync) {
//
// SI->statsMutex.Lock();
// SI->readCnt += numReads;
// cumReads += numReads;
// numReads = 0;
// SI->prerCnt += numReadP;
// cumReadP += numReadP;
// numReadP = 0;
// SI->rvecCnt += numReadV;
// cumReadV += numReadV;
// numReadV = 0;
// SI->rsegCnt += numSegsV;
// cumSegsV += numSegsV;
// numSegsV = 0;
// SI->writeCnt += numWrites;
// cumWrites += numWrites;
// numWrites = 0;
// SI->statsMutex.UnLock();
// }
//
// // Now return the statistics
// //
// return SI->Stats(buff, blen, do_sync);
return 0;
}
/******************************************************************************/
/* C o n f i g */
/******************************************************************************/
#define TS_Xeq(x,m) (!strcmp(x,var)) GoNo = m(Config)
int XrdHttpProtocol::Config(const char *ConfigFN) {
XrdOucEnv myEnv;
XrdOucStream Config(&eDest, getenv("XRDINSTANCE"), &myEnv, "=====> ");
char *var;
int cfgFD, GoNo, NoGo = 0, ismine;
// Open and attach the config file
//
if ((cfgFD = open(ConfigFN, O_RDONLY, 0)) < 0)
return eDest.Emsg("Config", errno, "open config file", ConfigFN);
Config.Attach(cfgFD);
// Process items
//
while ((var = Config.GetMyFirstWord())) {
if ((ismine = !strncmp("http.", var, 5)) && var[5]) var += 5;
else if ((ismine = !strcmp("all.export", var))) var += 4;
else if ((ismine = !strcmp("all.pidpath", var))) var += 4;
else if ((ismine = !strcmp("all.seclib", var))) var += 4;
if (ismine) {
if TS_Xeq("seclib", xsecl);
else if TS_Xeq("trace", xtrace);
else if TS_Xeq("cert", xsslcert);
else if TS_Xeq("key", xsslkey);
else if TS_Xeq("cadir", xsslcadir);
else if TS_Xeq("cafile", xsslcafile);
else if TS_Xeq("secretkey", xsecretkey);
else if TS_Xeq("desthttps", xdesthttps);
else if TS_Xeq("secxtractor", xsecxtractor);
else if TS_Xeq("selfhttps2http", xselfhttps2http);
else if TS_Xeq("embeddedstatic", xembeddedstatic);
else if TS_Xeq("listingredir", xlistredir);
else if TS_Xeq("listingdeny", xlistdeny);
else {
eDest.Say("Config warning: ignoring unknown directive '", var, "'.");
Config.Echo();
continue;
}
if (GoNo) {
Config.Echo();
NoGo = 1;
}
}
}
if (sslcert)
InitSecurity();
return NoGo;
}
/******************************************************************************/
/* P r i v a t e M e t h o d s */
/******************************************************************************/
/// Copy a full line of text from the buffer into dest. Zero if no line can be found in the buffer
int XrdHttpProtocol::BuffgetLine(XrdOucString &dest) {
dest = "";
// Easy case
if (myBuffEnd >= myBuffStart) {
int l = 0;
for (char *p = myBuffStart; p < myBuffEnd; p++) {
l++;
if (*p == '\n') {
dest.assign(myBuffStart, 0, l-1);
//strncpy(dest, myBuffStart, l);
//dest[l] = '\0';
BuffConsume(l);
//if (dest[l-1] == '\n') dest[l - 1] = '\0';
return l;
}
}
return 0;
} else {
// More complex case... we have to do it in two segments
// Segment 1: myBuffStart->myBuff->buff+myBuff->bsize
int l = 0;
for (char *p = myBuffStart; p < myBuff->buff + myBuff->bsize; p++) {
l++;
if ((*p == '\n') || (*p == '\0')) {
dest.assign(myBuffStart, 0, l-1);
//strncpy(dest, myBuffStart, l);
BuffConsume(l);
//if (dest[l-1] == '\n') dest[l - 1] = '\0';
return l;
}
}
// We did not find the \n, let's keep on searching in the 2nd segment
// Segment 2: myBuff->buff --> myBuffEnd
l = 0;
for (char *p = myBuff->buff; p < myBuffEnd; p++) {
l++;
if ((*p == '\n') || (*p == '\0')) {
// Remember the 1st segment
int l1 = myBuff->buff + myBuff->bsize - myBuffStart;
dest.assign(myBuffStart, 0, l1-1);
//strncpy(dest, myBuffStart, l1);
BuffConsume(l1);
dest.insert(myBuffStart, l1, l-1);
//strncpy(dest + l1, myBuffStart, l);
//dest[l + l1] = '\0';
BuffConsume(l);
//if (dest[l + l1 - 1] == '\n') dest[l + l1 - 1] = '\0';
return l + l1;
}
}
}
return 0;
}
int XrdHttpProtocol::getDataOneShot(int blen, bool wait) {
int rlen, maxread;
// Get up to blen bytes from the connection. Put them into mybuff.
// This primitive, for the way it is used, is not supposed to block if wait=false
// Returns:
// 2: no space left in buffer
// 1: timeout
// -1: error
// 0: everything read correctly
// Check for buffer overflow first
maxread = min(blen, BuffAvailable());
TRACE(DEBUG, "getDataOneShot BuffAvailable: " << BuffAvailable() << " maxread: " << maxread);
if (!maxread)
return 2;
if (ishttps) {
int sslavail = maxread;
if (!wait) {
int l = SSL_pending(ssl);
if (l > 0)
sslavail = min(maxread, SSL_pending(ssl));
}
if (sslavail < 0) {
Link->setEtext("link SSL_pending error");
ERR_print_errors(sslbio_err);
return -1;
}
TRACE(DEBUG, "getDataOneShot sslavail: " << sslavail);
if (sslavail <= 0) return 0;
if (myBuffEnd - myBuff->buff >= myBuff->bsize) {
TRACE(DEBUG, "getDataOneShot Buffer panic");
myBuffEnd = myBuff->buff;
}
rlen = SSL_read(ssl, myBuffEnd, sslavail);
if (rlen <= 0) {
Link->setEtext("link SSL read error");
ERR_print_errors(sslbio_err);
return -1;
}
} else {
if (myBuffEnd - myBuff->buff >= myBuff->bsize) {
TRACE(DEBUG, "getDataOneShot Buffer panic");
myBuffEnd = myBuff->buff;
}
if (wait)
rlen = Link->Recv(myBuffEnd, maxread, readWait);
else
rlen = Link->Recv(myBuffEnd, maxread);
if (rlen == 0) {
Link->setEtext("link read error or closed");
return -1;
}
if (rlen < 0) {
Link->setEtext("link timeout");
return 1;
}
}
myBuffEnd += rlen;
TRACE(REQ, "read " << rlen << " of " << blen << " bytes");
return 0;
}
/// How many bytes still fit into the buffer in a contiguous way
int XrdHttpProtocol::BuffAvailable() {
int r;
if (myBuffEnd >= myBuffStart)
r = myBuff->buff + myBuff->bsize - myBuffEnd;
else
r = myBuffStart - myBuffEnd;
if ((r < 0) || (r > myBuff->bsize)) {
TRACE(REQ, "internal error, myBuffAvailable: " << r << " myBuff->bsize " << myBuff->bsize);
abort();
}
return r;
}
/// How many bytes in the buffer
int XrdHttpProtocol::BuffUsed() {
int r;
if (myBuffEnd >= myBuffStart)
r = myBuffEnd - myBuffStart;
else
r = myBuff->bsize - (myBuffStart - myBuffEnd);
if ((r < 0) || (r > myBuff->bsize)) {
TRACE(REQ, "internal error, myBuffUsed: " << r << " myBuff->bsize " << myBuff->bsize);
abort();
}
return r;
}
/// How many bytes free in the buffer
int XrdHttpProtocol::BuffFree() {
return (myBuff->bsize - BuffUsed());
}
void XrdHttpProtocol::BuffConsume(int blen) {
if (blen > myBuff->bsize) {
TRACE(REQ, "internal error, BuffConsume(" << blen << ") smaller than buffsize");
abort();
}
if (blen > BuffUsed()) {
TRACE(REQ, "internal error, BuffConsume(" << blen << ") larger than BuffUsed:" << BuffUsed());
abort();
}
myBuffStart = myBuffStart + blen;
if (myBuffStart >= myBuff->buff + myBuff->bsize)
myBuffStart -= myBuff->bsize;
if (myBuffEnd >= myBuff->buff + myBuff->bsize)
myBuffEnd -= myBuff->bsize;
if (BuffUsed() == 0)
myBuffStart = myBuffEnd = myBuff->buff;
}
/// Get a pointer, valid for up to blen bytes from the buffer. Returns the n
/// of bytes that one is allowed to read
int XrdHttpProtocol::BuffgetData(int blen, char **data, bool wait) {
int rlen;
if (wait && (blen > BuffUsed())) {
TRACE(REQ, "BuffgetData: need to read " << blen - BuffUsed() << " bytes");
if (getDataOneShot(blen - BuffUsed(), true) < 0) return 0;
}
if (myBuffStart < myBuffEnd) {
rlen = min((long) blen, myBuffEnd - myBuffStart);
} else
rlen = min((long) blen, myBuff->buff + myBuff->bsize - myBuffStart);
*data = myBuffStart;
BuffConsume(rlen);
return rlen;
}
/// Send some data to the client
int XrdHttpProtocol::SendData(char *body, int bodylen) {
int r;
if (body && bodylen) {
TRACE(REQ, "Sending " << bodylen << " bytes");
if (ishttps) {
r = SSL_write(ssl, body, bodylen);
if (r <= 0) {
ERR_print_errors(sslbio_err);
return -1;
}
} else {
r = Link->Send(body, bodylen);
if (r <= 0) return -1;
}
}
return 0;
}
/// Sends a basic response. If the length is < 0 then it is calculated internally
/// Header_to_add is a set of header lines each CRLF terminated to be added to the header
/// Returns 0 if OK
int XrdHttpProtocol::SendSimpleResp(int code, char *desc, char *header_to_add, char *body, int bodylen) {
char outhdr[512];
char b[16];