• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <https/PlainSocket.h>
20 #include <https/RunLoop.h>
21 #include <memory>
22 
23 #include <arpa/inet.h>
24 
25 struct STUNClient : public std::enable_shared_from_this<STUNClient> {
26     using Callback = std::function<void(int, const std::string &)>;
27 
28     explicit STUNClient(
29             std::shared_ptr<RunLoop> runLoop,
30             const sockaddr_in &addr,
31             Callback cb);
32 
33     void run();
34 
35 private:
36     static constexpr size_t kMaxUDPPayloadSize = 1536;
37     static constexpr size_t kMaxNumRetries = 5;
38 
39     static constexpr std::chrono::duration kTimeoutDelay =
40         std::chrono::seconds(1);
41 
42     std::shared_ptr<RunLoop> mRunLoop;
43     sockaddr_in mRemoteAddr;
44     Callback mCallback;
45 
46     std::shared_ptr<PlainSocket> mSocket;
47 
48     RunLoop::Token mTimeoutToken;
49     size_t mNumRetriesLeft;
50 
51     void onSendRequest();
52     void onReceiveResponse();
53 
54     void scheduleRequest();
55     void onTimeout();
56 };
57