• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifdef IPPOVERUSB_ENABLE
17 #include "print_http_request_process.h"
18 #include <cmath>
19 #include "print_log.h"
20 #include "print_ipp_over_usb_util.h"
21 #include "usb_errors.h"
22 
23 namespace OHOS::Print {
24 using namespace std;
25 using namespace OHOS;
26 using namespace OHOS::USB;
27 using namespace httplib;
28 
PrintHttpRequestProcess()29 PrintHttpRequestProcess::PrintHttpRequestProcess()
30 {}
31 
~PrintHttpRequestProcess()32 PrintHttpRequestProcess::~PrintHttpRequestProcess()
33 {}
34 
PrintOperation(Operation operation)35 std::string PrintHttpRequestProcess::PrintOperation(Operation operation)
36 {
37     if (operation == Operation::Get_Printer_Attributes) {
38         return HTTP_OPERATION_GET_ATTR;
39     } else if (operation == Operation::Send_Document) {
40         return HTTP_OPERATION_SEND_DOC;
41     } else {
42         return HTTP_OPERATION_COMMON;
43     }
44 }
45 
NeedOffset(const std::vector<uint8_t> & readTempBuffer)46 size_t PrintHttpRequestProcess::NeedOffset(const std::vector<uint8_t> &readTempBuffer)
47 {
48     size_t readSize = readTempBuffer.size();
49     size_t reqindex = 0;
50     bool checkNeedOffset = (readSize > HTTP_COMMON_CONST_VALUE_25 && readTempBuffer[INDEX_0] == HTTP_RESPONSE_H &&
51         readTempBuffer[INDEX_1] == HTTP_RESPONSE_T && readTempBuffer[INDEX_2] == HTTP_RESPONSE_T &&
52         readTempBuffer[INDEX_3] == HTTP_RESPONSE_P &&
53         readTempBuffer[INDEX_4] == HTTP_RESPONSE_VERSION_SPLIT_GANG &&
54         readTempBuffer[INDEX_5] == HTTP_MSG_CHAR_1 &&
55         readTempBuffer[INDEX_6] == HTTP_MSG_CHAR_2E &&
56         readTempBuffer[INDEX_7] == HTTP_MSG_CHAR_1 &&
57         readTempBuffer[INDEX_8] == HTTP_MSG_CHAR_20 &&
58         readTempBuffer[INDEX_9] == HTTP_MSG_CHAR_1 &&
59         readTempBuffer[INDEX_10] == HTTP_MSG_CHAR_0 &&
60         readTempBuffer[INDEX_11] == HTTP_MSG_CHAR_0);
61     if (checkNeedOffset) {
62         PRINT_HILOGD("include HTTP/1.1 100");
63         reqindex = HTTP_COMMON_CONST_VALUE_25;
64     }
65     return reqindex;
66 }
67 
RecordBufByOperation(Operation operation,size_t requestId,const std::vector<uint8_t> & tmVector)68 void PrintHttpRequestProcess::RecordBufByOperation(Operation operation, size_t requestId,
69     const std::vector<uint8_t> &tmVector)
70 {
71     if (operation == Operation::Send_Document) {
72         std::lock_guard<std::mutex> mtx_locker(mutexSendDoc);
73         if (readSendDocBufMap.find(requestId) == readSendDocBufMap.end()) {
74             readSendDocBufMap[requestId] = tmVector;
75         }
76     } else {
77         if (reqIdOperaIdMap[requestId] == HTTP_REQUEST_GET_ATTR)  {
78             std::lock_guard<std::mutex> mtx_locker(mutexGetAttr);
79             if (readGetAttrBufMap.find(requestId) == readGetAttrBufMap.end()) {
80                 readGetAttrBufMap[requestId] = tmVector;
81             }
82         } else {
83             std::lock_guard<std::mutex> mtx_locker(mutexCommon);
84             if (readBufMap.find(requestId) == readBufMap.end()) {
85                 readBufMap[requestId] = tmVector;
86             }
87         }
88     }
89 }
90 
GetContentLength(const std::vector<uint8_t> & readTempBuffer,size_t index,bool & findContentLength,size_t & contentLength)91 void PrintHttpRequestProcess::GetContentLength(const std::vector<uint8_t> &readTempBuffer, size_t index,
92     bool &findContentLength, size_t &contentLength)
93 {
94     size_t readSize = readTempBuffer.size();
95     if ((index + HTTP_COMMON_CONST_VALUE_14) < readSize) {
96         std::string tmpStr = "";
97         for (size_t offset = 0; offset < HTTP_COMMON_CONST_VALUE_14; offset++) {
98             tmpStr += readTempBuffer[index + offset];
99         }
100         if (tmpStr == HTTP_CONTENT_LENGTH) {
101             findContentLength = true;
102             std::string lenStr = "";
103             size_t lenIndex = index + HTTP_COMMON_CONST_VALUE_14 + HTTP_COMMON_CONST_VALUE_2;
104             while (lenIndex < readSize - 1 && (!(readTempBuffer[lenIndex] == HTTP_SPLIT_R_CODE &&
105                                                   readTempBuffer[lenIndex + INDEX_1] == HTTP_SPLIT_N_CODE))) {
106                 lenStr += readTempBuffer[lenIndex];
107                 lenIndex++;
108             }
109             contentLength = static_cast<size_t>(std::stoi(lenStr));
110             PRINT_HILOGD("contentLength = %{public}s,  %{public}lu", lenStr.c_str(), contentLength);
111         }
112     }
113 }
114 
DumpRespIdCode(const std::vector<uint8_t> & readTempBuffer,Operation operation,size_t begin,size_t maxSize)115 void PrintHttpRequestProcess::DumpRespIdCode(const std::vector<uint8_t> &readTempBuffer,
116     Operation operation, size_t begin, size_t maxSize)
117 {
118     for (size_t i = begin; i < (begin + HTTP_COMMON_CONST_VALUE_8) && i < maxSize; i++) {
119         PRINT_HILOGD("operation:%{public}s, readTempBuffer: %{public}x",
120             PrintOperation(operation).c_str(), readTempBuffer[i]);
121     }
122 }
123 
CheckLineEnd(std::vector<uint8_t> & readTempBuffer,size_t index)124 bool PrintHttpRequestProcess::CheckLineEnd(std::vector<uint8_t> &readTempBuffer, size_t index)
125 {
126     size_t readSize = readTempBuffer.size();
127     if ((index + HTTP_COMMON_CONST_VALUE_3) < readSize && readTempBuffer[index] == HTTP_SPLIT_R_CODE &&
128         readTempBuffer[index + INDEX_1] == HTTP_SPLIT_N_CODE && readTempBuffer[index + INDEX_2] == HTTP_SPLIT_R_CODE &&
129         readTempBuffer[index + INDEX_3] == HTTP_SPLIT_N_CODE) {
130         return true;
131     }
132     return false;
133 }
134 
CalculateRequestId(std::vector<uint8_t> & readTempBuffer,size_t index,Operation operation)135 size_t PrintHttpRequestProcess::CalculateRequestId(
136     std::vector<uint8_t> &readTempBuffer, size_t index, Operation operation)
137 {
138     size_t readSize = readTempBuffer.size();
139     DumpRespIdCode(readTempBuffer, operation, index + HTTP_COMMON_CONST_VALUE_4, readSize);
140     return readTempBuffer[index + HTTP_COMMON_CONST_VALUE_8] *
141                pow(HTTP_COMMON_CONST_VALUE_10, HTTP_COMMON_CONST_VALUE_3) +
142            readTempBuffer[index + HTTP_COMMON_CONST_VALUE_9] *
143                pow(HTTP_COMMON_CONST_VALUE_10, HTTP_COMMON_CONST_VALUE_2) +
144            readTempBuffer[index + HTTP_COMMON_CONST_VALUE_10] * HTTP_COMMON_CONST_VALUE_10 +
145            readTempBuffer[index + HTTP_COMMON_CONST_VALUE_11];
146 }
147 
CalculateFileDataBeginIndex(size_t index,Operation operation)148 size_t PrintHttpRequestProcess::CalculateFileDataBeginIndex(size_t index, Operation operation)
149 {
150     size_t fileDataBeginIndex = index + INDEX_4;
151     PRINT_HILOGD("operation:%{public}s, fileDataBeginIndex = %{public}lu",
152         PrintOperation(operation).c_str(), fileDataBeginIndex);
153     return fileDataBeginIndex;
154 }
155 
ProcessDataFromDevice(Operation operation)156 bool PrintHttpRequestProcess::ProcessDataFromDevice(Operation operation)
157 {
158     std::vector<uint8_t> readTempBuffer;
159     int32_t readFromUsbRes =
160         DelayedSingleton<PrintUsbManager>::GetInstance()->BulkTransferRead(devName, operation, readTempBuffer);
161     if (readFromUsbRes == EORROR_HDF_DEV_ERR_NO_DEVICE) {
162         PRINT_HILOGE("HDF_DEV_ERR_NO_DEVICE, The device module has no device");
163         deviceOpen = false;
164         return true;
165     }
166     size_t readSize = readTempBuffer.size();
167     if (readSize > 0 && readFromUsbRes == UEC_OK) {
168         PRINT_HILOGD("operation:%{public}s, readSize = %{public}lu", PrintOperation(operation).c_str(), readSize);
169         size_t reqindex = NeedOffset(readTempBuffer);
170         size_t requestId = 0;
171         std::vector<uint8_t> tmVector;
172         bool findRequestId = false;
173         bool findContentLength = false;
174         size_t contentLength = 0;
175         size_t fileDataBeginIndex = 0;
176         // 解析出报文中的RequestId 和 Content-Length
177         for (size_t index = reqindex; index < readSize; index++) {
178             bool findLineEnd = (!findRequestId && CheckLineEnd(readTempBuffer, index));
179             if (findLineEnd) {
180                 fileDataBeginIndex = CalculateFileDataBeginIndex(index, operation);
181                 findRequestId = true;
182             }
183             if (!findContentLength) {
184                 GetContentLength(readTempBuffer, index, findContentLength, contentLength);
185             }
186             tmVector.push_back(readTempBuffer[index]);
187         }
188         // 一次读取的报文长度小于 Content-Length字段的值则需再读取一次
189         while (tmVector.size() < readSize + contentLength) {
190             GetAttrAgain(operation, tmVector);
191         }
192         if (fileDataBeginIndex > HTTP_COMMON_CONST_VALUE_4) {
193             requestId = CalculateRequestId(tmVector, fileDataBeginIndex - HTTP_COMMON_CONST_VALUE_4, operation);
194         }
195         PRINT_HILOGD("operation:%{public}s requestId: %{public}lu ", PrintOperation(operation).c_str(), requestId);
196         RecordBufByOperation(operation, requestId, tmVector);
197         return true;
198     }
199     return false;
200 }
201 
GetAttrAgain(Operation operation,std::vector<uint8_t> & tmVector)202 void PrintHttpRequestProcess::GetAttrAgain(Operation operation, std::vector<uint8_t> &tmVector)
203 {
204     PRINT_HILOGD("GetAttr again");
205     std::vector<uint8_t> readBuffer;
206     int32_t readFromUsbRes =
207         DelayedSingleton<PrintUsbManager>::GetInstance()->BulkTransferRead(devName, operation, readBuffer);
208     size_t readSize = readBuffer.size();
209     if (readSize > 0 && readFromUsbRes == UEC_OK) {
210         PRINT_HILOGD("GetAttr again readSize = %{public}lu", readSize);
211         for (size_t index = 0; index < readSize; index++) {
212             tmVector.push_back(readBuffer[index]);
213         }
214     }
215 }
216 
StartReadSendDocDataFromPrinterLooper()217 void PrintHttpRequestProcess::StartReadSendDocDataFromPrinterLooper()
218 {
219     PRINT_HILOGD("StartReadSendDocDataFromPrinterLooper");
220     while (deviceOpen && needReadSendDoc) {
221         if (ProcessDataFromDevice(Operation::Send_Document)) {
222             break;
223         }
224         std::this_thread::sleep_for(std::chrono::milliseconds(USB_READ_INTERVAL));
225     }
226     PRINT_HILOGD("EndReadSendDocDataFromPrinterLooper");
227 }
228 
ProcessHttpResponse(httplib::Response & responseData,size_t requestId)229 void PrintHttpRequestProcess::ProcessHttpResponse(httplib::Response &responseData, size_t requestId)
230 {
231     PRINT_HILOGD("processHttpResponse enter");
232     int retryCount = 0;
233     // cups timeout is 30 seconds
234     while (retryCount < RESPONSE_RETRY_MAX_TIMES && deviceOpen) {
235         std::this_thread::sleep_for(std::chrono::milliseconds(RESPONSE_RETRY_INTERVAL));
236         retryCount++;
237         std::lock_guard<std::mutex> mtx_locker(mutexCommon);
238         if (readBufMap.find(requestId) != readBufMap.end()) {
239             size_t totalSize = readBufMap[requestId].size();
240             PRINT_HILOGD("Response totalSize:%{public}lu, retryCout = %{public}d", totalSize, retryCount);
241             PrintIppOverUsbUtil::ConstructHttpResponse(&readBufMap[requestId][0], totalSize, responseData);
242             readBufMap.erase(requestId);
243             break;
244         } else {
245             continue;
246         }
247     }
248     // 超时错误
249     if (retryCount >= RESPONSE_RETRY_MAX_TIMES) {
250         PRINT_HILOGE("process_http_response time out retryCout: %{public}d", retryCount);
251     }
252     PRINT_HILOGD("process_http_response out");
253 }
254 
ProcessHttpResponseGetAttr(httplib::Response & responseData,size_t requestId)255 void PrintHttpRequestProcess::ProcessHttpResponseGetAttr(httplib::Response &responseData, size_t requestId)
256 {
257     PRINT_HILOGD("processHttpResponseGetAttr enter");
258     int retryCount = 0;
259     while (retryCount < RESPONSE_RETRY_MAX_TIMES && deviceOpen) {
260         std::this_thread::sleep_for(std::chrono::milliseconds(RESPONSE_RETRY_INTERVAL));
261         retryCount++;
262         std::lock_guard<std::mutex> mtx_locker(mutexGetAttr);
263         if (readGetAttrBufMap.find(requestId) != readGetAttrBufMap.end()) {
264             size_t totalSize = readGetAttrBufMap[requestId].size();
265             PRINT_HILOGD("Response GetAttr totalSize:%{public}lu, retryCout = %{public}d", totalSize, retryCount);
266             PrintIppOverUsbUtil::ConstructHttpResponse(&readGetAttrBufMap[requestId][0], totalSize, responseData);
267             readGetAttrBufMap.erase(requestId);
268             break;
269         } else {
270             continue;
271         }
272     }
273     // 超时错误
274     if (retryCount >= RESPONSE_RETRY_MAX_TIMES) {
275         PRINT_HILOGE("process_http_response_get_attr time out retryCout: %{public}d", retryCount);
276     }
277     PRINT_HILOGD("process_http_response_get_attr out");
278 }
279 
ProcessHttpResponseSendDoc(httplib::Response & responseData,size_t requestId)280 void PrintHttpRequestProcess::ProcessHttpResponseSendDoc(httplib::Response &responseData, size_t requestId)
281 {
282     PRINT_HILOGD("ProcessHttpResponseSendDoc enter");
283     int retryCount = 0;
284     while (retryCount < RESPONSE_RETRY_MAX_TIMES && deviceOpen) {
285         std::this_thread::sleep_for(std::chrono::milliseconds(RESPONSE_RETRY_INTERVAL));
286         retryCount++;
287         std::lock_guard<std::mutex> mtx_locker(mutexSendDoc);
288         if (readSendDocBufMap.find(requestId) != readSendDocBufMap.end()) {
289             size_t totalSize = readSendDocBufMap[requestId].size();
290             PRINT_HILOGD("Response SendDoc totalSize:%{public}lu, retryCout = %{public}d", totalSize, retryCount);
291             PrintIppOverUsbUtil::ConstructHttpResponse(&readSendDocBufMap[requestId][0], totalSize, responseData);
292             readSendDocBufMap.erase(requestId);
293             break;
294         } else {
295             continue;
296         }
297     }
298     // 超时错误
299     if (retryCount >= RESPONSE_RETRY_MAX_TIMES) {
300         PRINT_HILOGE("ProcessHttpResponseSendDoc time out retryCout: %{public}d", retryCount);
301         needReadSendDoc = false;
302     }
303     PRINT_HILOGD("ProcessHttpResponseSendDoc out");
304 }
305 
DealRequestHeader(const httplib::Request & requestData,std::string & sHeadersAndBody)306 bool PrintHttpRequestProcess::DealRequestHeader(const httplib::Request &requestData, std::string &sHeadersAndBody)
307 {
308     bool ischunked = false;
309     for (const auto &x : requestData.headers) {
310         PRINT_HILOGD("requestData.headers first: %{public}s, second : %{public}s", x.first.c_str(), x.second.c_str());
311         if (x.first == HTTP_TRANSFER_ENCODING && x.second == HTTP_CHUNKED) {
312             ischunked = true;
313         }
314         if (x.first == HTTP_EXPECT) {
315             continue;
316         }
317         sHeadersAndBody += x.first;
318         sHeadersAndBody += SPLIT_VALUE_COLON;
319         sHeadersAndBody += x.second;
320         sHeadersAndBody += HTTP_MSG_STRING_R_AND_N;
321     }
322     sHeadersAndBody += HTTP_MSG_STRING_R_AND_N;
323     return ischunked;
324 }
325 
CalcReqIdOperaId(const char * data,size_t dataLength,size_t & requestId)326 void PrintHttpRequestProcess::CalcReqIdOperaId(const char *data, size_t dataLength, size_t &requestId)
327 {
328     if (dataLength < HTTP_COMMON_CONST_VALUE_8) {
329         return;
330     }
331     DumpReqIdOperaId(data, dataLength);
332     size_t operationId = (uint8_t)(*(data + INDEX_2)) * HTTP_COMMON_CONST_VALUE_10 + (uint8_t)(*(data + INDEX_3));
333     requestId = (uint8_t)(*(data + INDEX_4)) * HTTP_COMMON_CONST_VALUE_1000 +
334         (uint8_t)(*(data + INDEX_5)) * HTTP_COMMON_CONST_VALUE_100 +
335          (uint8_t)(*(data + INDEX_6)) * HTTP_COMMON_CONST_VALUE_10 + (uint8_t)(*(data + INDEX_7));
336     reqIdOperaIdMap[requestId] = operationId;
337 }
338 
StartWriteDataToPrinterLooper()339 void PrintHttpRequestProcess::StartWriteDataToPrinterLooper()
340 {
341     PRINT_HILOGD("StartWriteDataToPrinterLooper");
342     std::vector<uint8_t> vectorRequestBuffer;
343     while (deviceOpen && needWriteData) {
344         std::string str = "";
345         if (!ippDataQue.pop(str)) {
346             continue;
347         }
348 
349         vectorRequestBuffer.assign(str.begin(), str.end());
350         int32_t ret = 0;
351         int32_t writeDataRetryCount = 0;
352         do {
353             ret = DelayedSingleton<PrintUsbManager>::GetInstance()->BulkTransferWrite(
354                 devName, Operation::Common, vectorRequestBuffer);
355             PRINT_HILOGD("writeBody ret: %{public}d", ret);
356             if (ret == EORROR_HDF_DEV_ERR_TIME_OUT) {
357                 std::this_thread::sleep_for(std::chrono::milliseconds(USB_WRITE_INTERVAL));
358                 writeDataRetryCount++;
359                 PRINT_HILOGE(
360                     "StartWriteDataToPrinterLooper, retrwriteDataRetryCounty = %{public}d", writeDataRetryCount);
361             }
362         } while (ret == EORROR_HDF_DEV_ERR_TIME_OUT && writeDataRetryCount < WRITE_RETRY_MAX_TIMES);
363 
364         if (ret == EORROR_HDF_DEV_ERR_NO_DEVICE) {
365             PRINT_HILOGE("WriteData HDF_DEV_ERR_NO_DEVICE, The device module has no device");
366             needWriteData = false;
367             break;
368         }
369         vectorRequestBuffer.clear();
370         int retryCount = 0;
371         while (retryCount < READ_RETRY_MAX_TIMES) {
372             retryCount++;
373             if (ProcessDataFromDevice(Operation::Common)) {
374                 break;
375             }
376             std::this_thread::sleep_for(std::chrono::milliseconds(USB_READ_INTERVAL));
377         }
378         // 读超时错误
379         if (retryCount >= READ_RETRY_MAX_TIMES) {
380             PRINT_HILOGE("read data time out retryCout: %{public}d", retryCount);
381         }
382     }
383     PRINT_HILOGD("endtWriteDataToPrinterLooper");
384 }
385 
CreatWriteDataTask()386 void PrintHttpRequestProcess::CreatWriteDataTask()
387 {
388     PRINT_HILOGD("CreatWriteDataTask needWriteData: %{public}d", needWriteData);
389     if (!needWriteData) {
390         needWriteData = true;
391         std::thread writeDataTask([this] {this->StartWriteDataToPrinterLooper();});
392         writeDataTask.detach();
393     }
394 }
395 
ProcessOtherRequest(const char * data,size_t data_length,std::string & sHeadersAndBody,size_t requestId)396 void PrintHttpRequestProcess::ProcessOtherRequest(const char *data, size_t data_length,
397     std::string &sHeadersAndBody, size_t requestId)
398 {
399     CreatWriteDataTask();
400 
401     sHeadersAndBody.append(data, data_length);
402     ippDataQue.push(sHeadersAndBody);
403 }
404 
DumpReqIdOperaId(const char * data,size_t data_length)405 void PrintHttpRequestProcess::DumpReqIdOperaId(const char *data, size_t data_length)
406 {
407     if (data_length < REQID_OPERAID_LEN) {
408         return;
409     }
410     for (size_t i = 0; i < REQID_OPERAID_LEN; i++) {
411         PRINT_HILOGD("ipp: %{public}x", *(data + i));
412     }
413 }
414 
CreatReadSendDocTask()415 void PrintHttpRequestProcess::CreatReadSendDocTask()
416 {
417     PRINT_HILOGD("CreatReadSendDocTask needReadSendDoc: %{public}d", needReadSendDoc);
418     if (!needReadSendDoc) {
419         needReadSendDoc = true;
420         std::thread readSendDocTask([this] {this->StartReadSendDocDataFromPrinterLooper();});
421         readSendDocTask.detach();
422     }
423 }
424 
CreateChunk(const char * data,size_t data_length)425 std::string PrintHttpRequestProcess::CreateChunk(const char *data, size_t data_length)
426 {
427     std::string chunkStr = PrintIppOverUsbUtil::IntToHexString(static_cast<unsigned int>(data_length));
428     chunkStr += HTTP_MSG_STRING_R_AND_N;
429     chunkStr.append(data, data_length);
430     chunkStr += HTTP_MSG_STRING_R_AND_N;
431     return chunkStr;
432 }
433 
WriteDataSync(const std::string & dataStr)434 int32_t PrintHttpRequestProcess::WriteDataSync(const std::string &dataStr)
435 {
436     std::string sHeadersAndBody = dataStr;
437     int32_t ret = 0;
438     while (sHeadersAndBody.length() > USB_ENDPOINT_MAX_LENGTH) {
439         std::string send = sHeadersAndBody.substr(0, USB_ENDPOINT_MAX_LENGTH);
440         ret = BulkTransferWriteData(send);
441         if (ret != 0) {
442             return ret;
443         }
444         sHeadersAndBody = sHeadersAndBody.substr(USB_ENDPOINT_MAX_LENGTH);
445     }
446     if (!sHeadersAndBody.empty()) {
447         ret = BulkTransferWriteData(sHeadersAndBody);
448     }
449     return ret;
450 }
451 
BulkTransferWriteData(const std::string & dataStr)452 int32_t PrintHttpRequestProcess::BulkTransferWriteData(const std::string &dataStr)
453 {
454     std::vector<uint8_t> vectorRequestBuffer;
455     size_t len = dataStr.length();
456     sendDocTotalLen += len;
457     vectorRequestBuffer.assign(dataStr.begin(), dataStr.end());
458     uint32_t retryNum = 0;
459     int32_t ret = 0;
460     do {
461         ret = DelayedSingleton<PrintUsbManager>::GetInstance()->BulkTransferWrite(devName,
462             Operation::Send_Document, vectorRequestBuffer);
463         PRINT_HILOGD("writeBody chunk, ret: %{public}d, len: %{public}lu, sendDocTotalLen: %{public}lu",
464             ret, len, sendDocTotalLen);
465         if (ret == EORROR_HDF_DEV_ERR_NO_DEVICE) {
466             sendDocTotalLen = 0;
467             deviceOpen = false;
468             return ret;
469         }
470         if (ret == EORROR_HDF_DEV_ERR_TIME_OUT) {
471             std::this_thread::sleep_for(std::chrono::milliseconds(USB_BULKTRANSFER_WRITE_SLEEP));
472             retryNum++;
473         }
474     } while (ret == EORROR_HDF_DEV_ERR_TIME_OUT && retryNum < WRITE_RETRY_MAX_TIMES);
475     if (ret != 0) {
476         sendDocTotalLen = 0;
477         PRINT_HILOGD("Write data fail");
478         return ret;
479     }
480     vectorRequestBuffer.clear();
481     return ret;
482 }
483 
ProcessHttpResp(size_t requestId,httplib::Response & responseData,const std::string & sHeadersAndBody)484 void PrintHttpRequestProcess::ProcessHttpResp(size_t requestId, httplib::Response &responseData,
485     const std::string &sHeadersAndBody)
486 {
487     if (reqIdOperaIdMap[requestId] == HTTP_REQUEST_GET_ATTR) {
488         ProcessHttpResponseGetAttr(responseData, requestId);
489     } else if (reqIdOperaIdMap[requestId] == HTTP_REQUEST_SEND_DOC) {
490         if (!deviceOpen) {
491             PRINT_HILOGE("Device disconnect, return");
492             return;
493         }
494         PRINT_HILOGD("writeBody chunk end sHeadersAndBody len: %{public}lu", sHeadersAndBody.length());
495         std::string dataStr = sHeadersAndBody + HTTP_MSG_STRING_CHUNK_END;
496         auto ret = WriteDataSync(dataStr);
497         sendDocTotalLen = 0;
498         if (ret != 0) {
499             PRINT_HILOGE("writeBody chunk end fail");
500             return;
501         }
502         PRINT_HILOGD("writeBody chunk end");
503         ProcessHttpResponseSendDoc(responseData, requestId);
504     } else {
505         ProcessHttpResponse(responseData, requestId);
506     }
507 }
508 
ProcessRequest(const httplib::Request & requestData,httplib::Response & responseData,const httplib::ContentReader & content_reader)509 uint32_t PrintHttpRequestProcess::ProcessRequest(const httplib::Request &requestData, httplib::Response &responseData,
510     const httplib::ContentReader &content_reader)
511 {
512     PRINT_HILOGI("ProcessRequest devName: %{public}s", devName.c_str());
513     std::string sHeadersAndBody = HTTP_POST;
514     bool isChunked = DealRequestHeader(requestData, sHeadersAndBody);
515     size_t requestId = 0;
516     bool isFirstRead = true;
517     content_reader([&](const char *data, size_t data_length) {
518         if (isChunked) {
519             if (isFirstRead) {
520                 isFirstRead = false;
521                 CalcReqIdOperaId(data, data_length, requestId);
522                 CreatReadSendDocTask();
523                 sHeadersAndBody += CreateChunk(data, data_length);
524                 return CPP_HTTP_OK;
525             }
526         } else {
527             CalcReqIdOperaId(data, data_length, requestId);
528         }
529 
530         if (reqIdOperaIdMap[requestId] == HTTP_REQUEST_SEND_DOC) {
531             std::string dataChunk = CreateChunk(data, data_length);
532             if ((sHeadersAndBody.length() + dataChunk.length()) < USB_DATA_MAX_LENGTH) {
533                 sHeadersAndBody += dataChunk;
534                 return CPP_HTTP_OK;
535             }
536             auto ret = WriteDataSync(sHeadersAndBody);
537             if (ret != 0) {
538                 return CPP_HTTP_FAIL;
539             }
540             sHeadersAndBody = dataChunk;
541             return CPP_HTTP_OK;
542         }
543 
544         ProcessOtherRequest(data, data_length, sHeadersAndBody, requestId);
545         return CPP_HTTP_OK;
546     });
547     ProcessHttpResp(requestId, responseData, sHeadersAndBody);
548     PRINT_HILOGD("processRequest path: %{public}s end", requestData.path.c_str());
549     return 0;
550 }
551 
SetDeviceName(std::string name)552 void PrintHttpRequestProcess::SetDeviceName(std::string name)
553 {
554     devName = name;
555 }
556 
GetDeviceName()557 std::string PrintHttpRequestProcess::GetDeviceName()
558 {
559     return devName;
560 }
561 
Stop()562 void PrintHttpRequestProcess::Stop()
563 {
564     PRINT_HILOGD("stop read data looper");
565     needReadSendDoc = false;
566     needWriteSendDoc = false;
567     needWriteData = false;
568 }
569 
570 }
571 
572 #endif // IPPOVERUSB_ENABLE