1 /*
2  * Copyright (C) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef HTTP_SERVER_DEMO_H
17 #define HTTP_SERVER_DEMO_H
18 
19 #include <atomic>
20 #include <cerrno>
21 #include <cstdio>
22 #include <cstdlib>
23 #include <cstring>
24 #include <fcntl.h>
25 #include <functional>
26 #include <iostream>
27 #include <map>
28 #include <mutex>
29 #include <regex>
30 #include <securec.h>
31 #include <sstream>
32 #include <string>
33 #include <thread>
34 #include <unistd.h>
35 #include <vector>
36 #include <arpa/inet.h>
37 #include <condition_variable>
38 #include <netinet/in.h>
39 #include <netinet/tcp.h>
40 #include <sys/socket.h>
41 #include <sys/stat.h>
42 #include <sys/types.h>
43 #include <thread_pool.h>
44 #include "nocopyable.h"
45 
46 namespace OHOS {
47 namespace MediaAVCodec {
48 class HttpServerDemo {
49 public:
50     explicit HttpServerDemo();
51     virtual ~HttpServerDemo();
52     void StartServer();
53     void StartServer(int32_t port);
54     void StopServer();
55 
56 private:
57     void ServerLoopFunc();
58     static void FileReadFunc(int32_t connFd);
59 
60     static void CloseFd(int32_t &connFd, int32_t &fileFd, bool connCond, bool fileCond);
61     static void GetRange(const std::string &recvStr, int32_t &startPos, int32_t &endPos);
62     static void GetKeepAlive(const std::string &recvStr, int32_t &keep);
63     static void GetFilePath(const std::string &recvStr, std::string &path);
64 
65     static int32_t SendRequestSize(int32_t &connFd, int32_t &fileFd, const std::string &recvStr);
66     static int32_t SetKeepAlive(int32_t &connFd, int32_t &keepAlive, int32_t &keepIdle);
67 
68     std::atomic<bool> isRunning_ = false;
69     std::unique_ptr<std::thread> serverLoop_ = nullptr;
70     std::unique_ptr<ThreadPool> threadPool_ = nullptr;
71     int32_t listenFd_ = 0;
72 };
73 } // namespace MediaAVCodec
74 } // namespace OHOS
75 
76 #endif