1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <cstdint>
20 #include <map>
21 #include <string>
22 #include <string_view>
23 
24 struct HTTPRequestResponse {
25     explicit HTTPRequestResponse();
26     virtual ~HTTPRequestResponse() = default;
27 
28     HTTPRequestResponse(const HTTPRequestResponse &) = delete;
29     HTTPRequestResponse &operator=(const HTTPRequestResponse &) = delete;
30 
31     int setTo(const uint8_t *data, size_t size);
32     int initCheck() const;
33 
34     bool getHeaderField(std::string_view key, std::string *value) const;
35 
36     size_t getContentLength() const;
37 
38 protected:
39     virtual bool parseRequestResponseLine(const std::string &line) = 0;
40 
41 private:
42     struct CaseInsensitiveCompare {
operatorHTTPRequestResponse::CaseInsensitiveCompare43         bool operator()(const std::string &a, const std::string &b) const {
44             return strcasecmp(a.c_str(), b.c_str()) < 0;
45         }
46     };
47 
48     int mInitCheck;
49 
50     size_t mContentLength;
51 
52     std::map<std::string, std::string, CaseInsensitiveCompare> mHeaders;
53 };
54 
55 struct HTTPRequest : public HTTPRequestResponse {
56     std::string getMethod() const;
57     std::string getPath() const;
58     std::string getVersion() const;
59 
60 protected:
61     bool parseRequestResponseLine(const std::string &line) override;
62 
63 private:
64     std::string mMethod;
65     std::string mPath;
66     std::string mVersion;
67 };
68 
69 struct HTTPResponse : public HTTPRequestResponse {
70     std::string getVersion() const;
71     int32_t getStatusCode() const;
72     std::string getStatusMessage() const;
73 
74 protected:
75     bool parseRequestResponseLine(const std::string &line) override;
76 
77 private:
78     std::string mVersion;
79     std::string mStatusMessage;
80     int32_t mStatusCode;
81 };
82 
83