• 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/RunLoop.h>
20 
21 #include <openssl/bio.h>
22 #include <openssl/ssl.h>
23 
24 #include <functional>
25 #include <memory>
26 #include <netinet/in.h>
27 #include <optional>
28 #include <vector>
29 
30 #include <srtp2/srtp.h>
31 
32 struct RTPSocketHandler;
33 
34 struct DTLS : public std::enable_shared_from_this<DTLS> {
35     static void Init();
36 
37     enum class Mode {
38         ACCEPT,
39         CONNECT
40     };
41 
42     explicit DTLS(
43             std::shared_ptr<RTPSocketHandler> handler,
44             Mode mode,
45             std::shared_ptr<X509> certificate,
46             std::shared_ptr<EVP_PKEY> key,
47             const std::string &remoteFingerprint,
48             bool useSRTP);
49 
50     ~DTLS();
51 
52     void connect(const sockaddr_storage &remoteAddr);
53     void inject(const uint8_t *data, size_t size);
54 
55     size_t protect(void *data, size_t size, bool isRTP);
56     size_t unprotect(void *data, size_t size, bool isRTP);
57 
58     // Returns -EAGAIN if no data is currently available.
59     ssize_t readApplicationData(void *data, size_t size);
60 
61     ssize_t writeApplicationData(const void *data, size_t size);
62 
63 private:
64     enum class State {
65         UNINITIALIZED,
66         CONNECTING,
67         CONNECTED,
68 
69     } mState;
70 
71     std::weak_ptr<RTPSocketHandler> mHandler;
72     Mode mMode;
73     std::string mRemoteFingerprint;
74     bool mUseSRTP;
75 
76     SSL_CTX *mCtx;
77     SSL *mSSL;
78 
79     // These are owned by the SSL object.
80     BIO *mBioR, *mBioW;
81 
82     sockaddr_storage mRemoteAddr;
83 
84     srtp_t mSRTPInbound, mSRTPOutbound;
85 
86     static int OnVerifyPeerCertificate(int ok, X509_STORE_CTX *ctx);
87 
88     void doTheThing(int res);
89     void queueOutputDataFromDTLS();
90     void tryConnecting();
91 
92     void getKeyingMaterial();
93 
94     static void CreateSRTPSession(
95             srtp_t *session,
96             const std::string &keyAndSalt,
97             srtp_ssrc_type_t direction);
98 
99     bool useCertificate(std::shared_ptr<X509> certificate);
100     bool usePrivateKey(std::shared_ptr<EVP_PKEY> key);
101 };
102