File: ap_http_response.cpp

package info (click to toggle)
gogglesmm 1.2.5-6
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 16,812 kB
  • sloc: cpp: 231,960; ansic: 893; xml: 222; makefile: 33
file content (783 lines) | stat: -rw-r--r-- 17,559 bytes parent folder | download | duplicates (2)
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
/*******************************************************************************
*                         Goggles Audio Player Library                         *
********************************************************************************
*           Copyright (C) 2010-2021 by Sander Jansen. All Rights Reserved      *
*                               ---                                            *
* This program is free software: you can redistribute it and/or modify         *
* it under the terms of the GNU General Public License as published by         *
* the Free Software Foundation, either version 3 of the License, or            *
* (at your option) any later version.                                          *
*                                                                              *
* This program is distributed in the hope that it will be useful,              *
* but WITHOUT ANY WARRANTY; without even the implied warranty of               *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                *
* GNU General Public License for more details.                                 *
*                                                                              *
* You should have received a copy of the GNU General Public License            *
* along with this program.  If not, see http://www.gnu.org/licenses.           *
********************************************************************************/
#include "ap_defs.h"
#include "ap_utils.h"
#include "ap_buffer_base.h"
#include "ap_buffer_io.h"
#include "ap_http_response.h"

#ifdef HAVE_ZLIB
#include <zlib.h>
#endif


using namespace ap;

namespace ap {


// apparently defined as macros by glibc/gcc.
#undef major
#undef minor

#ifdef HAVE_ZLIB

struct ZIO {
  z_stream stream;

  ZIO() {
    memset(&stream,0,sizeof(stream));
    }
  };

#endif


HttpIO::HttpIO() : BufferIO(4096), z(nullptr) {
  }

HttpIO::HttpIO(FXIO * dev) : BufferIO(dev,4096), z(nullptr) {
  }

HttpIO::~HttpIO() {
#ifdef HAVE_ZLIB
  if (z) {
    inflateEnd(&z->stream);
    delete z;
    z=nullptr;
    }
#endif
  }



#ifdef HAVE_ZLIB
FXival HttpIO::gzip_read(FXString & data,FXival & bytes_written,FXival bytes_available) {
  const FXint blocksize = 4096;

  FXival bytes_consumed = 0;

  if (dir!=DirWrite) {

    // Initialize inflater on first call
    if (z==nullptr) {
      z = new ZIO;
      if (inflateInit2(&z->stream,15+16)!=Z_OK) {
        delete z;
        return FXIO::Error;
        }
      bytes_written = 0;
      data.length(blocksize);
      }

    // Read until we consumed all available bytes
    while(bytes_available) {

      // update buffers
      z->stream.next_in   = rdptr;
      z->stream.avail_in  = FXMIN(bytes_available,wrptr-rdptr);
      z->stream.next_out  = (FXuchar*)&data[bytes_written];
      z->stream.avail_out = data.length()-bytes_written;

      // inflate
      int zerror = inflate(&z->stream,Z_NO_FLUSH);

      bytes_consumed  += (z->stream.next_in - rdptr);
      bytes_available -= (z->stream.next_in - rdptr);
      bytes_written   += ((data.length()-bytes_written) - z->stream.avail_out);

      // update read ptr
      rdptr = z->stream.next_in;

      // check result of inflate
      if (zerror!=Z_OK) {
        if (zerror==Z_STREAM_END) {
          inflateEnd(&z->stream);
          data.length(bytes_written);
          delete z;
          z=nullptr;
          return bytes_consumed;
          }
        else if (zerror==Z_BUF_ERROR) {

          if (bytes_available==0)
            return bytes_consumed;

          if (z->stream.avail_out==0)
            data.length(data.length()+blocksize);

          const FXival bytes_in_buffer = wrptr-rdptr;
          if (z->stream.avail_in==0 && (bytes_available>bytes_in_buffer)) {
            if (readBuffer()<=(FXuval)bytes_in_buffer) {
              inflateEnd(&z->stream);
              delete z;
              z=nullptr;
              return FXIO::Error;
              }
            }

          }
        else {
          inflateEnd(&z->stream);
          delete z;
          z=nullptr;
          return FXIO::Error;
          }
        }
      }
    return bytes_consumed;
    }
  return FXIO::Error;
  }
#else
FXival HttpIO::gzip_read(FXString &,FXival &,FXival) {
  return FXIO::Error;
  }
#endif




FXival HttpIO::read(FXString & str,FXival n) {
  if (0<n) {
    FXint pos = str.length();
    str.length(pos+n);
    return readBlock(&str[pos],n);
    }
  return 0;
  }

FXbool HttpIO::readHeader(FXString & header,FXbool single) {
  FXbool cnl=false; // continue next line
  FXuchar * p;
  do {

    /* check if we continue on the next line */
    if (cnl) {
test_cnl:
      FXASSERT(rdptr<wrptr);
      if (!(*rdptr=='\t' || *rdptr==' ')) {
        return true;
        }
      cnl=false;
      }

    /* find end of line \r\n */
    for (p=rdptr;p<wrptr;p++) {
      if (*p=='\n') {

        if (*(p-1)=='\r')
          header.append((const FXchar*)rdptr,p-rdptr-1);
        else
          header.append((const FXchar*)rdptr,p-rdptr);

        rdptr=p+1;

        /* HTTP status or end of header section */
        if (single || header.length()==0) {
          dir = (wrptr>rdptr) ? DirRead : DirNone;
          return true;
          }

        cnl=true;
        if (wrptr>rdptr)
          goto test_cnl;

        break;
        }
      }

    /* consume what we have so far */
    if (p>rdptr) {

      if (*p=='\r')
        header.append((const FXchar*)rdptr,p-rdptr-1);
      else
        header.append((const FXchar*)rdptr,p-rdptr);

      rdptr=p;
      }
    }
  while(readBuffer());
  return false;
  }


FXbool HttpIO::write(const FXString & str) {
  //fxmessage("[%d]%s\n",str.length(),str.text());
  FXint n = writeBlock(str.text(),str.length());
  if (n==-1) return false;
  FXASSERT(n==str.length());
  return flush();
  }



FXint HttpStatus::type() const {
  if (code>=100 && code<200)
    return HTTP_RESPONSE_INFORMATIONAL;
  else if (code>=200 && code<300)
    return HTTP_RESPONSE_SUCCESS;
  else if (code>=300 && code<400)
    return HTTP_RESPONSE_REDIRECT;
  else if (code>=400 && code<500)
    return HTTP_RESPONSE_CLIENT_ERROR;
  else if (code>=500 && code<600)
    return HTTP_RESPONSE_SERVER_ERROR;
  else
    return HTTP_RESPONSE_FAILED;
  }


// HttpHeader

FXint HttpHeader::parseToken(const FXString & str,FXint & p){
  FXchar c;
  FXint  s=p;
  while(p<str.length()){
    c=str[p];
    if (!Ascii::isAlphaNumeric(c)) {
      switch(c) {
        case  '!':
        case  '#':
        case  '$':
        case  '%':
        case  '&':
        case '\'':
        case  '*':
        case  '+':
        case  '-':
        case  '.':
        case  '^':
        case  '_':
        case  '`':
        case  '|':
        case  '~': break;
        default  : return p-s; break;
        }
      }
    p++;
    }
  return p-s;
  }

FXint HttpHeader::parseQuotedString(const FXString & str,FXint & p){
  FXint s=p;
  while(p<str.length()) {
    if (str[p]=='\"' && str[p-1]!='\\')
      return p-s;
    p++;
    }
  return 0;
  }


HttpMediaType::HttpMediaType() {}

HttpMediaType::HttpMediaType(const FXString & str,FXuint opts) {
  parse(str,opts);
  }

FXbool HttpMediaType::parse(const FXString & str,FXuint opts) {
  FXint s,p=0,ks,kp;

  // parse the field name
  if (opts&ParseFieldName)
    p=str.find(':')+1;

  // white space
  while(str[p]==' '||str[p]=='\t') p++;
  s=p;

  // "type/"
  if (parseToken(str,p)==0 || str[p++]!='/')
    return false;

  // "subtype"
  if (parseToken(str,p)==0)
    return false;

  // Get mime
  mime = str.mid(s,p-s).lower(); // mime is case insensitive, force lower case

  // Parameters
  while(p<str.length()) {

    // white space
    while(str[p]==' '||str[p]=='\t') p++;

    // check for parameter separator
    if (str[p++]!=';') break;

    // eat space
    while(str[p]==' '||str[p]=='\t') p++;

    // get key and =
    ks=kp=p;
    if (parseToken(str,kp)==0 || str[kp]!='=')
      break;
    p=kp+1;

    // get the value
    if (str[p]=='"') {
      s=p;
      if (parseQuotedString(str,p)==0)
        break;

      parameters.insert(str.mid(ks,kp-ks),
                        FXString::unescape(str.mid(s,p-s),'\"','\"'));
      p++;
      }
    else {
      s=p;
      if (parseToken(str,p)==0)
        break;

      parameters.insert(str.mid(ks,kp-ks),
                        str.mid(s,p-s));
      p++;
      }
    }
  return true;
  }


HttpContentRange::HttpContentRange(const FXString & str,FXuint opts) : first(-1),last(-1),length(-1) {
  parse(str,opts);
  }

FXbool HttpContentRange::parse(const FXString & str,FXuint opts) {
  FXint s,p=0;

  // parse the field name
  if (opts&ParseFieldName)
    p=str.find(':')+1;

  // white space
  while(str[p]==' '||str[p]=='\t') p++;

  // Make sure ranges are in bytes
  if (str[p]!='b' || str[p+1]!='y' || str[p+2]!='t' || str[p+3]!='e' || str[p+4]!='s' || str[p+5]!=' ')
    return false;
  p+=6;

  // first and last byte pos
  if (str[p]!='*') {
    s=p;
    while(Ascii::isDigit(str[p])) p++;

    if (str[p]!='-')
      return false;

    first = str.mid(s,p-s).toLong();

    s=++p;
    while(Ascii::isDigit(str[p])) p++;
    if (str[p]!='/')
      goto failed;

    last = str.mid(s,p-s).toLong();

    if (last<first)
      goto failed;
    }
  p++;

  // Length
  if (str[p]!='*') {
    s=p;
    while(Ascii::isDigit(str[p])) p++;
    length = str.mid(s,p-s).toLong();

    if (last!=-1 && length<last)
      goto failed;
    }

  return true;
failed:
  length=first=last=-1;
  return false;
  }




HttpResponse::HttpResponse() :
  content_length(-1),
  content_remaining(-1),
  chunk_remaining(-1),
  flags(0){
  }

HttpResponse::~HttpResponse() {
  clear();
  }

void HttpResponse::clear() {
  flags=0;
  content_length=-1;
  content_remaining=-1;
  chunk_remaining=-1;
  clear_headers();
  }


// Store parsed header into headers.
void HttpResponse::insert_header(const FXString & header) {
  FXString key   = header.before(':').lower();
  FXString value = header.after(':').trim();
  FXint p = headers.find(key);
  if (p!=-1)
    headers.data(p).append(","+value);
  else
    headers[key] = value;
  }

void HttpResponse::clear_headers() {
  headers.clear();
  }

void HttpResponse::check_headers() {
#ifdef DEBUG
  FXbool firstline = true;
  for (FXint pos=0;pos<headers.no();pos++) {
    if (!headers.key(pos).empty()) {
      if (firstline) {
        fxmessage("[http] %s: %s\n",headers.key(pos).text(),headers.data(pos).text());
        firstline=false;
        }
      else {
        fxmessage("       %s: %s\n",headers.key(pos).text(),headers.data(pos).text());
        }
      }
    }
#endif
  FXint p;

  p = headers.find("content-length");
  if (p!=-1) content_length = content_remaining = headers.data(p).toInt();


  p = headers.find("content-encoding");
  if ((p!=-1) && headers.data(p).contains("gzip"))
    flags|=ContentEncodingGZip;

  p = headers.find("transfer-encoding");
  if (p!=-1 && headers.data(p).contains("chunked"))
    flags|=ChunkedResponse;

  if (status.major==1 && status.minor==1) {
    if (headers["connection"].contains("close"))
      flags|=ConnectionClose;
    }
  else {
    if (!headers["connection"].lower().contains("keep-alive"))
      flags|=ConnectionClose;
    }
  }

// Read a chunk header and set the chunksize
FXbool HttpResponse::read_chunk_header(FXint & chunksize) {
  FXString header;
  FXchar   clrf[2];

  // We've read a previous chunk
  if (chunksize==0) {
    if (io.readBlock(clrf,2)!=2 || clrf[0]!='\r' || clrf[1]!='\n') {
      GM_DEBUG_PRINT("[http] missing line feed: %c%c\n",clrf[0],clrf[1]);
      return false;
      }
    }

  if (io.readHeader(header,true)) {
    if (header.scan("%x",&chunksize)==1) {
      return true;
      }
    }
  return false;
  }


// Read status line and set status.
FXbool HttpResponse::read_status() {
  FXString header;
  if (io.readHeader(header,true)) {
    if (header.scan("HTTP/%d.%d %d",&status.major,&status.minor,&status.code)==3){
      GM_DEBUG_PRINT("[http] HTTP/%d.%d %d\n",status.major,status.minor,status.code);
      return true;
      }
    else if (header.scan("ICY %d",&status.code)==1){
      GM_DEBUG_PRINT("[http] ICY %d\n",status.code);
      return true;
      }
    else {
      GM_DEBUG_PRINT("[http] Failed to parse http header: %s\n",header.text());
      }
    }
  return false;
  }



// Read the full message body non-chunked
FXString HttpResponse::read_body() {
  FXString content;
  if (content_length==0) {
    return FXString::null;
    }
  else if (content_length>0) {
    content_remaining=0;
    if (flags&ContentEncodingGZip) {
#ifdef HAVE_ZLIB
      FXival bytes_written=0;
      if (io.gzip_read(content,bytes_written,content_length)!=content_length)
        return FXString::null;
#else
        return FXString::null;
#endif
      }
    else {
      if (io.read(content,content_length)!=content_length)
        return FXString::null;
      }
    }
  else {
    FXival n,c=0;
    const FXival BLOCK = 4096;
    while((n=io.read(content,BLOCK))==BLOCK) c+=n;
    if (0<n) c+=n;
    content.length(c);
    }
  return content;
  }

// Read the full message body chunked
FXString HttpResponse::read_body_chunked() {
  FXString header;
  FXString content;
  FXint    chunksize=-1;
#ifdef HAVE_ZLIB
  FXival   bytes_written=0;
#endif

  // Reading all content
  if (content_remaining>0)
    content_remaining=0;

  if (read_chunk_header(chunksize)) {

    while(chunksize) {

      if (flags&ContentEncodingGZip) {
#ifdef HAVE_ZLIB
        if (io.gzip_read(content,bytes_written,chunksize)!=chunksize) {
          GM_DEBUG_PRINT("[http] read_body_chunked() - failed reading chunksize %d\n",chunksize);
          goto fail;
          }
#else
        goto fail;
#endif
        }
      else {
        if (io.read(content,chunksize)!=chunksize) {
          GM_DEBUG_PRINT("[http] read_body_chunked() - failed reading chunksize %d\n",chunksize);
          goto fail;
          }
        }

      // Set to zero so read_chunk_header will check for crlf
      chunksize=0;

      // Next chunk header
      if (!read_chunk_header(chunksize))
        goto fail;
      }

    GM_DEBUG_PRINT("[http] done with chunks...\n");

    // Trailing Headers
    while(io.readHeader(header)) {

      // empty header indicates end of headers
      if (header.empty())
        break;

      insert_header(header);

      header.clear();
      }

    return content;
    }
fail:
  return FXString::null;
  }




FXival HttpResponse::read_body(void*ptr,FXival len) {
  if (content_remaining >= 0) {
    FXchar * data = (FXchar*)ptr;
    FXival n = io.readBlock(data,FXMIN(content_remaining,len));
    if (n>0) content_remaining-=n;
    return n;
    }
  else {
    return io.readBlock((FXchar*)ptr,len);
    }
  }


FXival HttpResponse::read_body_chunked(void * ptr,FXival len) {
  FXchar * data = (FXchar*)ptr;
  FXString header;
  FXival   nbytes=0;
  while(len) {

    if (chunk_remaining<=0) {

      if (!read_chunk_header(chunk_remaining))
        return -1;

      if (chunk_remaining==0) {

        // Trailing Headers
        while(io.readHeader(header)) {

          // empty header indicates end of headers
          if (header.empty())
            break;

          insert_header(header);

          header.clear();
          }
        return nbytes;
        }
      }

    FXival n = io.readBlock(data+nbytes,FXMIN(len,chunk_remaining));
    if (n<=0) return nbytes;
    chunk_remaining-=n;
    nbytes+=n;
    len-=n;
    }
  return nbytes;
  }


// Parse the response status and headers. Returns true if succesful
FXint HttpResponse::parse() {
  FXString header;
  if (read_status()) {
    while(io.readHeader(header)) {
      // empty header indicates end of headers
      if (header.empty()) {
        check_headers();
        return status.type();
        }
      insert_header(header);
      header.clear();
      }
    }
  return HTTP_RESPONSE_FAILED;
  }

// Read the full message body into string
FXString HttpResponse::body() {
  if (flags&HeadRequest)
    return FXString::null;
  else if (flags&ChunkedResponse)
    return read_body_chunked();
  else
    return read_body();
  }

FXString HttpResponse::textBody() {
  HttpMediaType media;

  if (getContentType(media) && media.parameters.has("charset")) {
    const FXTextCodec * codec = ap_get_textcodec(media.parameters["charset"]);
    if (codec) return codec->mb2utf(body());

    discard();
    }
  else {
    return body();
    }
  return FXString::null;
  }


FXival HttpResponse::readBody(void * ptr,FXival len) {
  if (flags&HeadRequest)
    return 0;
  else if (flags&ChunkedResponse)
    return read_body_chunked(ptr,len);
  else
    return read_body(ptr,len);
  }


void HttpResponse::discard() {
  if (!(flags&ConnectionClose) && !(flags&HeadRequest)) {
    FXchar b[1024];
    while(readBody(b,1024)==1024) ;
    }
  }

FXString HttpResponse::getHeader(const FXString & key) const {
  return headers[key];
  }


FXint HttpResponse::getContentLength() const {
  return content_length;
  }

FXbool HttpResponse::getContentType(HttpMediaType & media) const {
  return media.parse(headers["content-type"]);
  }

FXbool HttpResponse::getContentRange(HttpContentRange & range) const {
  return range.parse(headers["content-range"]);
  }



FXbool HttpResponse::eof() {
  if (content_remaining>=0)
    return (content_remaining==0);
  else
    return io.eof();
  }


// Return whether zlib support is available
FXbool HttpResponse::has_zlib_support() {
#ifdef HAVE_ZLIB
  return true;
#else
  return false;
#endif
  }


}