| 160 | } |
| 161 | |
| 162 | SC::Result SC::HttpTestClient::postMultipart(AsyncEventLoop& loop, StringSpan url, StringSpan fieldName, |
| 163 | StringSpan fileName, StringSpan fileContent, TimeMs delay) |
| 164 | { |
| 165 | bodyDelay = delay; |
| 166 | eventLoop = &loop; |
| 167 | responseHasNoBody = false; |
| 168 | |
| 169 | uint16_t port; |
| 170 | HttpURLParser urlParser; |
| 171 | SC_TRY(urlParser.parse(url)); |
| 172 | SC_TRY_MSG(urlParser.protocol == "http", "Invalid protocol"); |
| 173 | // TODO: Make DNS Resolution asynchronous |
| 174 | char buffer[256]; |
| 175 | Span<char> ipAddress = {buffer}; |
| 176 | SC_TRY(SocketDNS::resolveDNS(urlParser.hostname, ipAddress)) |
| 177 | port = urlParser.port; |
| 178 | SocketIPAddress localHost; |
| 179 | SC_TRY(localHost.fromAddressPort({ipAddress, true, StringEncoding::Ascii}, port)); |
| 180 | SC_TRY(eventLoop->createAsyncTCPSocket(localHost.getAddressFamily(), clientSocket)); |
| 181 | |
| 182 | // Generate a unique boundary |
| 183 | StringSpan boundary = "----SCFormBoundary7MA4YWxkTrZu0gW"; |
| 184 | size_t boundaryLen = boundary.sizeInBytes(); |
| 185 | |
| 186 | { |
| 187 | GrowableBuffer<decltype(content)> gb = {content}; |
| 188 | |
| 189 | HttpStringAppend& sb = static_cast<HttpStringAppend&>(static_cast<IGrowableBuffer&>(gb)); |
| 190 | sb.clear(); |
| 191 | |
| 192 | // Build the multipart body first to know content length |
| 193 | // Body format: |
| 194 | // --boundary\r\n |
| 195 | // Content-Disposition: form-data; name="fieldName"; filename="fileName"\r\n |
| 196 | // Content-Type: application/octet-stream\r\n |
| 197 | // \r\n |
| 198 | // fileContent |
| 199 | // \r\n--boundary--\r\n |
| 200 | |
| 201 | // Calculate body size |
| 202 | size_t bodySize = 0; |
| 203 | bodySize += 2 + boundaryLen + 2; // --boundary\r\n |
| 204 | bodySize += 38 + fieldName.sizeInBytes() + 13 + fileName.sizeInBytes() + 3; // Content-Disposition: ...\r\n |
| 205 | bodySize += 40; // Content-Type: application/octet-stream\r\n |
| 206 | bodySize += 2; // \r\n |
| 207 | bodySize += fileContent.sizeInBytes(); // file content |
| 208 | bodySize += 4 + boundaryLen + 4; // \r\n--boundary--\r\n |
| 209 | |
| 210 | // Build HTTP headers |
| 211 | SC_TRY(sb.append("POST ")); |
| 212 | SC_TRY(sb.append(urlParser.path)); |
| 213 | SC_TRY(sb.append(" HTTP/1.1\r\n")); |
| 214 | SC_TRY(sb.append("User-agent: SC\r\n")); |
| 215 | SC_TRY(sb.append("Host: 127.0.0.1\r\n")); |
| 216 | SC_TRY(sb.append("Content-Type: multipart/form-data; boundary=")); |
| 217 | SC_TRY(sb.append(boundary)); |
| 218 | SC_TRY(sb.append("\r\n")); |
| 219 |
no test coverage detected