oem-ibm: inband: Remove the lid header

The host sends the LID files with a header that needs to be
stripped out before adding it to the code update image.

Since the write interface is not unique to the inband update
process, we can't strip the header there, so need to make a
copy of the lid file without the header. Remove the original
one once the lid without header has been created.

Change-Id: Id1e009e1716e3103bc38f7111ba1865228db2bad
Signed-off-by: Adriana Kobylak <anoo@us.ibm.com>
diff --git a/meson.build b/meson.build
index acd0e98..93ca718 100644
--- a/meson.build
+++ b/meson.build
@@ -27,6 +27,7 @@
   conf_data.set_quoted('FILE_TABLE_JSON', '/usr/share/pldm/fileTable.json')
   conf_data.set_quoted('LID_RUNNING_DIR', '/var/lib/phosphor-software-manager/hostfw/running')
   conf_data.set_quoted('LID_ALTERNATE_DIR', '/var/lib/phosphor-software-manager/hostfw/alternate')
+  conf_data.set_quoted('LID_STAGING_DIR', '/var/lib/phosphor-software-manager/hostfw/staging')
   conf_data.set_quoted('LID_RUNNING_PATCH_DIR', '/usr/local/share/hostfw/running')
   conf_data.set_quoted('LID_ALTERNATE_PATCH_DIR', '/usr/local/share/hostfw/alternate')
   conf_data.set_quoted('LID_STAGING_DIR', '/var/lib/phosphor-software-manager/hostfw/staging')
diff --git a/oem/ibm/libpldmresponder/inband_code_update.cpp b/oem/ibm/libpldmresponder/inband_code_update.cpp
index 2023a99..101025e 100644
--- a/oem/ibm/libpldmresponder/inband_code_update.cpp
+++ b/oem/ibm/libpldmresponder/inband_code_update.cpp
@@ -20,6 +20,9 @@
 {
 using namespace oem_ibm_platform;
 
+/** @brief Directory where the lid files without a header are stored */
+auto lidDirPath = fs::path(LID_STAGING_DIR) / "lid";
+
 std::string CodeUpdate::fetchCurrentBootSide()
 {
     return currBootSide;
@@ -240,7 +243,6 @@
     }
     ifs.seekg(0);
     ifs.read(reinterpret_cast<char*>(&header), sizeof(header));
-    ifs.close();
 
     // File size should be the value of lid size minus the header size
     auto fileSize = fs::file_size(filePath);
@@ -248,6 +250,7 @@
     if (fileSize < htonl(header.lidSize))
     {
         // File is not completely written yet
+        ifs.close();
         return PLDM_SUCCESS;
     }
 
@@ -255,9 +258,24 @@
     if (htons(header.magicNumber) != magicNumber)
     {
         std::cerr << "Invalid magic number: " << filePath << "\n";
+        ifs.close();
         return PLDM_ERROR;
     }
 
+    fs::create_directories(lidDirPath);
+
+    std::stringstream lidFileName;
+    lidFileName << std::hex << htonl(header.lidNumber) << ".lid";
+    auto lidNoHeaderPath = fs::path(lidDirPath) / lidFileName.str();
+    std::ofstream ofs(lidNoHeaderPath,
+                      std::ios::out | std::ios::binary | std::ios::trunc);
+    ifs.seekg(htonl(header.headerSize));
+    ofs << ifs.rdbuf();
+    ofs.flush();
+    ofs.close();
+
+    ifs.close();
+    fs::remove(filePath);
     return PLDM_SUCCESS;
 }