Init basesystem source codes.
[staging/basesystem.git] / video_in_hal / nsframework / notification_persistent_service / server / src / ns_npp_copy_worker.cpp
1 /*
2  * @copyright Copyright (c) 2016-2020 TOYOTA MOTOR CORPORATION.
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 ////////////////////////////////////////////////////////////////////////////////////////////////////
18 /// \defgroup <<Group Tag>> <<Group Name>>
19 /// \ingroup  tag_NS_NPPService
20 ///
21 ////////////////////////////////////////////////////////////////////////////////////////////////////
22
23 ////////////////////////////////////////////////////////////////////////////////////////////////////
24 /// \ingroup  tag_NS_NPPService
25 /// \brief    This file implements the CCopyWorker class.
26 ///
27 ////////////////////////////////////////////////////////////////////////////////////////////////////
28 #include <native_service/ns_util_crc.h>
29 #include <native_service/ns_logger_if.h>
30
31 // standard headers
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <dirent.h>
39
40 #include <string>
41 #include <utility>
42
43 // ns headers
44 #include "ns_npp_copy_worker.h"
45 #include "ns_npp_notificationpersistentservicelog.h"
46 #include "ns_npp_fs_directory.h"
47 #include "ns_npp_persistence.h"
48 #include "ns_npp_threads.h"
49 #include "ns_npp.h"
50
51 #ifdef AGL_STUB
52 #include <other_service/strlcpy.h>
53 /*#include "PosixBasedOS001legacy_types.h"*/
54 #include <unistd.h>
55 #include <sys/syscall.h>
56 #endif
57
58 #define NS_NPP_WRITESIZE1   4096
59 #define NS_NPP_WRITESIZE2   32768
60 #define NS_NPP_REMOVE_DIR_DELAY 100  // in ms
61 #define NS_NPP_FILEWRITE_DELAY  50  // in ms
62
63 pthread_mutex_t g_mutworkerthread = PTHREAD_MUTEX_INITIALIZER;
64 pthread_mutex_t CCopyWorker::m_sAbortMutex = PTHREAD_MUTEX_INITIALIZER;
65 BOOL CCopyWorker::m_sbAbortCopy = FALSE;
66
67 template <typename C, eFrameworkunifiedStatus(C::*M)(HANDLE)> EFrameworkunifiedStatus WorkerCallback(HANDLE hthread) {
68   EFrameworkunifiedStatus l_estatus = eFrameworkunifiedStatusOK;
69
70   C *l_pClass = static_cast<C *>(FrameworkunifiedGetThreadSpecificData(hthread));
71
72   if (l_pClass) {  // LCOV_EXCL_BR_LINE 6: l_pClass can't be NULL
73     l_estatus = (l_pClass->*M)(hthread);
74   }
75
76   return l_estatus;
77 }
78
79 // Initialize static members
80 TMServiceTagCRC CCopyWorker::CCopyWorker::g_mservicetagcrc;
81 CMutex CCopyWorker::CCopyWorker::g_objmtxservicetag;
82
83 static FrameworkunifiedProtocolCallbackHandler aServiceHandlers[] = {  // NOLINT (readability/naming)  // LCOV_EXCL_BR_LINE 11: unexpected branch
84   { CP_WRK_CMD_COPY,            WorkerCallback<CCopyWorker, &CCopyWorker::OnWrkCmdCopy>   },
85   { CP_WRK_CMD_RESUME,          WorkerCallback<CCopyWorker, &CCopyWorker::OnWrkCmdResume> },
86   { AR_CMD_ARCHIVE,               WorkerCallback<CCopyWorker, &CCopyWorker::OnWrkCmdArchive>    },
87   { CMD_WRK_SHUTDOWN_REQ,           WorkerCallback<CCopyWorker, &CCopyWorker::OnCmdShutdownRequest>},
88 };
89
90 ////////////////////////////////////////////////////////////////////////////////////////////////////
91 /// CCopyWorker
92 /// Constructor of CCopyWorker class
93 ////////////////////////////////////////////////////////////////////////////////////////////////////
94 CCopyWorker::CCopyWorker() {
95   pthread_mutex_init(&m_sAbortMutex, NULL);
96 }
97
98 ////////////////////////////////////////////////////////////////////////////////////////////////////
99 /// ~CCopyWorker
100 /// Destructor of CCopyWorker class
101 ////////////////////////////////////////////////////////////////////////////////////////////////////
102 CCopyWorker::~CCopyWorker() {
103   pthread_mutex_destroy(&m_sAbortMutex);
104 }
105
106 ////////////////////////////////////////////////////////////////////////////////////////////////////
107 /// Abort
108 /// Method to abort worker thread.
109 ////////////////////////////////////////////////////////////////////////////////////////////////////
110 VOID CCopyWorker::Abort() {   // LCOV_EXCL_START 8: not used
111   AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
112   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
113
114   pthread_mutex_lock(&m_sAbortMutex);
115   m_sbAbortCopy = TRUE;
116   pthread_mutex_unlock(&m_sAbortMutex);
117
118   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
119 }
120 // LCOV_EXCL_STOP
121
122 ////////////////////////////////////////////////////////////////////////////////////////////////////
123 /// InAbortState
124 /// Method to check for abort state.
125 ////////////////////////////////////////////////////////////////////////////////////////////////////
126 BOOL CCopyWorker::InAbortState() const {
127   BOOL l_bAbortStatus = FALSE;
128   pthread_mutex_lock(&m_sAbortMutex);
129   l_bAbortStatus = m_sbAbortCopy;
130   pthread_mutex_unlock(&m_sAbortMutex);
131
132   return l_bAbortStatus;
133 }
134
135 ////////////////////////////////////////////////////////////////////////////////////////////////////
136 /// SetCopyStatusToFailure
137 /// Method to set the copy status failure.
138 ////////////////////////////////////////////////////////////////////////////////////////////////////
139 EFrameworkunifiedStatus CCopyWorker::SetCopyStatusToFailure(NSP_CopyStatusResponse &f_tcopystatusresponse,  // LCOV_EXCL_START 8: not used  // NOLINT[whitespace/line_length]
140                                                const ENPS_CopyWorkerFailures f_eworkerfailcmd) {
141   AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
142   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
143
144   f_tcopystatusresponse.m_bpersistencechk = FALSE;
145   f_tcopystatusresponse.m_ecopyfailures = f_eworkerfailcmd;
146
147   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
148   return eFrameworkunifiedStatusFail;
149 }
150 // LCOV_EXCL_STOP
151
152 ////////////////////////////////////////////////////////////////////////////////////////////////////
153 /// OnWrkCmdCopy
154 /// Callback method on copy command.
155 ////////////////////////////////////////////////////////////////////////////////////////////////////
156 EFrameworkunifiedStatus CCopyWorker::OnWrkCmdCopy(HANDLE hthread) {
157   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
158   EFrameworkunifiedStatus l_estatus = eFrameworkunifiedStatusOK;
159   NSP_CopyStatusResponse l_tCopyStatus = {};
160   NSP_CopyInfoCmd l_tCopyInfo = {};
161   UI_32 l_uiFileSize = 0;
162   UI_32 l_ui32FileCRC = 0;
163   PSTR  l_cTmpStorageFile = NULL;
164
165   if (NULL != hthread) {  // LCOV_EXCL_BR_LINE 6: hthread can't be NULL
166     if (FrameworkunifiedGetMsgLength(hthread) == sizeof(l_tCopyInfo)) {  // LCOV_EXCL_BR_LINE 200: the size of msg must be sizeof(NSP_CopyInfoCmd)  // NOLINT[whitespace/line_length]
167       if (eFrameworkunifiedStatusOK == (l_estatus = FrameworkunifiedGetMsgDataOfSize(hthread, &l_tCopyInfo, sizeof(NSP_CopyInfoCmd), eSMRRelease))) {  // LCOV_EXCL_BR_LINE 4: NSFW error case  // NOLINT[whitespace/line_length]
168         l_tCopyStatus.m_eloadtype = l_tCopyInfo.m_eloadtype;
169 #ifdef AGL_PosixBasedOS001LEGACY_USED
170         strlcpy(l_tCopyStatus.m_cpersistenttag, l_tCopyInfo.m_cpersistenttag, sizeof(l_tCopyStatus.m_cpersistenttag));
171         strlcpy(l_tCopyStatus.m_crequesterappname,
172                 l_tCopyInfo.m_crequesterappname,
173                 sizeof(l_tCopyStatus.m_crequesterappname));
174 #endif
175
176         l_tCopyStatus.m_epersisttype = l_tCopyInfo.m_epersisttype;
177
178         if (ENOTIFICATIONPERSISTENTSERVICECOMPRESSUSINGLIBZ == l_tCopyInfo.m_ecompressiontype) {  // LCOV_EXCL_BR_LINE 6: l_tCopyInfo.m_ecompressiontype can't be ENOTIFICATIONPERSISTENTSERVICECOMPRESSUSINGLIBZ  // NOLINT[whitespace/line_length]
179           // LCOV_EXCL_START 6: l_tCopyInfo.m_ecompressiontype can't be ENOTIFICATIONPERSISTENTSERVICECOMPRESSUSINGLIBZ
180           AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
181           CCopyWorker::CArchive *l_pCArchive =  new(std::nothrow) CCopyWorker::CArchive();
182
183           if (NULL != l_pCArchive) {
184             // Start the folder archive or extract operation
185             if (eFrameworkunifiedStatusOK == (l_estatus = l_pCArchive->FileOperationUsingLibz(l_tCopyInfo, l_tCopyStatus))) {
186               FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "Compress/Decompress Successful");
187             } else {
188               l_estatus = eFrameworkunifiedStatusFail;  // Set the archive status to failure
189             }
190             delete l_pCArchive;
191             l_pCArchive = NULL;
192           }
193           // LCOV_EXCL_STOP
194         } else {
195           FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "Tag: %s SourceFile: %s DestFile: %s",
196                  l_tCopyInfo.m_cpersistenttag != 0 ? l_tCopyInfo.m_cpersistenttag : NULL,
197                  l_tCopyInfo.m_csourcepath != 0 ? l_tCopyInfo.m_csourcepath : NULL,
198                  l_tCopyInfo.m_cdestinationpath != 0 ? l_tCopyInfo.m_cdestinationpath : NULL);
199
200           if (LOADTYPE_RELEASE == l_tCopyStatus.m_eloadtype) {
201             // if release, source file needs to check whether it's changed or not
202             l_cTmpStorageFile = l_tCopyInfo.m_csourcepath;
203           } else if (LOADTYPE_LOAD == l_tCopyStatus.m_eloadtype) {  // LCOV_EXCL_BR_LINE 6: m_eloadtype must be LOADTYPE_RELEASE or LOADTYPE_LOAD  // NOLINT[whitespace/line_length]
204             // if load, dest file needs to check whether it's changed or not
205             l_cTmpStorageFile = l_tCopyInfo.m_cdestinationpath;
206
207             // check if file on temporary location exists, then no need to load from persistent memory
208             if (0 == access(l_tCopyInfo.m_cdestinationpath, F_OK)) {  // LCOV_EXCL_BR_LINE 5: access's error case
209               FRAMEWORKUNIFIEDLOG(ZONE_PRD_INFO2, __FUNCTION__, "File to load::%s for source::%s "
210                      "is already present on path:: %s.",
211                      l_tCopyInfo.m_cpersistenttag != 0 ? l_tCopyInfo.m_cpersistenttag : NULL,
212                      l_tCopyStatus.m_crequesterappname != 0 ? l_tCopyStatus.m_crequesterappname : NULL,
213                      l_tCopyInfo.m_cdestinationpath != 0 ? l_tCopyInfo.m_cdestinationpath : NULL);
214               l_estatus = eFrameworkunifiedStatusFileLoadSuccess;
215             }
216           } else {
217             AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
218             // let l_cTmpStorageFile be NULL.
219           }
220
221           if (eFrameworkunifiedStatusFileLoadSuccess == l_estatus) {
222             l_estatus = eFrameworkunifiedStatusOK;
223           } else {
224             if (NULL != l_cTmpStorageFile) {  // LCOV_EXCL_BR_LINE 6: l_cTmpStorageFile can't be NULL
225               if (!VerifyWithStoredCRC(l_tCopyStatus.m_crequesterappname,
226                                        l_tCopyStatus.m_cpersistenttag,
227                                        l_cTmpStorageFile,
228                                        l_ui32FileCRC)) {  // l_ui32FileCRC: out param
229                 // Check if file release and CRC verification is enabled
230                 if ((LOADTYPE_RELEASE == l_tCopyStatus.m_eloadtype) && (CNSNPP::m_siCRCCheckCount > 0)) {  // LCOV_EXCL_BR_LINE 200: cannot test code  // NOLINT[whitespace/line_length]
231                   // LCOV_EXCL_START 200: cannot test code
232                   AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
233                   l_estatus = TryFileCopyWithCRCCheck(l_tCopyInfo.m_csourcepath,
234                                                       l_tCopyInfo.m_cdestinationpath,
235                                                       CNSNPP::m_siCRCCheckCount);
236                   // LCOV_EXCL_STOP
237                 } else {
238                   if (LOADTYPE_RELEASE == l_tCopyStatus.m_eloadtype) {
239                     l_estatus = CopyFile(l_tCopyInfo.m_csourcepath,
240                                          l_tCopyInfo.m_cdestinationpath,
241                                          l_uiFileSize,
242                                          TRUE);
243                   } else {
244                     l_estatus = CopyFile(l_tCopyInfo.m_csourcepath,
245                                          l_tCopyInfo.m_cdestinationpath,
246                                          l_uiFileSize,
247                                          FALSE);
248                   }
249                 }
250                 if (eFrameworkunifiedStatusOK == l_estatus) {
251                   FRAMEWORKUNIFIEDLOG(ZONE_PRD_INFO3, __FUNCTION__, "Bytes written:%d file=%s",
252                          l_uiFileSize, l_tCopyInfo.m_cdestinationpath != 0 ? l_tCopyInfo.m_cdestinationpath : NULL);
253                   if (0 == l_ui32FileCRC) {
254                     if (eFrameworkunifiedStatusOK != CalculateCRC32(l_cTmpStorageFile, l_ui32FileCRC)) {  // LCOV_EXCL_BR_LINE 200: CalculateCRC32() return ok  // NOLINT[whitespace/line_length]
255                       // LCOV_EXCL_START 200: CalculateCRC32() return ok
256                       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
257                       FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, "Warn: getting crc. File:%s, crc:%d",
258                              l_cTmpStorageFile, l_ui32FileCRC);
259                       // LCOV_EXCL_STOP
260                     }
261                   }
262                   UpdateTagCRC(l_tCopyStatus.m_crequesterappname, l_tCopyInfo.m_cpersistenttag, l_ui32FileCRC);
263                 } else {
264                   FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "FileCopy Error, status : 0x%x", l_estatus);
265                 }
266               } else {
267                 FRAMEWORKUNIFIEDLOG(ZONE_PRD_INFO2, __FUNCTION__,
268                        "File %s not changed. No copy done. Load type:%d. Tag:%s for Requester:%s.",
269                        l_cTmpStorageFile,
270                        l_tCopyStatus.m_eloadtype,
271                        l_tCopyStatus.m_cpersistenttag != 0 ? l_tCopyStatus.m_cpersistenttag : NULL,
272                        l_tCopyStatus.m_crequesterappname != 0 ? l_tCopyStatus.m_crequesterappname : NULL);
273               }
274             } else {
275               // LCOV_EXCL_START 6: l_cTmpStorageFile can't be NULL
276               AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
277               FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Unknown load type:%d, for tag:%s",
278                      l_tCopyStatus.m_eloadtype,
279                      l_tCopyStatus.m_cpersistenttag != 0 ? l_tCopyStatus.m_cpersistenttag : NULL);
280               // LCOV_EXCL_STOP
281             }
282           }
283         }
284
285         if (eFrameworkunifiedStatusOK != l_estatus) {
286           l_tCopyStatus.m_bpersistencechk = FALSE;
287
288           FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "COPY_FAILED_ID sending parent message. Tag:%s for Requester:%s.",
289                  l_tCopyStatus.m_cpersistenttag != 0 ? l_tCopyStatus.m_cpersistenttag : NULL,
290                  l_tCopyStatus.m_crequesterappname != 0 ? l_tCopyStatus.m_crequesterappname : NULL);
291
292           FrameworkunifiedSendParent(hthread, CP_WRK_NTFY, sizeof(NSP_CopyStatusResponse), &l_tCopyStatus);
293         } else {
294           l_tCopyStatus.m_bpersistencechk = TRUE;
295
296           FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "COPY_COMPLETE_ID sending parent message. Tag:%s for Requester:%s.",
297                  l_tCopyStatus.m_cpersistenttag != 0 ? l_tCopyStatus.m_cpersistenttag : NULL,
298                  l_tCopyStatus.m_crequesterappname != 0 ? l_tCopyStatus.m_crequesterappname : NULL);
299
300           FrameworkunifiedSendParent(hthread, CP_WRK_NTFY, sizeof(NSP_CopyStatusResponse), &l_tCopyStatus);
301         }
302       } else {
303         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
304         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Error:FrameworkunifiedGetMsgDataOfSize returned:%d", l_estatus);  // LCOV_EXCL_LINE 4: NSFW error case  // NOLINT[whitespace/line_length]
305       }
306     } else {
307       // LCOV_EXCL_START 200: the size of msg must be sizeof(NSP_CopyInfoCmd)
308       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
309       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Error:MsgLength: Expected:%ld, Received:%d.",
310              static_cast<long int>(sizeof(l_tCopyInfo)), FrameworkunifiedGetMsgLength(hthread)); // NOLINT (runtime/int)
311       // LCOV_EXCL_STOP
312     }
313     l_estatus = SendAck(hthread, CP_WRK_CMD_COPY);
314   } else {
315     // LCOV_EXCL_START 6: hthread can't be NULL
316     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
317     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Thread App Handle Null");
318     l_estatus = eFrameworkunifiedStatusInvldHandle;
319     // LCOV_EXCL_STOP
320   }
321
322   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
323   return l_estatus;
324 }
325
326 ////////////////////////////////////////////////////////////////////////////////////////////////
327 /// GetCopyBufSize
328 /// Get the proper buffer size.
329 ////////////////////////////////////////////////////////////////////////////////////////////////
330 SI_32 CCopyWorker::GetCopyBufSize(SI_32 f_si32openfd, UI_32 &f_ui32filesize) {
331   UI_32 l_ui32BufSize = NS_NPP_WRITESIZE1;
332   // to get the size of file
333   struct stat l_tSrcFstat = {};
334
335   if (-1 == fstat(f_si32openfd , &l_tSrcFstat)) {  // LCOV_EXCL_BR_LINE 5: fstat's error case
336     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
337     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "fstat failure, errno:%d", errno);  // LCOV_EXCL_LINE 5: fstat's error case
338   } else {
339     f_ui32filesize = static_cast<UI_32>(l_tSrcFstat.st_size);  // set out param
340     if (l_tSrcFstat.st_size < NS_NPP_WRITESIZE1) {
341       l_ui32BufSize = NS_NPP_WRITESIZE1;
342     } else {
343       l_ui32BufSize = NS_NPP_WRITESIZE2;
344     }
345   }
346   return l_ui32BufSize;
347 }
348
349 ////////////////////////////////////////////////////////////////////////////////////////////////
350 /// CopyFile
351 /// Copy the content of source file f_csrcpath to destination file f_cdestpath
352 ////////////////////////////////////////////////////////////////////////////////////////////////
353 EFrameworkunifiedStatus CCopyWorker::CopyFile(PCSTR f_csrcpath, PCSTR f_cdestpath, UI_32 &f_uiNS_NPP_WRITESIZE, BOOL btmpfile) {
354   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
355
356   // declare variables
357   EFrameworkunifiedStatus l_estatus = eFrameworkunifiedStatusOK;
358   SI_32 l_iSourceFileFd  = -1;        // file descriptor of source file
359   SI_32 l_iDestFileFd = -1;         // file descriptor of destination file
360   PSTR l_cWriteBuffer = NULL;
361   SI_32 l_si32BufSize = NS_NPP_WRITESIZE1;
362   size_t l_iReadBuffLength = 0;        // size of data read from source file
363   UI_32 l_ui32SrcFileSize = 0;
364   std::string l_cTempDestPath;  // temporary file path
365   if (btmpfile == FALSE) {
366     l_cTempDestPath = f_cdestpath;
367   } else {
368     l_cTempDestPath = CPersistence::GetStoragePath();  // LCOV_EXCL_BR_LINE 11: unexpected branch
369     if (l_cTempDestPath.length() > 0) {  // LCOV_EXCL_BR_LINE 6: l_cTempDestPath.length() is bigger than 0
370       l_cTempDestPath.append(RELEASETEMP_DIR);  // LCOV_EXCL_BR_LINE 11: unexpected branch
371       // create the destination folder path if does not exists
372       if (!CFSDirectory::DoesDirecotryExist(l_cTempDestPath)) {
373         FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "%s DOESN'T exist, Creating...", l_cTempDestPath.c_str());
374         if (eFrameworkunifiedStatusOK != (l_estatus = CFSDirectory::CreateDirectory(l_cTempDestPath))) {  // LCOV_EXCL_BR_LINE 200: CreateDirectory() is eFrameworkunifiedStatusOK  // NOLINT[whitespace/line_length]
375           // LCOV_EXCL_START 200: CreateDirectory() is eFrameworkunifiedStatusOK
376           AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
377           FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to create %s, errno:%d", l_cTempDestPath.c_str(), errno);
378           return l_estatus;
379           // LCOV_EXCL_STOP
380         }
381       }
382       l_cTempDestPath.append(RELEASETEMP_FILENAME);
383
384     } else {
385       // LCOV_EXCL_START 6: l_cTempDestPath.length() is bigger than 0
386       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
387       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "l_cTempDestPath.length():%ld", static_cast<long int>(l_cTempDestPath.length())); // NOLINT (runtime/int)
388       return eFrameworkunifiedStatusFail;
389       // LCOV_EXCL_STOP
390     }
391   }
392   // get the destination folder path from full file path
393   std::string l_cOutDirPath(f_cdestpath);
394   size_t l_ifound = l_cOutDirPath.rfind("/");
395   l_cOutDirPath = l_cOutDirPath.substr(0, l_ifound);
396
397   FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "Full Path for persistence %s.", f_cdestpath);
398
399   // create the destination folder path if does not exists
400   if (!CFSDirectory::DoesDirecotryExist(l_cOutDirPath)) {
401     FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "%s DOESN'T exist, Creating...", l_cOutDirPath.c_str());
402
403     if (eFrameworkunifiedStatusOK != (l_estatus = CFSDirectory::CreateDirectory(l_cOutDirPath))) {
404       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to create %s, errno:%d", l_cOutDirPath.c_str(), errno);
405       return eFrameworkunifiedStatusFail;
406     }
407   }
408
409   // open source file
410   if (-1 == (l_iSourceFileFd = open(f_csrcpath, O_RDONLY, S_IRUSR))) {  // LCOV_EXCL_BR_LINE 5: open's error case
411     // LCOV_EXCL_START 5: open's error case
412     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
413     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Warning :: CP_WRK_FAILURE_SRC_NOT_FND, errno:%d", errno);
414     l_estatus = eFrameworkunifiedStatusFail;
415     // LCOV_EXCL_STOP
416   } else {
417     // open the destination file for writing or create if does not exists
418     if (-1 == (l_iDestFileFd = open(l_cTempDestPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC,  // LCOV_EXCL_BR_LINE 5: open's error case  // NOLINT[whitespace/line_length]
419                                     S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH))) {
420       // LCOV_EXCL_START 5: open's error case
421       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
422       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "CP_WRK_FAILURE_DST_CREATE, errno:%d", errno);
423       l_estatus = eFrameworkunifiedStatusFail;
424       // LCOV_EXCL_STOP
425     } else {
426       l_si32BufSize = GetCopyBufSize(l_iSourceFileFd, l_ui32SrcFileSize);
427
428       FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "Src file:%s, size:%d", f_csrcpath, l_ui32SrcFileSize);
429       l_cWriteBuffer = (PSTR) std::malloc(l_si32BufSize);
430       f_uiNS_NPP_WRITESIZE = 0;
431
432       if (NULL != l_cWriteBuffer) {  // LCOV_EXCL_BR_LINE 5: malloc's error case
433 #ifdef AGL_STUB
434         while (1) {
435           std::memset(l_cWriteBuffer, 0, l_si32BufSize);
436           l_iReadBuffLength = read(l_iSourceFileFd, l_cWriteBuffer, l_si32BufSize);
437           if (0 == l_iReadBuffLength) {
438             break;
439           } else if (0 < l_iReadBuffLength) {  // LCOV_EXCL_BR_LINE 5: read's error case
440             f_uiNS_NPP_WRITESIZE += static_cast<UI_32>(l_iReadBuffLength);
441
442             if (-1 == write(l_iDestFileFd, l_cWriteBuffer, l_iReadBuffLength)) {
443               FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "CP_WRK_FAILURE_WRITE_ERROR_CP, errno:%d", errno);
444               l_estatus = eFrameworkunifiedStatusFail;
445             }
446
447             if (InAbortState()) {  // LCOV_EXCL_START 200: the state can't be aborted
448               AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
449               FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "CP_WRK_FAILURE_ABORT_DURING_CP");
450               l_estatus = eFrameworkunifiedStatusFail;
451             }
452             // LCOV_EXCL_STOP
453           } else {
454             // LCOV_EXCL_START 5: read's error case
455             AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
456             FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Error reading from source file, errno:%d", errno);
457             l_estatus = eFrameworkunifiedStatusFail;
458             // LCOV_EXCL_STOP
459           }
460
461           if (eFrameworkunifiedStatusOK != l_estatus) {
462             break;
463           }
464         }
465 #else
466         while (!eof(l_iSourceFileFd)) {
467           std::memset(l_cWriteBuffer, 0, l_si32BufSize);
468           if (-1 != (l_iReadBuffLength = read(l_iSourceFileFd, l_cWriteBuffer, l_si32BufSize))) {
469             f_uiNS_NPP_WRITESIZE += static_cast<UI_32>(l_iReadBuffLength);
470
471             if (-1 == write(l_iDestFileFd, l_cWriteBuffer, l_iReadBuffLength)) {
472               FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "CP_WRK_FAILURE_WRITE_ERROR_CP, errno:%d", errno);
473               l_estatus = eFrameworkunifiedStatusFail;
474             }
475
476             if (InAbortState()) {
477               FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "CP_WRK_FAILURE_ABORT_DURING_CP");
478               l_estatus = eFrameworkunifiedStatusFail;
479             }
480           } else {
481             FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Error reading from source file, errno:%d", errno);
482             l_estatus = eFrameworkunifiedStatusFail;
483           }
484
485           if (eFrameworkunifiedStatusOK != l_estatus) {
486             break;
487           }
488         }
489 #endif
490
491         free(l_cWriteBuffer);
492         l_cWriteBuffer = NULL;
493       } else {
494         // LCOV_EXCL_START 5: malloc's error case
495         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
496         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Mem alloc error for l_cWriteBuffer");
497         l_estatus = eFrameworkunifiedStatusNullPointer;
498         // LCOV_EXCL_STOP
499       }
500
501       close(l_iDestFileFd);
502
503       if (eFrameworkunifiedStatusOK == l_estatus) {
504         if (btmpfile == TRUE) {
505           if (0 != rename(l_cTempDestPath.c_str(), f_cdestpath)) {  // LCOV_EXCL_START 5: rename's error case
506             AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
507             l_estatus = eFrameworkunifiedStatusFail;
508             FRAMEWORKUNIFIEDLOG(ZONE_ERR, __PRETTY_FUNCTION__,
509                    "Error renaming file %s to %s, errno: %d", l_cTempDestPath.c_str(), f_cdestpath,
510                    errno);
511           }
512           // LCOV_EXCL_STOP
513         }
514       } else {
515         // remove the source file after successful copy
516         if (0 != remove(l_cTempDestPath.c_str())) {
517           FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, "Temporary file not deleted::%s, errno:%d", l_cTempDestPath.c_str(), errno);
518         }
519       }
520     }
521
522     close(l_iSourceFileFd);
523   }
524
525   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
526   return l_estatus;
527 }
528
529 ////////////////////////////////////////////////////////////////////////////////////////////////////
530 /// OnWrkCmdResume
531 /// Callback on resume worker thread command
532 ////////////////////////////////////////////////////////////////////////////////////////////////////
533 EFrameworkunifiedStatus CCopyWorker::OnWrkCmdResume(HANDLE hthread) {  // LCOV_EXCL_START 8: not used
534   AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
535   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
536   EFrameworkunifiedStatus l_estatus = eFrameworkunifiedStatusOK;
537
538   if (hthread) {
539     pthread_mutex_lock(&m_sAbortMutex);
540     m_sbAbortCopy = FALSE;
541     pthread_mutex_unlock(&m_sAbortMutex);
542     l_estatus =  SendAck(hthread, CP_WRK_CMD_RESUME);
543   } else {
544     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Thread App Handle Null.");
545     l_estatus = eFrameworkunifiedStatusInvldHandle;
546   }
547   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
548   return l_estatus;
549 }
550 // LCOV_EXCL_STOP
551
552 ////////////////////////////////////////////////////////////////////////////////////////////////////
553 /// OnWrkCmdStart
554 /// Callback method on start worker thread command.
555 ////////////////////////////////////////////////////////////////////////////////////////////////////
556 EFrameworkunifiedStatus CCopyWorker::OnWrkCmdStart(HANDLE hthread) {
557   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
558   EFrameworkunifiedStatus l_estatus = eFrameworkunifiedStatusOK;
559
560   if (hthread) {  // LCOV_EXCL_BR_LINE 6:hthread can't be NULL
561     l_estatus = SendAck(hthread, CP_WRK_CMD_START);
562   } else {
563     // LCOV_EXCL_START 6:hthread can't be NULL
564     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
565     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Thread App Handle Null.");
566     l_estatus = eFrameworkunifiedStatusInvldHandle;
567     // LCOV_EXCL_STOP
568   }
569
570   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
571   return l_estatus;
572 }
573
574 ////////////////////////////////////////////////////////////////////////////////////////////////////
575 /// OnWrkCmdStop
576 /// Callback method on stop worker thread command.
577 ////////////////////////////////////////////////////////////////////////////////////////////////////
578 EFrameworkunifiedStatus CCopyWorker::OnWrkCmdStop(HANDLE hthread) {  // LCOV_EXCL_START 200: can't test
579   AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
580   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
581   EFrameworkunifiedStatus l_estatus = eFrameworkunifiedStatusOK;
582
583   if (hthread) {
584     l_estatus = SendAck(hthread, CP_WRK_CMD_STOP);
585   } else {
586     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Thread App Handle Null.");
587     l_estatus = eFrameworkunifiedStatusInvldHandle;
588   }
589
590   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
591   return l_estatus;
592 }
593 // LCOV_EXCL_STOP
594
595 ////////////////////////////////////////////////////////////////////////////////////////////////////
596 /// OnCmdShutdownRequest
597 /// Callback method for  shutdown request command.
598 ////////////////////////////////////////////////////////////////////////////////////////////////////
599 EFrameworkunifiedStatus CCopyWorker::OnCmdShutdownRequest(HANDLE hthread) {  // LCOV_EXCL_START 8: not used
600   AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
601   EFrameworkunifiedStatus l_estatus = eFrameworkunifiedStatusOK;
602   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
603   if (hthread) {
604     NSP_CopyShutdownAck l_tCopyShutdownAck = {};
605     if (FrameworkunifiedGetMsgLength(hthread) == sizeof(l_tCopyShutdownAck)) {
606       if (eFrameworkunifiedStatusOK == (l_estatus = FrameworkunifiedGetMsgDataOfSize(hthread, &l_tCopyShutdownAck, sizeof(NSP_CopyShutdownAck),
607                                                            eSMRRelease))) {
608         FrameworkunifiedSendParent(hthread,  CMD_WRK_SHUTDOWN_ACK, sizeof(NSP_CopyShutdown), &l_tCopyShutdownAck);
609       } else {
610         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Error:FrameworkunifiedGetMsgDataOfSize returned:%d", l_estatus);
611       }
612     } else {
613       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Error:MsgLength: Expected:%ld, Received:%d.",
614              static_cast<long int>(sizeof(l_tCopyShutdownAck)), FrameworkunifiedGetMsgLength(hthread)); // NOLINT (runtime/int)
615     }
616   } else {
617     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Thread App Handle Null.");
618     l_estatus = eFrameworkunifiedStatusInvldHandle;
619   }
620
621   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
622   return l_estatus;
623 }
624 // LCOV_EXCL_STOP
625
626 ////////////////////////////////////////////////////////////////////////////////////////////////////
627 /// SendAck
628 /// Method to send ack to the parent thread
629 ////////////////////////////////////////////////////////////////////////////////////////////////////
630 EFrameworkunifiedStatus CCopyWorker::SendAck(HANDLE hthread, const ENSP_CopyWorkerProtocol &f_eworkercmd) {
631   EFrameworkunifiedStatus l_estatus = eFrameworkunifiedStatusOK;
632   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
633
634   if (hthread) {  // LCOV_EXCL_BR_LINE 6: hthread can't be NULL
635     NSP_CopyAckMsg l_tCopyAckMs = {};
636     l_tCopyAckMs.m_eworkerprotocol = f_eworkercmd;
637     l_estatus =  FrameworkunifiedSendParent(hthread,  CP_WRK_ACK_CMD_COMPLETE, sizeof(l_tCopyAckMs), &l_tCopyAckMs);
638   } else {
639     // LCOV_EXCL_START 6: hthread can't be NULL
640     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
641     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Thread App Handle Null.");
642     l_estatus = eFrameworkunifiedStatusInvldHandle;
643     // LCOV_EXCL_STOP
644   }
645   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
646   return l_estatus;
647 }
648
649 ////////////////////////////////////////////////////////////////////////////////////////////////////
650 /// OnWrkCmdArchive
651 /// Callback method on archive command
652 ////////////////////////////////////////////////////////////////////////////////////////////////////
653 EFrameworkunifiedStatus CCopyWorker::OnWrkCmdArchive(HANDLE f_hThread) {
654   EFrameworkunifiedStatus l_estatus = eFrameworkunifiedStatusOK;
655
656   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
657   // Archive response struct
658   NSP_CopyStatusResponse l_tArchiveStatusResponse;
659
660   if (f_hThread) {  // LCOV_EXCL_BR_LINE 6: f_hThread can't be NULL
661     // Archive info struct
662     NSP_CopyInfoCmd l_tArchiveInfo = {};
663
664     if (FrameworkunifiedGetMsgLength(f_hThread) == sizeof(l_tArchiveInfo)) {  // LCOV_EXCL_BR_LINE 4: NSFW error case
665       if (eFrameworkunifiedStatusOK == (l_estatus = FrameworkunifiedGetMsgDataOfSize(f_hThread, &l_tArchiveInfo, sizeof(NSP_CopyInfoCmd),  // LCOV_EXCL_BR_LINE 4: NSFW error case  // NOLINT[whitespace/line_length]
666                                                            eSMRRelease))) {
667         // Copy archive status response
668         l_tArchiveStatusResponse.m_eloadtype = l_tArchiveInfo.m_eloadtype;
669         l_tArchiveStatusResponse.m_epersisttype = l_tArchiveInfo.m_epersisttype;
670         std::strncpy(l_tArchiveStatusResponse.m_cpersistenttag, l_tArchiveInfo.m_cpersistenttag, (MAX_PATH_LENGTH - 1));
671         std::strncpy(l_tArchiveStatusResponse.m_crequesterappname,
672                      l_tArchiveInfo.m_crequesterappname, (MAX_PATH_LENGTH - 1));
673
674         CCopyWorker::CArchive *l_pCArchive =  new CCopyWorker::CArchive();
675
676         // Start the folder archive or extract operation
677         if (eFrameworkunifiedStatusOK == (l_estatus = l_pCArchive->Archive(l_tArchiveInfo, l_tArchiveStatusResponse))) {
678           FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "Archive/Extract Successful!");
679         } else {
680           // Set the archive status to failure
681           l_estatus = eFrameworkunifiedStatusFail;
682         }
683         if (NULL != l_pCArchive) {  // LCOV_EXCL_BR_LINE 5: l_pCArchive can't be null
684           delete l_pCArchive;
685           l_pCArchive = NULL;
686         }
687       } else {
688         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
689         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Error:FrameworkunifiedGetMsgDataOfSize returned:%d", l_estatus);  // LCOV_EXCL_LINE 4: NSFW error case  // NOLINT[whitespace/line_length]
690       }
691     } else {
692       // LCOV_EXCL_START 4: NSFW error case
693       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
694       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Error:MsgLength: Expected:%ld, Received:%d.",
695              static_cast<long int>(sizeof(l_tArchiveInfo)), FrameworkunifiedGetMsgLength(f_hThread)); // NOLINT (runtime/int)
696       // LCOV_EXCL_STOP
697     }
698
699     if (eFrameworkunifiedStatusOK != l_estatus) {
700       l_tArchiveStatusResponse.m_bpersistencechk = FALSE;
701       FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "Archive/Extract fail.Sending parent message!");
702     } else {
703       l_tArchiveStatusResponse.m_bpersistencechk = TRUE;
704       FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "Archive/Extract success.Sending parent message!");
705     }
706
707     FrameworkunifiedSendParent(f_hThread,  CP_WRK_NTFY, sizeof(NSP_CopyStatusResponse), &l_tArchiveStatusResponse);
708   } else {
709     // LCOV_EXCL_START 6: f_hThread can't be NULL
710     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
711     l_estatus = eFrameworkunifiedStatusFail;
712     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Thread Application Handle NULL");
713     // LCOV_EXCL_STOP
714   }
715
716   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
717   return l_estatus;
718 }
719
720 ////////////////////////////////////////////////////////////////////////////////////////////////////
721 /// NSPCopyWorkerOnStart
722 /// Callback method on start of worker thread
723 ////////////////////////////////////////////////////////////////////////////////////////////////////
724 EFrameworkunifiedStatus NSPCopyWorkerOnStart(HANDLE hthread) {
725   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
726   EFrameworkunifiedStatus l_estatus = eFrameworkunifiedStatusOK;
727
728   if (hthread) {  // LCOV_EXCL_BR_LINE 6: hthread can't be NULL
729     pthread_mutex_lock(&g_mutworkerthread);
730
731     // Note: this variable is made static just to ignore the resource leak showing in coverity analysis
732     static CCopyWorker *l_pccopyworker = NULL;
733
734     l_pccopyworker = new(std::nothrow) CCopyWorker;  // LCOV_EXCL_BR_LINE 11: unexpected branch
735
736     if (NULL != l_pccopyworker) {  // LCOV_EXCL_BR_LINE 5: l_pccopyworker can't be NULL
737       if (eFrameworkunifiedStatusOK == (l_estatus = l_pccopyworker->OnWrkCmdStart(hthread))) {  // LCOV_EXCL_BR_LINE 4: NSFW error case  // NOLINT[whitespace/line_length]
738         l_estatus = FrameworkunifiedSetThreadSpecificData(hthread, l_pccopyworker);
739
740         if (eFrameworkunifiedStatusOK == l_estatus) {  // LCOV_EXCL_BR_LINE 4: NSFW error case
741           l_estatus = FrameworkunifiedAttachCallbacksToDispatcher(
742                         hthread, AppName, aServiceHandlers, static_cast<UI_32>(_countof(aServiceHandlers)));
743
744           if (0 == std::strcmp(NS_NPP_WRITE_THREAD_NAME, FrameworkunifiedGetAppName(hthread))) {
745             l_estatus = FrameworkunifiedAttachCallbackToDispatcher(hthread, AppName,
746                                                       CMD_DELETE_OLD_DATA, NPServiceOnDeleteOldDataCmd);
747           }
748         } else {
749           // LCOV_EXCL_START 4: NSFW error case
750           AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
751           delete l_pccopyworker;
752           l_pccopyworker = NULL;
753           // LCOV_EXCL_STOP
754         }
755       } else {
756         // LCOV_EXCL_START 4: NSFW error case
757         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
758         delete l_pccopyworker;
759         l_pccopyworker = NULL;
760
761         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Thread Start failed.");
762         l_estatus = eFrameworkunifiedStatusFail;
763         // LCOV_EXCL_STOP
764       }
765     } else {
766       // LCOV_EXCL_START 5: l_pccopyworker can't be NULL
767       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
768       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Worker Object Null.");
769       l_estatus = eFrameworkunifiedStatusNullPointer;
770       // LCOV_EXCL_STOP
771     }
772     pthread_mutex_unlock(&g_mutworkerthread);
773   } else {
774     // LCOV_EXCL_START 6: hthread can't be NULL
775     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
776     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Thread App Handle Null.");
777     l_estatus = eFrameworkunifiedStatusInvldHandle;
778     // LCOV_EXCL_STOP
779   }
780
781   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
782   return l_estatus;
783 }
784
785 ////////////////////////////////////////////////////////////////////////////////////////////////////
786 /// NSPCopyWorkerOnStop
787 /// Callback method on stop of worker thread
788 ////////////////////////////////////////////////////////////////////////////////////////////////////
789 EFrameworkunifiedStatus NSPCopyWorkerOnStop(HANDLE hthread) {  // LCOV_EXCL_START 200: can't test
790   AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
791   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
792   EFrameworkunifiedStatus l_estatus = eFrameworkunifiedStatusOK;
793
794   if (NULL != hthread) {
795     pthread_mutex_lock(&g_mutworkerthread);
796     CCopyWorker *l_pccopyworker = static_cast<CCopyWorker *>(FrameworkunifiedGetThreadSpecificData(hthread));
797
798     if (NULL != l_pccopyworker) {
799       l_pccopyworker->OnWrkCmdStop(hthread);
800
801       delete l_pccopyworker;
802       l_pccopyworker = NULL;
803     } else {
804       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Worker Object Null");
805       l_estatus = eFrameworkunifiedStatusNullPointer;
806     }
807
808     if (eFrameworkunifiedStatusOK != (l_estatus = FrameworkunifiedSetThreadSpecificData(hthread, NULL))) {
809       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "FrameworkunifiedSetThreadSpecificData Error, status=%d", l_estatus);
810     }
811
812     PCSTR l_cservice = FrameworkunifiedGetAppName(hthread);
813     if (NULL != l_cservice) {
814       if (eFrameworkunifiedStatusOK != (l_estatus = FrameworkunifiedDetachServiceFromDispatcher(hthread, l_cservice))) {
815         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Error Detaching service %s from dispatcher, status=%d", l_cservice, l_estatus);
816       }
817     } else {
818       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "FrameworkunifiedGetAppName returned NULL");
819       l_estatus = eFrameworkunifiedStatusNullPointer;
820     }
821
822     pthread_mutex_unlock(&g_mutworkerthread);
823   } else {
824     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Thread App Handle Null.");
825     l_estatus = eFrameworkunifiedStatusInvldHandle;
826   }
827   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
828
829   return l_estatus;
830 }
831 // LCOV_EXCL_STOP
832
833 ////////////////////////////////////////////////////////////////////////////////////////////
834 /// NPServiceOnDeleteOldDataCmd
835 /// This callback is used to delete the data which was requested to be deleted during
836 ////////////////////////////////////////////////////////////////////////////////////////////
837 EFrameworkunifiedStatus NPServiceOnDeleteOldDataCmd(HANDLE f_happ) {
838   EFrameworkunifiedStatus l_estatus = eFrameworkunifiedStatusOK;
839   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
840
841   SI_32 l_ithreadcreate = 0;
842   pthread_attr_t l_tattr;
843   struct sched_param l_tschedparam = {};
844
845   // thread id
846   pthread_t childthread = 0;
847
848   if (EOK == pthread_attr_init(&l_tattr)) {  // LCOV_EXCL_BR_LINE 11:except,C++ STL
849     // detach the thread from parent thread
850     if (EOK != pthread_attr_setdetachstate(&l_tattr, PTHREAD_CREATE_DETACHED)) {  // LCOV_EXCL_BR_LINE 11:except,C++ STL
851       // LCOV_EXCL_START 11:except,C++ STL
852       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
853       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
854              "Error setting detach state attribute for thread %s", NS_NPP_DATA_RESET_THREAD_NAME);
855       l_estatus = eFrameworkunifiedStatusFail;
856       // LCOV_EXCL_STOP
857     }
858
859     if (eFrameworkunifiedStatusOK == l_estatus) {  // LCOV_EXCL_BR_LINE 200: l_estatus must be eFrameworkunifiedStatusOK
860       // set the schedule property of thread
861       if (EOK != pthread_attr_setinheritsched(&l_tattr, PTHREAD_EXPLICIT_SCHED)) {  // LCOV_EXCL_BR_LINE 5:except,C++ STL  // NOLINT[whitespace/line_length]
862         // LCOV_EXCL_START 5:except,C++ STL
863         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
864         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
865                "Error setting inherit schedule attribute for thread %s", NS_NPP_DATA_RESET_THREAD_NAME);
866         l_estatus = eFrameworkunifiedStatusFail;
867         // LCOV_EXCL_STOP
868       }
869     }
870
871     if (eFrameworkunifiedStatusOK == l_estatus) {  // LCOV_EXCL_BR_LINE 200: l_estatus must be eFrameworkunifiedStatusOK
872       if (EOK != pthread_attr_getschedparam(&l_tattr, &l_tschedparam)) {  // LCOV_EXCL_BR_LINE 5:except,C++ STL
873         // LCOV_EXCL_START 5:except,C++ STL
874         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
875         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
876                "Error getting schedule param attribute for thread %s", NS_NPP_DATA_RESET_THREAD_NAME);
877         l_estatus = eFrameworkunifiedStatusFail;
878         // LCOV_EXCL_STOP
879       }
880     }
881
882     if (eFrameworkunifiedStatusOK == l_estatus) {  // LCOV_EXCL_BR_LINE 200: l_estatus must be eFrameworkunifiedStatusOK
883       // set the schedule priority of thread
884       l_tschedparam.sched_priority = NS_NPP_DATA_RESET_THREAD_PRIO;
885       if (EOK != pthread_attr_setschedparam(&l_tattr, &l_tschedparam)) {  // LCOV_EXCL_BR_LINE 5:except,C++ STL
886         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
887                "Error setting schedule param attribute for thread %s", NS_NPP_DATA_RESET_THREAD_NAME);
888         l_estatus = eFrameworkunifiedStatusFail;
889       }
890     }
891
892     if (eFrameworkunifiedStatusOK == l_estatus) {
893       // start the child thread
894       if (EOK == (l_ithreadcreate = pthread_create(&childthread, &l_tattr, NSPDataResetThreadCallback, NULL))) {
895         FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__,
896                "Thread id %ld created, name=%s, prio=%d", childthread, NS_NPP_DATA_RESET_THREAD_NAME,
897                NS_NPP_DATA_RESET_THREAD_PRIO);
898       } else {
899         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "pthread_create failed for %s, error = %d", NS_NPP_DATA_RESET_THREAD_NAME,
900                l_ithreadcreate);
901       }
902     }
903
904     // release the thread attribute object
905     pthread_attr_destroy(&l_tattr);
906   } else {
907     // LCOV_EXCL_START 11:except,C++ STL
908     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
909     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Unable to initialize attribute for thread %s", NS_NPP_DATA_RESET_THREAD_NAME);
910     l_estatus = eFrameworkunifiedStatusFail;
911     // LCOV_EXCL_STOP
912   }
913
914   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
915   return l_estatus;
916 }
917
918 ////////////////////////////////////////////////////////////////////////////////////////////
919 /// NSPDataResetThreadCallback
920 /// Callback of data reset thread.
921 ///////////////////////////////////////////////////////////////////////////////////////////
922 PVOID   NSPDataResetThreadCallback(PVOID f_parg) {
923   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
924
925   std::string f_csourcepath = "";
926   std::string f_ctargetpath = "";
927   std::string l_ctargetdir = "";
928
929   DIR *l_pdir = NULL;
930   struct dirent *l_pdirent = NULL;
931
932   // set the name of thread
933   if (EOK == pthread_setname_np(0, NS_NPP_DATA_RESET_THREAD_NAME)) {  // LCOV_EXCL_BR_LINE 5:pthread_setname_np's error case  // NOLINT[whitespace/line_length]
934 #ifdef AGL_STUB
935     FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "Name of thread id %ld set to %s",
936            syscall(__NR_gettid), NS_NPP_DATA_RESET_THREAD_NAME);
937 #else
938     FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "Name of thread id %d set to %s", gettid(), NS_NPP_DATA_RESET_THREAD_NAME);
939 #endif
940   } else {
941     // LCOV_EXCL_START 5:pthread_setname_np's error case
942     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
943 #ifdef AGL_STUB
944     FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, "Error setting name %s for thread-id %ld", NS_NPP_DATA_RESET_THREAD_NAME,
945            syscall(__NR_gettid));
946 #else
947     FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, "Error setting name %s for thread-id %d", NS_NPP_DATA_RESET_THREAD_NAME, gettid());
948 #endif
949     // LCOV_EXCL_STOP
950   }
951
952   f_csourcepath = CPersistence::GetStoragePath();
953   l_pdir = opendir(f_csourcepath.c_str());
954
955   if (NULL != l_pdir) {  // LCOV_EXCL_BR_LINE 5:opendir's error case
956     if ('/' != f_csourcepath[f_csourcepath.length() - 1]) {  // LCOV_EXCL_BR_LINE 200: there must be '/' in f_csourcepath  // NOLINT[whitespace/line_length]
957       f_csourcepath.append("/");
958     }
959
960     /*
961      * Old Persistent data folders which needs to be deleted are renamed with the orignal folder name
962      * followed by underscore and date and time.
963      */
964     std::string l_colduserdata = USERDATA;
965     l_colduserdata.append("_");
966
967     std::string l_coldfactorydata = FACTORYDATA;
968     l_coldfactorydata.append("_");
969
970     std::string l_coldfactorycustomerdata = FACTORYCUSTOMERDATA;
971     l_coldfactorycustomerdata.append("_");
972
973     std::string l_colddealerdata = DEALERDATA;
974     l_colddealerdata.append("_");
975
976     while (NULL != (l_pdirent = readdir(l_pdir))) {
977       l_ctargetdir = l_pdirent->d_name;
978
979       if (0 == l_ctargetdir.find(l_colduserdata) ||
980           0 == l_ctargetdir.find(l_coldfactorydata) ||
981           0 == l_ctargetdir.find(l_coldfactorycustomerdata) ||
982           0 == l_ctargetdir.find(l_colddealerdata)) {
983         f_ctargetpath.assign(f_csourcepath);
984         f_ctargetpath.append(l_ctargetdir);
985
986         if (!CFSDirectory::RemoveDirectory(f_ctargetpath, NS_NPP_REMOVE_DIR_DELAY)) {
987           FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Unable to delete directory :: %s", f_ctargetpath.c_str());
988         }
989       }
990     }
991     closedir(l_pdir);  // close the directory
992   } else {
993     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
994     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Directory does not exists :: %s", f_csourcepath.c_str());  // LCOV_EXCL_LINE 5:opendir's error case  // NOLINT[whitespace/line_length]
995   }
996
997   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
998   return NULL;
999 }
1000
1001 ////////////////////////////////////////////////////////////////////////////////////////////
1002 /// VerifyWithStoredCRC
1003 /// Check if crc of the file passed matches with existing crc of a file
1004 ///////////////////////////////////////////////////////////////////////////////////////////
1005 BOOL CCopyWorker::VerifyWithStoredCRC(PCSTR f_crequesterappname, PCSTR f_cpersistenttag, PCSTR f_cFile,
1006                                       UI_32 &f_ui32crc) {
1007   UI_32 l_ui32StoredCrc = 0;
1008   BOOL l_bRet = FALSE;
1009   EFrameworkunifiedStatus l_estatus = eFrameworkunifiedStatusFail;
1010   TMServiceTagCRC::iterator l_itServiceTag;
1011   TMTagCRC::iterator l_itTagCRC;
1012
1013   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
1014
1015   f_ui32crc = 0;  // initialize with default
1016
1017   if ((NULL != f_crequesterappname) && (NULL != f_cpersistenttag) && (NULL != f_cFile)) {   // LCOV_EXCL_BR_LINE 6: f_crequesterappname, f_cpersistenttag, f_cFile can't be null  // NOLINT[whitespace/line_length]
1018     // Get the existing crc of a file from the map
1019     CCopyWorker::g_objmtxservicetag.ReadLock();
1020     l_itServiceTag = CCopyWorker::g_mservicetagcrc.find(f_crequesterappname);
1021     if (l_itServiceTag != CCopyWorker::g_mservicetagcrc.end()) {
1022       l_itTagCRC = (l_itServiceTag->second).find(f_cpersistenttag);
1023       if (l_itTagCRC != (l_itServiceTag->second).end()) {
1024         l_ui32StoredCrc = (l_itTagCRC->second);
1025         l_estatus = eFrameworkunifiedStatusOK;
1026       } else {
1027         // Do nothing.
1028       }
1029     } else {
1030       // Do nothing.
1031     }
1032     CCopyWorker::g_objmtxservicetag.Unlock();
1033
1034     if (eFrameworkunifiedStatusOK == l_estatus) {
1035       // get the crc of a file
1036       l_estatus = CalculateCRC32(f_cFile, f_ui32crc);
1037       if (eFrameworkunifiedStatusOK == l_estatus) {  // LCOV_EXCL_BR_LINE 200: CalculateCRC32() return ok
1038         if (f_ui32crc == l_ui32StoredCrc) {
1039           l_bRet = TRUE;
1040           FRAMEWORKUNIFIEDLOG(ZONE_NPP_INFO, __FUNCTION__, "CRC matched. crc:%u", l_ui32StoredCrc);
1041         } else {
1042           // Do nothing. Return value already set.
1043           FRAMEWORKUNIFIEDLOG(ZONE_NPP_INFO, __FUNCTION__, "CRC different. stored:%u, new:%u",
1044                  l_ui32StoredCrc, f_ui32crc);
1045         }
1046       } else {
1047         // LCOV_EXCL_START: CalculateCRC32() return ok
1048         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1049         FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, "Warn: getting crc:file:%s, status:%d, errno:%d",
1050                f_cFile, l_estatus, errno);
1051         // LCOV_EXCL_STOP
1052       }
1053     } else {
1054       // Do nothing. Return value already set.
1055     }
1056   } else {
1057     // LCOV_EXCL_START 6: f_crequesterappname, f_cpersistenttag, f_cFile can't be null
1058     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1059     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Invalid param::f_crequesterappname:%p, f_cpersistenttag:%p, f_cFile:%p",
1060            f_crequesterappname, f_cpersistenttag, f_cFile);
1061     // LCOV_EXCL_STOP
1062   }
1063
1064   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
1065   return l_bRet;
1066 }
1067
1068 ////////////////////////////////////////////////////////////////////////////////////////////
1069 /// UpdateTagCRC
1070 /// Update the internal map with new crc
1071 ///////////////////////////////////////////////////////////////////////////////////////////
1072 VOID CCopyWorker::UpdateTagCRC(PCSTR f_crequesterappname, PCSTR f_cpersistenttag, UI_32 f_ui32crc) {
1073   TMServiceTagCRC::iterator l_itServiceTag;
1074   TMTagCRC::iterator l_itTagCRC;
1075
1076   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
1077
1078   CCopyWorker::g_objmtxservicetag.ReadLock();
1079   l_itServiceTag = CCopyWorker::g_mservicetagcrc.find(f_crequesterappname);
1080   if (l_itServiceTag != CCopyWorker::g_mservicetagcrc.end()) {
1081     l_itTagCRC = (l_itServiceTag->second).find(f_cpersistenttag);
1082     if (l_itTagCRC != (l_itServiceTag->second).end()) {
1083       l_itTagCRC->second = f_ui32crc;
1084     } else {
1085       (l_itServiceTag->second).insert(std::make_pair(f_cpersistenttag, f_ui32crc));
1086     }
1087   } else {
1088     TMTagCRC l_mTagCRC;
1089     l_mTagCRC.insert(std::make_pair(f_cpersistenttag, f_ui32crc));
1090     CCopyWorker::g_mservicetagcrc.insert(std::make_pair(f_crequesterappname, l_mTagCRC));
1091   }
1092   CCopyWorker::g_objmtxservicetag.Unlock();
1093   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
1094 }
1095
1096 ////////////////////////////////////////////////////////////////////////////////////////////
1097 /// TryFileCopyWithCRCCheck
1098 /// Try file copy with CRC validation
1099 ///////////////////////////////////////////////////////////////////////////////////////////
1100 EFrameworkunifiedStatus CCopyWorker::TryFileCopyWithCRCCheck(PCSTR f_csource, PCSTR f_cdest, UI_32 f_ui32checkcount) {  // LCOV_EXCL_START 200: cannot test code  // NOLINT[whitespace/line_length]
1101   AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1102   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
1103   UI_32 l_uiSrcFileCrc = 0;
1104   UI_32 l_uiDestFileCrc = 0;
1105   UI_32 l_uiFileSize = 0;
1106   EFrameworkunifiedStatus l_estatus = eFrameworkunifiedStatusOK;
1107
1108   for (UI_16 l_uiCrcCnt = 1; l_uiCrcCnt <= CNSNPP::m_siCRCCheckCount; l_uiCrcCnt++) {
1109     l_uiSrcFileCrc = 0;
1110     l_uiDestFileCrc = 0;
1111     l_uiFileSize = 0;
1112
1113     l_estatus = CopyFile(f_csource, f_cdest, l_uiFileSize, TRUE);
1114     if (eFrameworkunifiedStatusOK == l_estatus) {
1115       // calculate crc of file in temp memory(RAM)
1116       l_estatus = CalculateCRC32(f_csource, l_uiSrcFileCrc);
1117       if (eFrameworkunifiedStatusOK == l_estatus) {
1118         // calculate crc of file stored in persistent memory
1119         l_estatus = CalculateCRC32(f_cdest, l_uiDestFileCrc);
1120         if (eFrameworkunifiedStatusOK == l_estatus) {
1121           if (l_uiSrcFileCrc == l_uiDestFileCrc) {   // if checksum matches for both the files
1122             FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "CRC Checksum matches for file:%s :: 0x%x", f_csource, l_uiSrcFileCrc);
1123             FRAMEWORKUNIFIEDLOG(ZONE_PRD_INFO3, __FUNCTION__, "Bytes written:%d file=%s",
1124                    l_uiFileSize, f_cdest);
1125             break;
1126           } else {  // else delete the file from target
1127             FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "CRC doesn't match for src:%s::0x%x and dest:%s::0x%x, CRC cnt=%d",
1128                    f_csource, l_uiSrcFileCrc, f_cdest, l_uiDestFileCrc, l_uiCrcCnt);
1129             // if the checksum does not matches even for the last time, do not delete the file from target
1130             if (l_uiCrcCnt < (CNSNPP::m_siCRCCheckCount)) {
1131               if (0 != remove(f_cdest)) {
1132                 FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, "Error deleting file:%s, errno:%d", f_cdest, errno);
1133               }
1134             }
1135           }
1136         } else {
1137           FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Error Calculating Checksum for DestFile:%s",
1138                  f_cdest != 0 ? f_cdest : NULL);
1139           l_estatus = eFrameworkunifiedStatusFail;
1140         }
1141       } else {
1142         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Error Calculating Checksum for SrcFile:%s",
1143                f_csource != 0 ? f_csource : NULL);
1144         l_estatus = eFrameworkunifiedStatusFail;
1145       }
1146     } else {
1147       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "FileCopy Error:%d", l_estatus);
1148     }
1149   }
1150   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
1151   return l_estatus;
1152 }
1153 // LCOV_EXCL_STOP