1 /*
2  *  Copyright (c) 2022, The OpenThread Authors.
3  *  All rights reserved.
4  *
5  *  Redistribution and use in source and binary forms, with or without
6  *  modification, are permitted provided that the following conditions are met:
7  *  1. Redistributions of source code must retain the above copyright
8  *     notice, this list of conditions and the following disclaimer.
9  *  2. Redistributions in binary form must reproduce the above copyright
10  *     notice, this list of conditions and the following disclaimer in the
11  *     documentation and/or other materials provided with the distribution.
12  *  3. Neither the name of the copyright holder nor the
13  *     names of its contributors may be used to endorse or promote products
14  *     derived from this software without specific prior written permission.
15  *
16  *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17  *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20  *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  *  POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /**
30  * @file
31  *   This file implements TCP/IPv6 socket extensions.
32  */
33 
34 #include "openthread-core-config.h"
35 
36 #if OPENTHREAD_CONFIG_TCP_ENABLE
37 
38 #include "tcp6_ext.hpp"
39 
40 #include "common/code_utils.hpp"
41 #include "common/error.hpp"
42 #include "common/locator_getters.hpp"
43 #include "common/log.hpp"
44 
45 namespace ot {
46 namespace Ip6 {
47 
48 RegisterLogModule("TcpExt");
49 
Initialize(void * aDataBuffer,size_t aCapacity)50 void TcpCircularSendBuffer::Initialize(void *aDataBuffer, size_t aCapacity)
51 {
52     mDataBuffer = static_cast<uint8_t *>(aDataBuffer);
53     mCapacity   = aCapacity;
54     ForceDiscardAll();
55 }
56 
Write(Tcp::Endpoint & aEndpoint,const void * aData,size_t aLength,size_t & aWritten,uint32_t aFlags)57 Error TcpCircularSendBuffer::Write(Tcp::Endpoint &aEndpoint,
58                                    const void    *aData,
59                                    size_t         aLength,
60                                    size_t        &aWritten,
61                                    uint32_t       aFlags)
62 {
63     Error    error     = kErrorNone;
64     size_t   bytesFree = GetFreeSpace();
65     size_t   writeIndex;
66     uint32_t flags = 0;
67     size_t   bytesUntilWrap;
68 
69     /*
70      * Handle the case where we don't have enough space to accommodate all of the
71      * provided data.
72      */
73     aLength = Min(aLength, bytesFree);
74     VerifyOrExit(aLength != 0);
75 
76     /*
77      * This is a "simplifying" if statement the removes an edge case from the logic
78      * below. It guarantees that a write to an empty buffer will never wrap.
79      */
80     if (mCapacityUsed == 0)
81     {
82         mStartIndex = 0;
83     }
84 
85     writeIndex = GetIndex(mStartIndex, mCapacityUsed);
86 
87     if ((aFlags & OT_TCP_CIRCULAR_SEND_BUFFER_WRITE_MORE_TO_COME) != 0 && aLength < bytesFree)
88     {
89         flags |= OT_TCP_SEND_MORE_TO_COME;
90     }
91 
92     bytesUntilWrap = mCapacity - writeIndex;
93     if (aLength <= bytesUntilWrap)
94     {
95         memcpy(&mDataBuffer[writeIndex], aData, aLength);
96         if (writeIndex == 0)
97         {
98             /*
99              * mCapacityUsed == 0 corresponds to the case where we're writing
100              * to an empty buffer. mCapacityUsed != 0 && writeIndex == 0
101              * corresponds to the case where the buffer is not empty and this is
102              * writing the first bytes that wrap.
103              */
104             uint8_t linkIndex;
105             if (mCapacityUsed == 0)
106             {
107                 linkIndex = mFirstSendLinkIndex;
108             }
109             else
110             {
111                 linkIndex = 1 - mFirstSendLinkIndex;
112             }
113             {
114                 otLinkedBuffer &dataSendLink = mSendLinks[linkIndex];
115 
116                 dataSendLink.mNext   = nullptr;
117                 dataSendLink.mData   = &mDataBuffer[writeIndex];
118                 dataSendLink.mLength = aLength;
119 
120                 LogDebg("Appending link %u (points to index %u, length %u)", static_cast<unsigned>(linkIndex),
121                         static_cast<unsigned>(writeIndex), static_cast<unsigned>(aLength));
122                 error = aEndpoint.SendByReference(dataSendLink, flags);
123             }
124         }
125         else
126         {
127             LogDebg("Extending tail link by length %u", static_cast<unsigned>(aLength));
128             error = aEndpoint.SendByExtension(aLength, flags);
129         }
130         VerifyOrExit(error == kErrorNone, aLength = 0);
131     }
132     else
133     {
134         const uint8_t *dataIndexable = static_cast<const uint8_t *>(aData);
135         size_t         bytesWrapped  = aLength - bytesUntilWrap;
136 
137         memcpy(&mDataBuffer[writeIndex], &dataIndexable[0], bytesUntilWrap);
138         memcpy(&mDataBuffer[0], &dataIndexable[bytesUntilWrap], bytesWrapped);
139 
140         /*
141          * Because of the "simplifying" if statement at the top, we don't
142          * have to worry about starting from an empty buffer in this case.
143          */
144         LogDebg("Extending tail link by length %u (wrapping)", static_cast<unsigned>(bytesUntilWrap));
145         error = aEndpoint.SendByExtension(bytesUntilWrap, flags | OT_TCP_SEND_MORE_TO_COME);
146         VerifyOrExit(error == kErrorNone, aLength = 0);
147 
148         {
149             otLinkedBuffer &wrappedDataSendLink = mSendLinks[1 - mFirstSendLinkIndex];
150 
151             wrappedDataSendLink.mNext   = nullptr;
152             wrappedDataSendLink.mData   = &mDataBuffer[0];
153             wrappedDataSendLink.mLength = bytesWrapped;
154 
155             LogDebg("Appending link %u (wrapping)", static_cast<unsigned>(1 - mFirstSendLinkIndex));
156             error = aEndpoint.SendByReference(wrappedDataSendLink, flags);
157             VerifyOrExit(error == kErrorNone, aLength = bytesUntilWrap);
158         }
159     }
160 
161 exit:
162     mCapacityUsed += aLength;
163     aWritten = aLength;
164     return error;
165 }
166 
HandleForwardProgress(size_t aInSendBuffer)167 void TcpCircularSendBuffer::HandleForwardProgress(size_t aInSendBuffer)
168 {
169     size_t bytesRemoved;
170     size_t bytesUntilWrap;
171 
172     OT_ASSERT(aInSendBuffer <= mCapacityUsed);
173     LogDebg("Forward progress: %u bytes in send buffer\n", static_cast<unsigned>(aInSendBuffer));
174     bytesRemoved   = mCapacityUsed - aInSendBuffer;
175     bytesUntilWrap = mCapacity - mStartIndex;
176 
177     if (bytesRemoved < bytesUntilWrap)
178     {
179         mStartIndex += bytesRemoved;
180     }
181     else
182     {
183         mStartIndex = bytesRemoved - bytesUntilWrap;
184         /* The otLinkedBuffer for the pre-wrap data is now empty. */
185         LogDebg("Pre-wrap linked buffer now empty: switching first link index from %u to %u\n",
186                 static_cast<unsigned>(mFirstSendLinkIndex), static_cast<unsigned>(1 - mFirstSendLinkIndex));
187         mFirstSendLinkIndex = 1 - mFirstSendLinkIndex;
188     }
189     mCapacityUsed = aInSendBuffer;
190 }
191 
GetFreeSpace(void) const192 size_t TcpCircularSendBuffer::GetFreeSpace(void) const { return mCapacity - mCapacityUsed; }
193 
ForceDiscardAll(void)194 void TcpCircularSendBuffer::ForceDiscardAll(void)
195 {
196     mStartIndex         = 0;
197     mCapacityUsed       = 0;
198     mFirstSendLinkIndex = 0;
199 }
200 
Deinitialize(void)201 Error TcpCircularSendBuffer::Deinitialize(void) { return (mCapacityUsed != 0) ? kErrorBusy : kErrorNone; }
202 
GetIndex(size_t aStart,size_t aOffsetFromStart) const203 size_t TcpCircularSendBuffer::GetIndex(size_t aStart, size_t aOffsetFromStart) const
204 {
205     size_t bytesUntilWrap;
206     size_t index;
207 
208     OT_ASSERT(aStart < mCapacity);
209     bytesUntilWrap = mCapacity - aStart;
210     if (aOffsetFromStart < bytesUntilWrap)
211     {
212         index = aStart + aOffsetFromStart;
213     }
214     else
215     {
216         index = aOffsetFromStart - bytesUntilWrap;
217     }
218 
219     return index;
220 }
221 
222 } // namespace Ip6
223 } // namespace ot
224 
225 #endif // OPENTHREAD_CONFIG_TCP_ENABLE
226