xref: /openbmc/bmcweb/features/redfish/lib/log_services.hpp (revision 50b8a43af501412f93a93ccce34a9ea7abb6d57f)
1 /*
2 // Copyright (c) 2018 Intel 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 #pragma once
17 
18 #include "gzfile.hpp"
19 #include "http_utility.hpp"
20 #include "human_sort.hpp"
21 #include "registries.hpp"
22 #include "registries/base_message_registry.hpp"
23 #include "registries/openbmc_message_registry.hpp"
24 #include "task.hpp"
25 
26 #include <systemd/sd-journal.h>
27 #include <unistd.h>
28 
29 #include <app.hpp>
30 #include <boost/algorithm/string/replace.hpp>
31 #include <boost/algorithm/string/split.hpp>
32 #include <boost/beast/http.hpp>
33 #include <boost/container/flat_map.hpp>
34 #include <boost/system/linux_error.hpp>
35 #include <dbus_utility.hpp>
36 #include <error_messages.hpp>
37 #include <registries/privilege_registry.hpp>
38 
39 #include <charconv>
40 #include <filesystem>
41 #include <optional>
42 #include <span>
43 #include <string_view>
44 #include <variant>
45 
46 namespace redfish
47 {
48 
49 constexpr char const* crashdumpObject = "com.intel.crashdump";
50 constexpr char const* crashdumpPath = "/com/intel/crashdump";
51 constexpr char const* crashdumpInterface = "com.intel.crashdump";
52 constexpr char const* deleteAllInterface =
53     "xyz.openbmc_project.Collection.DeleteAll";
54 constexpr char const* crashdumpOnDemandInterface =
55     "com.intel.crashdump.OnDemand";
56 constexpr char const* crashdumpTelemetryInterface =
57     "com.intel.crashdump.Telemetry";
58 
59 namespace message_registries
60 {
61 static const Message*
62     getMessageFromRegistry(const std::string& messageKey,
63                            const std::span<const MessageEntry> registry)
64 {
65     std::span<const MessageEntry>::iterator messageIt = std::find_if(
66         registry.begin(), registry.end(),
67         [&messageKey](const MessageEntry& messageEntry) {
68             return !std::strcmp(messageEntry.first, messageKey.c_str());
69         });
70     if (messageIt != registry.end())
71     {
72         return &messageIt->second;
73     }
74 
75     return nullptr;
76 }
77 
78 static const Message* getMessage(const std::string_view& messageID)
79 {
80     // Redfish MessageIds are in the form
81     // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find
82     // the right Message
83     std::vector<std::string> fields;
84     fields.reserve(4);
85     boost::split(fields, messageID, boost::is_any_of("."));
86     std::string& registryName = fields[0];
87     std::string& messageKey = fields[3];
88 
89     // Find the right registry and check it for the MessageKey
90     if (std::string(base::header.registryPrefix) == registryName)
91     {
92         return getMessageFromRegistry(
93             messageKey, std::span<const MessageEntry>(base::registry));
94     }
95     if (std::string(openbmc::header.registryPrefix) == registryName)
96     {
97         return getMessageFromRegistry(
98             messageKey, std::span<const MessageEntry>(openbmc::registry));
99     }
100     return nullptr;
101 }
102 } // namespace message_registries
103 
104 namespace fs = std::filesystem;
105 
106 using GetManagedPropertyType =
107     boost::container::flat_map<std::string, dbus::utility::DbusVariantType>;
108 
109 inline std::string translateSeverityDbusToRedfish(const std::string& s)
110 {
111     if ((s == "xyz.openbmc_project.Logging.Entry.Level.Alert") ||
112         (s == "xyz.openbmc_project.Logging.Entry.Level.Critical") ||
113         (s == "xyz.openbmc_project.Logging.Entry.Level.Emergency") ||
114         (s == "xyz.openbmc_project.Logging.Entry.Level.Error"))
115     {
116         return "Critical";
117     }
118     if ((s == "xyz.openbmc_project.Logging.Entry.Level.Debug") ||
119         (s == "xyz.openbmc_project.Logging.Entry.Level.Informational") ||
120         (s == "xyz.openbmc_project.Logging.Entry.Level.Notice"))
121     {
122         return "OK";
123     }
124     if (s == "xyz.openbmc_project.Logging.Entry.Level.Warning")
125     {
126         return "Warning";
127     }
128     return "";
129 }
130 
131 inline static int getJournalMetadata(sd_journal* journal,
132                                      const std::string_view& field,
133                                      std::string_view& contents)
134 {
135     const char* data = nullptr;
136     size_t length = 0;
137     int ret = 0;
138     // Get the metadata from the requested field of the journal entry
139     // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
140     const void** dataVoid = reinterpret_cast<const void**>(&data);
141 
142     ret = sd_journal_get_data(journal, field.data(), dataVoid, &length);
143     if (ret < 0)
144     {
145         return ret;
146     }
147     contents = std::string_view(data, length);
148     // Only use the content after the "=" character.
149     contents.remove_prefix(std::min(contents.find('=') + 1, contents.size()));
150     return ret;
151 }
152 
153 inline static int getJournalMetadata(sd_journal* journal,
154                                      const std::string_view& field,
155                                      const int& base, long int& contents)
156 {
157     int ret = 0;
158     std::string_view metadata;
159     // Get the metadata from the requested field of the journal entry
160     ret = getJournalMetadata(journal, field, metadata);
161     if (ret < 0)
162     {
163         return ret;
164     }
165     contents = strtol(metadata.data(), nullptr, base);
166     return ret;
167 }
168 
169 inline static bool getEntryTimestamp(sd_journal* journal,
170                                      std::string& entryTimestamp)
171 {
172     int ret = 0;
173     uint64_t timestamp = 0;
174     ret = sd_journal_get_realtime_usec(journal, &timestamp);
175     if (ret < 0)
176     {
177         BMCWEB_LOG_ERROR << "Failed to read entry timestamp: "
178                          << strerror(-ret);
179         return false;
180     }
181     entryTimestamp = crow::utility::getDateTimeUint(timestamp / 1000 / 1000);
182     return true;
183 }
184 
185 static bool getSkipParam(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
186                          const crow::Request& req, uint64_t& skip)
187 {
188     boost::urls::params_view::iterator it = req.urlView.params().find("$skip");
189     if (it != req.urlView.params().end())
190     {
191         std::from_chars_result r = std::from_chars(
192             (*it).value.data(), (*it).value.data() + (*it).value.size(), skip);
193         if (r.ec != std::errc())
194         {
195             messages::queryParameterValueTypeError(asyncResp->res, "", "$skip");
196             return false;
197         }
198     }
199     return true;
200 }
201 
202 static constexpr const uint64_t maxEntriesPerPage = 1000;
203 static bool getTopParam(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
204                         const crow::Request& req, uint64_t& top)
205 {
206     boost::urls::params_view::iterator it = req.urlView.params().find("$top");
207     if (it != req.urlView.params().end())
208     {
209         std::from_chars_result r = std::from_chars(
210             (*it).value.data(), (*it).value.data() + (*it).value.size(), top);
211         if (r.ec != std::errc())
212         {
213             messages::queryParameterValueTypeError(asyncResp->res, "", "$top");
214             return false;
215         }
216         if (top < 1U || top > maxEntriesPerPage)
217         {
218 
219             messages::queryParameterOutOfRange(
220                 asyncResp->res, std::to_string(top), "$top",
221                 "1-" + std::to_string(maxEntriesPerPage));
222             return false;
223         }
224     }
225     return true;
226 }
227 
228 inline static bool getUniqueEntryID(sd_journal* journal, std::string& entryID,
229                                     const bool firstEntry = true)
230 {
231     int ret = 0;
232     static uint64_t prevTs = 0;
233     static int index = 0;
234     if (firstEntry)
235     {
236         prevTs = 0;
237     }
238 
239     // Get the entry timestamp
240     uint64_t curTs = 0;
241     ret = sd_journal_get_realtime_usec(journal, &curTs);
242     if (ret < 0)
243     {
244         BMCWEB_LOG_ERROR << "Failed to read entry timestamp: "
245                          << strerror(-ret);
246         return false;
247     }
248     // If the timestamp isn't unique, increment the index
249     if (curTs == prevTs)
250     {
251         index++;
252     }
253     else
254     {
255         // Otherwise, reset it
256         index = 0;
257     }
258     // Save the timestamp
259     prevTs = curTs;
260 
261     entryID = std::to_string(curTs);
262     if (index > 0)
263     {
264         entryID += "_" + std::to_string(index);
265     }
266     return true;
267 }
268 
269 static bool getUniqueEntryID(const std::string& logEntry, std::string& entryID,
270                              const bool firstEntry = true)
271 {
272     static time_t prevTs = 0;
273     static int index = 0;
274     if (firstEntry)
275     {
276         prevTs = 0;
277     }
278 
279     // Get the entry timestamp
280     std::time_t curTs = 0;
281     std::tm timeStruct = {};
282     std::istringstream entryStream(logEntry);
283     if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
284     {
285         curTs = std::mktime(&timeStruct);
286     }
287     // If the timestamp isn't unique, increment the index
288     if (curTs == prevTs)
289     {
290         index++;
291     }
292     else
293     {
294         // Otherwise, reset it
295         index = 0;
296     }
297     // Save the timestamp
298     prevTs = curTs;
299 
300     entryID = std::to_string(curTs);
301     if (index > 0)
302     {
303         entryID += "_" + std::to_string(index);
304     }
305     return true;
306 }
307 
308 inline static bool
309     getTimestampFromID(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
310                        const std::string& entryID, uint64_t& timestamp,
311                        uint64_t& index)
312 {
313     if (entryID.empty())
314     {
315         return false;
316     }
317     // Convert the unique ID back to a timestamp to find the entry
318     std::string_view tsStr(entryID);
319 
320     auto underscorePos = tsStr.find('_');
321     if (underscorePos != tsStr.npos)
322     {
323         // Timestamp has an index
324         tsStr.remove_suffix(tsStr.size() - underscorePos);
325         std::string_view indexStr(entryID);
326         indexStr.remove_prefix(underscorePos + 1);
327         auto [ptr, ec] = std::from_chars(
328             indexStr.data(), indexStr.data() + indexStr.size(), index);
329         if (ec != std::errc())
330         {
331             messages::resourceMissingAtURI(asyncResp->res, entryID);
332             return false;
333         }
334     }
335     // Timestamp has no index
336     auto [ptr, ec] =
337         std::from_chars(tsStr.data(), tsStr.data() + tsStr.size(), timestamp);
338     if (ec != std::errc())
339     {
340         messages::resourceMissingAtURI(asyncResp->res, entryID);
341         return false;
342     }
343     return true;
344 }
345 
346 static bool
347     getRedfishLogFiles(std::vector<std::filesystem::path>& redfishLogFiles)
348 {
349     static const std::filesystem::path redfishLogDir = "/var/log";
350     static const std::string redfishLogFilename = "redfish";
351 
352     // Loop through the directory looking for redfish log files
353     for (const std::filesystem::directory_entry& dirEnt :
354          std::filesystem::directory_iterator(redfishLogDir))
355     {
356         // If we find a redfish log file, save the path
357         std::string filename = dirEnt.path().filename();
358         if (boost::starts_with(filename, redfishLogFilename))
359         {
360             redfishLogFiles.emplace_back(redfishLogDir / filename);
361         }
362     }
363     // As the log files rotate, they are appended with a ".#" that is higher for
364     // the older logs. Since we don't expect more than 10 log files, we
365     // can just sort the list to get them in order from newest to oldest
366     std::sort(redfishLogFiles.begin(), redfishLogFiles.end());
367 
368     return !redfishLogFiles.empty();
369 }
370 
371 inline void
372     getDumpEntryCollection(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
373                            const std::string& dumpType)
374 {
375     std::string dumpPath;
376     if (dumpType == "BMC")
377     {
378         dumpPath = "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/";
379     }
380     else if (dumpType == "System")
381     {
382         dumpPath = "/redfish/v1/Systems/system/LogServices/Dump/Entries/";
383     }
384     else
385     {
386         BMCWEB_LOG_ERROR << "Invalid dump type" << dumpType;
387         messages::internalError(asyncResp->res);
388         return;
389     }
390 
391     crow::connections::systemBus->async_method_call(
392         [asyncResp, dumpPath,
393          dumpType](const boost::system::error_code ec,
394                    dbus::utility::ManagedObjectType& resp) {
395             if (ec)
396             {
397                 BMCWEB_LOG_ERROR << "DumpEntry resp_handler got error " << ec;
398                 messages::internalError(asyncResp->res);
399                 return;
400             }
401 
402             nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"];
403             entriesArray = nlohmann::json::array();
404             std::string dumpEntryPath =
405                 "/xyz/openbmc_project/dump/" +
406                 std::string(boost::algorithm::to_lower_copy(dumpType)) +
407                 "/entry/";
408 
409             for (auto& object : resp)
410             {
411                 if (object.first.str.find(dumpEntryPath) == std::string::npos)
412                 {
413                     continue;
414                 }
415                 uint64_t timestamp = 0;
416                 uint64_t size = 0;
417                 std::string dumpStatus;
418                 nlohmann::json thisEntry;
419 
420                 std::string entryID = object.first.filename();
421                 if (entryID.empty())
422                 {
423                     continue;
424                 }
425 
426                 for (auto& interfaceMap : object.second)
427                 {
428                     if (interfaceMap.first ==
429                         "xyz.openbmc_project.Common.Progress")
430                     {
431                         for (auto& propertyMap : interfaceMap.second)
432                         {
433                             if (propertyMap.first == "Status")
434                             {
435                                 auto status = std::get_if<std::string>(
436                                     &propertyMap.second);
437                                 if (status == nullptr)
438                                 {
439                                     messages::internalError(asyncResp->res);
440                                     break;
441                                 }
442                                 dumpStatus = *status;
443                             }
444                         }
445                     }
446                     else if (interfaceMap.first ==
447                              "xyz.openbmc_project.Dump.Entry")
448                     {
449 
450                         for (auto& propertyMap : interfaceMap.second)
451                         {
452                             if (propertyMap.first == "Size")
453                             {
454                                 auto sizePtr =
455                                     std::get_if<uint64_t>(&propertyMap.second);
456                                 if (sizePtr == nullptr)
457                                 {
458                                     messages::internalError(asyncResp->res);
459                                     break;
460                                 }
461                                 size = *sizePtr;
462                                 break;
463                             }
464                         }
465                     }
466                     else if (interfaceMap.first ==
467                              "xyz.openbmc_project.Time.EpochTime")
468                     {
469 
470                         for (auto& propertyMap : interfaceMap.second)
471                         {
472                             if (propertyMap.first == "Elapsed")
473                             {
474                                 const uint64_t* usecsTimeStamp =
475                                     std::get_if<uint64_t>(&propertyMap.second);
476                                 if (usecsTimeStamp == nullptr)
477                                 {
478                                     messages::internalError(asyncResp->res);
479                                     break;
480                                 }
481                                 timestamp = (*usecsTimeStamp / 1000 / 1000);
482                                 break;
483                             }
484                         }
485                     }
486                 }
487 
488                 if (dumpStatus !=
489                         "xyz.openbmc_project.Common.Progress.OperationStatus.Completed" &&
490                     !dumpStatus.empty())
491                 {
492                     // Dump status is not Complete, no need to enumerate
493                     continue;
494                 }
495 
496                 thisEntry["@odata.type"] = "#LogEntry.v1_8_0.LogEntry";
497                 thisEntry["@odata.id"] = dumpPath + entryID;
498                 thisEntry["Id"] = entryID;
499                 thisEntry["EntryType"] = "Event";
500                 thisEntry["Created"] =
501                     crow::utility::getDateTimeUint(timestamp);
502                 thisEntry["Name"] = dumpType + " Dump Entry";
503 
504                 thisEntry["AdditionalDataSizeBytes"] = size;
505 
506                 if (dumpType == "BMC")
507                 {
508                     thisEntry["DiagnosticDataType"] = "Manager";
509                     thisEntry["AdditionalDataURI"] =
510                         "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/" +
511                         entryID + "/attachment";
512                 }
513                 else if (dumpType == "System")
514                 {
515                     thisEntry["DiagnosticDataType"] = "OEM";
516                     thisEntry["OEMDiagnosticDataType"] = "System";
517                     thisEntry["AdditionalDataURI"] =
518                         "/redfish/v1/Systems/system/LogServices/Dump/Entries/" +
519                         entryID + "/attachment";
520                 }
521                 entriesArray.push_back(std::move(thisEntry));
522             }
523             asyncResp->res.jsonValue["Members@odata.count"] =
524                 entriesArray.size();
525         },
526         "xyz.openbmc_project.Dump.Manager", "/xyz/openbmc_project/dump",
527         "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
528 }
529 
530 inline void
531     getDumpEntryById(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
532                      const std::string& entryID, const std::string& dumpType)
533 {
534     std::string dumpPath;
535     if (dumpType == "BMC")
536     {
537         dumpPath = "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/";
538     }
539     else if (dumpType == "System")
540     {
541         dumpPath = "/redfish/v1/Systems/system/LogServices/Dump/Entries/";
542     }
543     else
544     {
545         BMCWEB_LOG_ERROR << "Invalid dump type" << dumpType;
546         messages::internalError(asyncResp->res);
547         return;
548     }
549 
550     crow::connections::systemBus->async_method_call(
551         [asyncResp, entryID, dumpPath,
552          dumpType](const boost::system::error_code ec,
553                    dbus::utility::ManagedObjectType& resp) {
554             if (ec)
555             {
556                 BMCWEB_LOG_ERROR << "DumpEntry resp_handler got error " << ec;
557                 messages::internalError(asyncResp->res);
558                 return;
559             }
560 
561             bool foundDumpEntry = false;
562             std::string dumpEntryPath =
563                 "/xyz/openbmc_project/dump/" +
564                 std::string(boost::algorithm::to_lower_copy(dumpType)) +
565                 "/entry/";
566 
567             for (auto& objectPath : resp)
568             {
569                 if (objectPath.first.str != dumpEntryPath + entryID)
570                 {
571                     continue;
572                 }
573 
574                 foundDumpEntry = true;
575                 uint64_t timestamp = 0;
576                 uint64_t size = 0;
577                 std::string dumpStatus;
578 
579                 for (auto& interfaceMap : objectPath.second)
580                 {
581                     if (interfaceMap.first ==
582                         "xyz.openbmc_project.Common.Progress")
583                     {
584                         for (auto& propertyMap : interfaceMap.second)
585                         {
586                             if (propertyMap.first == "Status")
587                             {
588                                 auto status = std::get_if<std::string>(
589                                     &propertyMap.second);
590                                 if (status == nullptr)
591                                 {
592                                     messages::internalError(asyncResp->res);
593                                     break;
594                                 }
595                                 dumpStatus = *status;
596                             }
597                         }
598                     }
599                     else if (interfaceMap.first ==
600                              "xyz.openbmc_project.Dump.Entry")
601                     {
602                         for (auto& propertyMap : interfaceMap.second)
603                         {
604                             if (propertyMap.first == "Size")
605                             {
606                                 auto sizePtr =
607                                     std::get_if<uint64_t>(&propertyMap.second);
608                                 if (sizePtr == nullptr)
609                                 {
610                                     messages::internalError(asyncResp->res);
611                                     break;
612                                 }
613                                 size = *sizePtr;
614                                 break;
615                             }
616                         }
617                     }
618                     else if (interfaceMap.first ==
619                              "xyz.openbmc_project.Time.EpochTime")
620                     {
621                         for (auto& propertyMap : interfaceMap.second)
622                         {
623                             if (propertyMap.first == "Elapsed")
624                             {
625                                 const uint64_t* usecsTimeStamp =
626                                     std::get_if<uint64_t>(&propertyMap.second);
627                                 if (usecsTimeStamp == nullptr)
628                                 {
629                                     messages::internalError(asyncResp->res);
630                                     break;
631                                 }
632                                 timestamp = *usecsTimeStamp / 1000 / 1000;
633                                 break;
634                             }
635                         }
636                     }
637                 }
638 
639                 if (dumpStatus !=
640                         "xyz.openbmc_project.Common.Progress.OperationStatus.Completed" &&
641                     !dumpStatus.empty())
642                 {
643                     // Dump status is not Complete
644                     // return not found until status is changed to Completed
645                     messages::resourceNotFound(asyncResp->res,
646                                                dumpType + " dump", entryID);
647                     return;
648                 }
649 
650                 asyncResp->res.jsonValue["@odata.type"] =
651                     "#LogEntry.v1_8_0.LogEntry";
652                 asyncResp->res.jsonValue["@odata.id"] = dumpPath + entryID;
653                 asyncResp->res.jsonValue["Id"] = entryID;
654                 asyncResp->res.jsonValue["EntryType"] = "Event";
655                 asyncResp->res.jsonValue["Created"] =
656                     crow::utility::getDateTimeUint(timestamp);
657                 asyncResp->res.jsonValue["Name"] = dumpType + " Dump Entry";
658 
659                 asyncResp->res.jsonValue["AdditionalDataSizeBytes"] = size;
660 
661                 if (dumpType == "BMC")
662                 {
663                     asyncResp->res.jsonValue["DiagnosticDataType"] = "Manager";
664                     asyncResp->res.jsonValue["AdditionalDataURI"] =
665                         "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/" +
666                         entryID + "/attachment";
667                 }
668                 else if (dumpType == "System")
669                 {
670                     asyncResp->res.jsonValue["DiagnosticDataType"] = "OEM";
671                     asyncResp->res.jsonValue["OEMDiagnosticDataType"] =
672                         "System";
673                     asyncResp->res.jsonValue["AdditionalDataURI"] =
674                         "/redfish/v1/Systems/system/LogServices/Dump/Entries/" +
675                         entryID + "/attachment";
676                 }
677             }
678             if (foundDumpEntry == false)
679             {
680                 BMCWEB_LOG_ERROR << "Can't find Dump Entry";
681                 messages::internalError(asyncResp->res);
682                 return;
683             }
684         },
685         "xyz.openbmc_project.Dump.Manager", "/xyz/openbmc_project/dump",
686         "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
687 }
688 
689 inline void deleteDumpEntry(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
690                             const std::string& entryID,
691                             const std::string& dumpType)
692 {
693     auto respHandler = [asyncResp,
694                         entryID](const boost::system::error_code ec) {
695         BMCWEB_LOG_DEBUG << "Dump Entry doDelete callback: Done";
696         if (ec)
697         {
698             if (ec.value() == EBADR)
699             {
700                 messages::resourceNotFound(asyncResp->res, "LogEntry", entryID);
701                 return;
702             }
703             BMCWEB_LOG_ERROR << "Dump (DBus) doDelete respHandler got error "
704                              << ec;
705             messages::internalError(asyncResp->res);
706             return;
707         }
708     };
709     crow::connections::systemBus->async_method_call(
710         respHandler, "xyz.openbmc_project.Dump.Manager",
711         "/xyz/openbmc_project/dump/" +
712             std::string(boost::algorithm::to_lower_copy(dumpType)) + "/entry/" +
713             entryID,
714         "xyz.openbmc_project.Object.Delete", "Delete");
715 }
716 
717 inline void
718     createDumpTaskCallback(task::Payload&& payload,
719                            const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
720                            const uint32_t& dumpId, const std::string& dumpPath,
721                            const std::string& dumpType)
722 {
723     std::shared_ptr<task::TaskData> task = task::TaskData::createTask(
724         [dumpId, dumpPath, dumpType](
725             boost::system::error_code err, sdbusplus::message::message& m,
726             const std::shared_ptr<task::TaskData>& taskData) {
727             if (err)
728             {
729                 BMCWEB_LOG_ERROR << "Error in creating a dump";
730                 taskData->state = "Cancelled";
731                 return task::completed;
732             }
733             std::vector<std::pair<
734                 std::string, std::vector<std::pair<
735                                  std::string, dbus::utility::DbusVariantType>>>>
736                 interfacesList;
737 
738             sdbusplus::message::object_path objPath;
739 
740             m.read(objPath, interfacesList);
741 
742             if (objPath.str ==
743                 "/xyz/openbmc_project/dump/" +
744                     std::string(boost::algorithm::to_lower_copy(dumpType)) +
745                     "/entry/" + std::to_string(dumpId))
746             {
747                 nlohmann::json retMessage = messages::success();
748                 taskData->messages.emplace_back(retMessage);
749 
750                 std::string headerLoc =
751                     "Location: " + dumpPath + std::to_string(dumpId);
752                 taskData->payload->httpHeaders.emplace_back(
753                     std::move(headerLoc));
754 
755                 taskData->state = "Completed";
756                 return task::completed;
757             }
758             return task::completed;
759         },
760         "type='signal',interface='org.freedesktop.DBus."
761         "ObjectManager',"
762         "member='InterfacesAdded', "
763         "path='/xyz/openbmc_project/dump'");
764 
765     task->startTimer(std::chrono::minutes(3));
766     task->populateResp(asyncResp->res);
767     task->payload.emplace(std::move(payload));
768 }
769 
770 inline void createDump(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
771                        const crow::Request& req, const std::string& dumpType)
772 {
773 
774     std::string dumpPath;
775     if (dumpType == "BMC")
776     {
777         dumpPath = "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/";
778     }
779     else if (dumpType == "System")
780     {
781         dumpPath = "/redfish/v1/Systems/system/LogServices/Dump/Entries/";
782     }
783     else
784     {
785         BMCWEB_LOG_ERROR << "Invalid dump type: " << dumpType;
786         messages::internalError(asyncResp->res);
787         return;
788     }
789 
790     std::optional<std::string> diagnosticDataType;
791     std::optional<std::string> oemDiagnosticDataType;
792 
793     if (!redfish::json_util::readJson(
794             req, asyncResp->res, "DiagnosticDataType", diagnosticDataType,
795             "OEMDiagnosticDataType", oemDiagnosticDataType))
796     {
797         return;
798     }
799 
800     if (dumpType == "System")
801     {
802         if (!oemDiagnosticDataType || !diagnosticDataType)
803         {
804             BMCWEB_LOG_ERROR << "CreateDump action parameter "
805                                 "'DiagnosticDataType'/"
806                                 "'OEMDiagnosticDataType' value not found!";
807             messages::actionParameterMissing(
808                 asyncResp->res, "CollectDiagnosticData",
809                 "DiagnosticDataType & OEMDiagnosticDataType");
810             return;
811         }
812         if ((*oemDiagnosticDataType != "System") ||
813             (*diagnosticDataType != "OEM"))
814         {
815             BMCWEB_LOG_ERROR << "Wrong parameter values passed";
816             messages::invalidObject(asyncResp->res,
817                                     "System Dump creation parameters");
818             return;
819         }
820     }
821     else if (dumpType == "BMC")
822     {
823         if (!diagnosticDataType)
824         {
825             BMCWEB_LOG_ERROR
826                 << "CreateDump action parameter 'DiagnosticDataType' not found!";
827             messages::actionParameterMissing(
828                 asyncResp->res, "CollectDiagnosticData", "DiagnosticDataType");
829             return;
830         }
831         if (*diagnosticDataType != "Manager")
832         {
833             BMCWEB_LOG_ERROR
834                 << "Wrong parameter value passed for 'DiagnosticDataType'";
835             messages::invalidObject(asyncResp->res,
836                                     "BMC Dump creation parameters");
837             return;
838         }
839     }
840 
841     crow::connections::systemBus->async_method_call(
842         [asyncResp, payload(task::Payload(req)), dumpPath,
843          dumpType](const boost::system::error_code ec,
844                    const uint32_t& dumpId) mutable {
845             if (ec)
846             {
847                 BMCWEB_LOG_ERROR << "CreateDump resp_handler got error " << ec;
848                 messages::internalError(asyncResp->res);
849                 return;
850             }
851             BMCWEB_LOG_DEBUG << "Dump Created. Id: " << dumpId;
852 
853             createDumpTaskCallback(std::move(payload), asyncResp, dumpId,
854                                    dumpPath, dumpType);
855         },
856         "xyz.openbmc_project.Dump.Manager",
857         "/xyz/openbmc_project/dump/" +
858             std::string(boost::algorithm::to_lower_copy(dumpType)),
859         "xyz.openbmc_project.Dump.Create", "CreateDump");
860 }
861 
862 inline void clearDump(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
863                       const std::string& dumpType)
864 {
865     std::string dumpTypeLowerCopy =
866         std::string(boost::algorithm::to_lower_copy(dumpType));
867 
868     crow::connections::systemBus->async_method_call(
869         [asyncResp, dumpType](const boost::system::error_code ec,
870                               const std::vector<std::string>& subTreePaths) {
871             if (ec)
872             {
873                 BMCWEB_LOG_ERROR << "resp_handler got error " << ec;
874                 messages::internalError(asyncResp->res);
875                 return;
876             }
877 
878             for (const std::string& path : subTreePaths)
879             {
880                 sdbusplus::message::object_path objPath(path);
881                 std::string logID = objPath.filename();
882                 if (logID.empty())
883                 {
884                     continue;
885                 }
886                 deleteDumpEntry(asyncResp, logID, dumpType);
887             }
888         },
889         "xyz.openbmc_project.ObjectMapper",
890         "/xyz/openbmc_project/object_mapper",
891         "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths",
892         "/xyz/openbmc_project/dump/" + dumpTypeLowerCopy, 0,
893         std::array<std::string, 1>{"xyz.openbmc_project.Dump.Entry." +
894                                    dumpType});
895 }
896 
897 inline static void parseCrashdumpParameters(
898     const std::vector<std::pair<std::string, dbus::utility::DbusVariantType>>&
899         params,
900     std::string& filename, std::string& timestamp, std::string& logfile)
901 {
902     for (auto property : params)
903     {
904         if (property.first == "Timestamp")
905         {
906             const std::string* value =
907                 std::get_if<std::string>(&property.second);
908             if (value != nullptr)
909             {
910                 timestamp = *value;
911             }
912         }
913         else if (property.first == "Filename")
914         {
915             const std::string* value =
916                 std::get_if<std::string>(&property.second);
917             if (value != nullptr)
918             {
919                 filename = *value;
920             }
921         }
922         else if (property.first == "Log")
923         {
924             const std::string* value =
925                 std::get_if<std::string>(&property.second);
926             if (value != nullptr)
927             {
928                 logfile = *value;
929             }
930         }
931     }
932 }
933 
934 constexpr char const* postCodeIface = "xyz.openbmc_project.State.Boot.PostCode";
935 inline void requestRoutesSystemLogServiceCollection(App& app)
936 {
937     /**
938      * Functions triggers appropriate requests on DBus
939      */
940     BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/")
941         .privileges(redfish::privileges::getLogServiceCollection)
942         .methods(boost::beast::http::verb::get)(
943             [](const crow::Request&,
944                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
945 
946             {
947                 // Collections don't include the static data added by SubRoute
948                 // because it has a duplicate entry for members
949                 asyncResp->res.jsonValue["@odata.type"] =
950                     "#LogServiceCollection.LogServiceCollection";
951                 asyncResp->res.jsonValue["@odata.id"] =
952                     "/redfish/v1/Systems/system/LogServices";
953                 asyncResp->res.jsonValue["Name"] =
954                     "System Log Services Collection";
955                 asyncResp->res.jsonValue["Description"] =
956                     "Collection of LogServices for this Computer System";
957                 nlohmann::json& logServiceArray =
958                     asyncResp->res.jsonValue["Members"];
959                 logServiceArray = nlohmann::json::array();
960                 logServiceArray.push_back(
961                     {{"@odata.id",
962                       "/redfish/v1/Systems/system/LogServices/EventLog"}});
963 #ifdef BMCWEB_ENABLE_REDFISH_DUMP_LOG
964                 logServiceArray.push_back(
965                     {{"@odata.id",
966                       "/redfish/v1/Systems/system/LogServices/Dump"}});
967 #endif
968 
969 #ifdef BMCWEB_ENABLE_REDFISH_CPU_LOG
970                 logServiceArray.push_back(
971                     {{"@odata.id",
972                       "/redfish/v1/Systems/system/LogServices/Crashdump"}});
973 #endif
974 
975 #ifdef BMCWEB_ENABLE_REDFISH_HOST_LOGGER
976                 logServiceArray.push_back(
977                     {{"@odata.id",
978                       "/redfish/v1/Systems/system/LogServices/HostLogger"}});
979 #endif
980                 asyncResp->res.jsonValue["Members@odata.count"] =
981                     logServiceArray.size();
982 
983                 crow::connections::systemBus->async_method_call(
984                     [asyncResp](const boost::system::error_code ec,
985                                 const std::vector<std::string>& subtreePath) {
986                         if (ec)
987                         {
988                             BMCWEB_LOG_ERROR << ec;
989                             return;
990                         }
991 
992                         for (auto& pathStr : subtreePath)
993                         {
994                             if (pathStr.find("PostCode") != std::string::npos)
995                             {
996                                 nlohmann::json& logServiceArrayLocal =
997                                     asyncResp->res.jsonValue["Members"];
998                                 logServiceArrayLocal.push_back(
999                                     {{"@odata.id",
1000                                       "/redfish/v1/Systems/system/LogServices/PostCodes"}});
1001                                 asyncResp->res
1002                                     .jsonValue["Members@odata.count"] =
1003                                     logServiceArrayLocal.size();
1004                                 return;
1005                             }
1006                         }
1007                     },
1008                     "xyz.openbmc_project.ObjectMapper",
1009                     "/xyz/openbmc_project/object_mapper",
1010                     "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths", "/",
1011                     0, std::array<const char*, 1>{postCodeIface});
1012             });
1013 }
1014 
1015 inline void requestRoutesEventLogService(App& app)
1016 {
1017     BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/EventLog/")
1018         .privileges(redfish::privileges::getLogService)
1019         .methods(
1020             boost::beast::http::verb::
1021                 get)([](const crow::Request&,
1022                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
1023             asyncResp->res.jsonValue["@odata.id"] =
1024                 "/redfish/v1/Systems/system/LogServices/EventLog";
1025             asyncResp->res.jsonValue["@odata.type"] =
1026                 "#LogService.v1_1_0.LogService";
1027             asyncResp->res.jsonValue["Name"] = "Event Log Service";
1028             asyncResp->res.jsonValue["Description"] =
1029                 "System Event Log Service";
1030             asyncResp->res.jsonValue["Id"] = "EventLog";
1031             asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull";
1032 
1033             std::pair<std::string, std::string> redfishDateTimeOffset =
1034                 crow::utility::getDateTimeOffsetNow();
1035 
1036             asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
1037             asyncResp->res.jsonValue["DateTimeLocalOffset"] =
1038                 redfishDateTimeOffset.second;
1039 
1040             asyncResp->res.jsonValue["Entries"] = {
1041                 {"@odata.id",
1042                  "/redfish/v1/Systems/system/LogServices/EventLog/Entries"}};
1043             asyncResp->res.jsonValue["Actions"]["#LogService.ClearLog"] = {
1044 
1045                 {"target",
1046                  "/redfish/v1/Systems/system/LogServices/EventLog/Actions/LogService.ClearLog"}};
1047         });
1048 }
1049 
1050 inline void requestRoutesJournalEventLogClear(App& app)
1051 {
1052     BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/EventLog/Actions/"
1053                       "LogService.ClearLog/")
1054         .privileges({{"ConfigureComponents"}})
1055         .methods(boost::beast::http::verb::post)(
1056             [](const crow::Request&,
1057                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
1058                 // Clear the EventLog by deleting the log files
1059                 std::vector<std::filesystem::path> redfishLogFiles;
1060                 if (getRedfishLogFiles(redfishLogFiles))
1061                 {
1062                     for (const std::filesystem::path& file : redfishLogFiles)
1063                     {
1064                         std::error_code ec;
1065                         std::filesystem::remove(file, ec);
1066                     }
1067                 }
1068 
1069                 // Reload rsyslog so it knows to start new log files
1070                 crow::connections::systemBus->async_method_call(
1071                     [asyncResp](const boost::system::error_code ec) {
1072                         if (ec)
1073                         {
1074                             BMCWEB_LOG_ERROR << "Failed to reload rsyslog: "
1075                                              << ec;
1076                             messages::internalError(asyncResp->res);
1077                             return;
1078                         }
1079 
1080                         messages::success(asyncResp->res);
1081                     },
1082                     "org.freedesktop.systemd1", "/org/freedesktop/systemd1",
1083                     "org.freedesktop.systemd1.Manager", "ReloadUnit",
1084                     "rsyslog.service", "replace");
1085             });
1086 }
1087 
1088 static int fillEventLogEntryJson(const std::string& logEntryID,
1089                                  const std::string& logEntry,
1090                                  nlohmann::json& logEntryJson)
1091 {
1092     // The redfish log format is "<Timestamp> <MessageId>,<MessageArgs>"
1093     // First get the Timestamp
1094     size_t space = logEntry.find_first_of(' ');
1095     if (space == std::string::npos)
1096     {
1097         return 1;
1098     }
1099     std::string timestamp = logEntry.substr(0, space);
1100     // Then get the log contents
1101     size_t entryStart = logEntry.find_first_not_of(' ', space);
1102     if (entryStart == std::string::npos)
1103     {
1104         return 1;
1105     }
1106     std::string_view entry(logEntry);
1107     entry.remove_prefix(entryStart);
1108     // Use split to separate the entry into its fields
1109     std::vector<std::string> logEntryFields;
1110     boost::split(logEntryFields, entry, boost::is_any_of(","),
1111                  boost::token_compress_on);
1112     // We need at least a MessageId to be valid
1113     if (logEntryFields.empty())
1114     {
1115         return 1;
1116     }
1117     std::string& messageID = logEntryFields[0];
1118 
1119     // Get the Message from the MessageRegistry
1120     const message_registries::Message* message =
1121         message_registries::getMessage(messageID);
1122 
1123     std::string msg;
1124     std::string severity;
1125     if (message != nullptr)
1126     {
1127         msg = message->message;
1128         severity = message->severity;
1129     }
1130 
1131     // Get the MessageArgs from the log if there are any
1132     std::span<std::string> messageArgs;
1133     if (logEntryFields.size() > 1)
1134     {
1135         std::string& messageArgsStart = logEntryFields[1];
1136         // If the first string is empty, assume there are no MessageArgs
1137         std::size_t messageArgsSize = 0;
1138         if (!messageArgsStart.empty())
1139         {
1140             messageArgsSize = logEntryFields.size() - 1;
1141         }
1142 
1143         messageArgs = {&messageArgsStart, messageArgsSize};
1144 
1145         // Fill the MessageArgs into the Message
1146         int i = 0;
1147         for (const std::string& messageArg : messageArgs)
1148         {
1149             std::string argStr = "%" + std::to_string(++i);
1150             size_t argPos = msg.find(argStr);
1151             if (argPos != std::string::npos)
1152             {
1153                 msg.replace(argPos, argStr.length(), messageArg);
1154             }
1155         }
1156     }
1157 
1158     // Get the Created time from the timestamp. The log timestamp is in RFC3339
1159     // format which matches the Redfish format except for the fractional seconds
1160     // between the '.' and the '+', so just remove them.
1161     std::size_t dot = timestamp.find_first_of('.');
1162     std::size_t plus = timestamp.find_first_of('+');
1163     if (dot != std::string::npos && plus != std::string::npos)
1164     {
1165         timestamp.erase(dot, plus - dot);
1166     }
1167 
1168     // Fill in the log entry with the gathered data
1169     logEntryJson = {
1170         {"@odata.type", "#LogEntry.v1_8_0.LogEntry"},
1171         {"@odata.id",
1172          "/redfish/v1/Systems/system/LogServices/EventLog/Entries/" +
1173              logEntryID},
1174         {"Name", "System Event Log Entry"},
1175         {"Id", logEntryID},
1176         {"Message", std::move(msg)},
1177         {"MessageId", std::move(messageID)},
1178         {"MessageArgs", messageArgs},
1179         {"EntryType", "Event"},
1180         {"Severity", std::move(severity)},
1181         {"Created", std::move(timestamp)}};
1182     return 0;
1183 }
1184 
1185 inline void requestRoutesJournalEventLogEntryCollection(App& app)
1186 {
1187     BMCWEB_ROUTE(app,
1188                  "/redfish/v1/Systems/system/LogServices/EventLog/Entries/")
1189         .privileges(redfish::privileges::getLogEntryCollection)
1190         .methods(boost::beast::http::verb::get)(
1191             [](const crow::Request& req,
1192                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
1193                 uint64_t skip = 0;
1194                 uint64_t top = maxEntriesPerPage; // Show max entries by default
1195                 if (!getSkipParam(asyncResp, req, skip))
1196                 {
1197                     return;
1198                 }
1199                 if (!getTopParam(asyncResp, req, top))
1200                 {
1201                     return;
1202                 }
1203                 // Collections don't include the static data added by SubRoute
1204                 // because it has a duplicate entry for members
1205                 asyncResp->res.jsonValue["@odata.type"] =
1206                     "#LogEntryCollection.LogEntryCollection";
1207                 asyncResp->res.jsonValue["@odata.id"] =
1208                     "/redfish/v1/Systems/system/LogServices/EventLog/Entries";
1209                 asyncResp->res.jsonValue["Name"] = "System Event Log Entries";
1210                 asyncResp->res.jsonValue["Description"] =
1211                     "Collection of System Event Log Entries";
1212 
1213                 nlohmann::json& logEntryArray =
1214                     asyncResp->res.jsonValue["Members"];
1215                 logEntryArray = nlohmann::json::array();
1216                 // Go through the log files and create a unique ID for each
1217                 // entry
1218                 std::vector<std::filesystem::path> redfishLogFiles;
1219                 getRedfishLogFiles(redfishLogFiles);
1220                 uint64_t entryCount = 0;
1221                 std::string logEntry;
1222 
1223                 // Oldest logs are in the last file, so start there and loop
1224                 // backwards
1225                 for (auto it = redfishLogFiles.rbegin();
1226                      it < redfishLogFiles.rend(); it++)
1227                 {
1228                     std::ifstream logStream(*it);
1229                     if (!logStream.is_open())
1230                     {
1231                         continue;
1232                     }
1233 
1234                     // Reset the unique ID on the first entry
1235                     bool firstEntry = true;
1236                     while (std::getline(logStream, logEntry))
1237                     {
1238                         entryCount++;
1239                         // Handle paging using skip (number of entries to skip
1240                         // from the start) and top (number of entries to
1241                         // display)
1242                         if (entryCount <= skip || entryCount > skip + top)
1243                         {
1244                             continue;
1245                         }
1246 
1247                         std::string idStr;
1248                         if (!getUniqueEntryID(logEntry, idStr, firstEntry))
1249                         {
1250                             continue;
1251                         }
1252 
1253                         if (firstEntry)
1254                         {
1255                             firstEntry = false;
1256                         }
1257 
1258                         logEntryArray.push_back({});
1259                         nlohmann::json& bmcLogEntry = logEntryArray.back();
1260                         if (fillEventLogEntryJson(idStr, logEntry,
1261                                                   bmcLogEntry) != 0)
1262                         {
1263                             messages::internalError(asyncResp->res);
1264                             return;
1265                         }
1266                     }
1267                 }
1268                 asyncResp->res.jsonValue["Members@odata.count"] = entryCount;
1269                 if (skip + top < entryCount)
1270                 {
1271                     asyncResp->res.jsonValue["Members@odata.nextLink"] =
1272                         "/redfish/v1/Systems/system/LogServices/EventLog/"
1273                         "Entries?$skip=" +
1274                         std::to_string(skip + top);
1275                 }
1276             });
1277 }
1278 
1279 inline void requestRoutesJournalEventLogEntry(App& app)
1280 {
1281     BMCWEB_ROUTE(
1282         app, "/redfish/v1/Systems/system/LogServices/EventLog/Entries/<str>/")
1283         .privileges(redfish::privileges::getLogEntry)
1284         .methods(boost::beast::http::verb::get)(
1285             [](const crow::Request&,
1286                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1287                const std::string& param) {
1288                 const std::string& targetID = param;
1289 
1290                 // Go through the log files and check the unique ID for each
1291                 // entry to find the target entry
1292                 std::vector<std::filesystem::path> redfishLogFiles;
1293                 getRedfishLogFiles(redfishLogFiles);
1294                 std::string logEntry;
1295 
1296                 // Oldest logs are in the last file, so start there and loop
1297                 // backwards
1298                 for (auto it = redfishLogFiles.rbegin();
1299                      it < redfishLogFiles.rend(); it++)
1300                 {
1301                     std::ifstream logStream(*it);
1302                     if (!logStream.is_open())
1303                     {
1304                         continue;
1305                     }
1306 
1307                     // Reset the unique ID on the first entry
1308                     bool firstEntry = true;
1309                     while (std::getline(logStream, logEntry))
1310                     {
1311                         std::string idStr;
1312                         if (!getUniqueEntryID(logEntry, idStr, firstEntry))
1313                         {
1314                             continue;
1315                         }
1316 
1317                         if (firstEntry)
1318                         {
1319                             firstEntry = false;
1320                         }
1321 
1322                         if (idStr == targetID)
1323                         {
1324                             if (fillEventLogEntryJson(
1325                                     idStr, logEntry,
1326                                     asyncResp->res.jsonValue) != 0)
1327                             {
1328                                 messages::internalError(asyncResp->res);
1329                                 return;
1330                             }
1331                             return;
1332                         }
1333                     }
1334                 }
1335                 // Requested ID was not found
1336                 messages::resourceMissingAtURI(asyncResp->res, targetID);
1337             });
1338 }
1339 
1340 inline void requestRoutesDBusEventLogEntryCollection(App& app)
1341 {
1342     BMCWEB_ROUTE(app,
1343                  "/redfish/v1/Systems/system/LogServices/EventLog/Entries/")
1344         .privileges(redfish::privileges::getLogEntryCollection)
1345         .methods(
1346             boost::beast::http::verb::
1347                 get)([](const crow::Request&,
1348                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
1349             // Collections don't include the static data added by SubRoute
1350             // because it has a duplicate entry for members
1351             asyncResp->res.jsonValue["@odata.type"] =
1352                 "#LogEntryCollection.LogEntryCollection";
1353             asyncResp->res.jsonValue["@odata.id"] =
1354                 "/redfish/v1/Systems/system/LogServices/EventLog/Entries";
1355             asyncResp->res.jsonValue["Name"] = "System Event Log Entries";
1356             asyncResp->res.jsonValue["Description"] =
1357                 "Collection of System Event Log Entries";
1358 
1359             // DBus implementation of EventLog/Entries
1360             // Make call to Logging Service to find all log entry objects
1361             crow::connections::systemBus->async_method_call(
1362                 [asyncResp](const boost::system::error_code ec,
1363                             const dbus::utility::ManagedObjectType& resp) {
1364                     if (ec)
1365                     {
1366                         // TODO Handle for specific error code
1367                         BMCWEB_LOG_ERROR
1368                             << "getLogEntriesIfaceData resp_handler got error "
1369                             << ec;
1370                         messages::internalError(asyncResp->res);
1371                         return;
1372                     }
1373                     nlohmann::json& entriesArray =
1374                         asyncResp->res.jsonValue["Members"];
1375                     entriesArray = nlohmann::json::array();
1376                     for (auto& objectPath : resp)
1377                     {
1378                         const uint32_t* id = nullptr;
1379                         const uint64_t* timestamp = nullptr;
1380                         const uint64_t* updateTimestamp = nullptr;
1381                         const std::string* severity = nullptr;
1382                         const std::string* message = nullptr;
1383                         const std::string* filePath = nullptr;
1384                         bool resolved = false;
1385                         for (auto& interfaceMap : objectPath.second)
1386                         {
1387                             if (interfaceMap.first ==
1388                                 "xyz.openbmc_project.Logging.Entry")
1389                             {
1390                                 for (auto& propertyMap : interfaceMap.second)
1391                                 {
1392                                     if (propertyMap.first == "Id")
1393                                     {
1394                                         id = std::get_if<uint32_t>(
1395                                             &propertyMap.second);
1396                                     }
1397                                     else if (propertyMap.first == "Timestamp")
1398                                     {
1399                                         timestamp = std::get_if<uint64_t>(
1400                                             &propertyMap.second);
1401                                     }
1402                                     else if (propertyMap.first ==
1403                                              "UpdateTimestamp")
1404                                     {
1405                                         updateTimestamp = std::get_if<uint64_t>(
1406                                             &propertyMap.second);
1407                                     }
1408                                     else if (propertyMap.first == "Severity")
1409                                     {
1410                                         severity = std::get_if<std::string>(
1411                                             &propertyMap.second);
1412                                     }
1413                                     else if (propertyMap.first == "Message")
1414                                     {
1415                                         message = std::get_if<std::string>(
1416                                             &propertyMap.second);
1417                                     }
1418                                     else if (propertyMap.first == "Resolved")
1419                                     {
1420                                         const bool* resolveptr =
1421                                             std::get_if<bool>(
1422                                                 &propertyMap.second);
1423                                         if (resolveptr == nullptr)
1424                                         {
1425                                             messages::internalError(
1426                                                 asyncResp->res);
1427                                             return;
1428                                         }
1429                                         resolved = *resolveptr;
1430                                     }
1431                                 }
1432                                 if (id == nullptr || message == nullptr ||
1433                                     severity == nullptr)
1434                                 {
1435                                     messages::internalError(asyncResp->res);
1436                                     return;
1437                                 }
1438                             }
1439                             else if (interfaceMap.first ==
1440                                      "xyz.openbmc_project.Common.FilePath")
1441                             {
1442                                 for (auto& propertyMap : interfaceMap.second)
1443                                 {
1444                                     if (propertyMap.first == "Path")
1445                                     {
1446                                         filePath = std::get_if<std::string>(
1447                                             &propertyMap.second);
1448                                     }
1449                                 }
1450                             }
1451                         }
1452                         // Object path without the
1453                         // xyz.openbmc_project.Logging.Entry interface, ignore
1454                         // and continue.
1455                         if (id == nullptr || message == nullptr ||
1456                             severity == nullptr || timestamp == nullptr ||
1457                             updateTimestamp == nullptr)
1458                         {
1459                             continue;
1460                         }
1461                         entriesArray.push_back({});
1462                         nlohmann::json& thisEntry = entriesArray.back();
1463                         thisEntry["@odata.type"] = "#LogEntry.v1_8_0.LogEntry";
1464                         thisEntry["@odata.id"] =
1465                             "/redfish/v1/Systems/system/LogServices/EventLog/Entries/" +
1466                             std::to_string(*id);
1467                         thisEntry["Name"] = "System Event Log Entry";
1468                         thisEntry["Id"] = std::to_string(*id);
1469                         thisEntry["Message"] = *message;
1470                         thisEntry["Resolved"] = resolved;
1471                         thisEntry["EntryType"] = "Event";
1472                         thisEntry["Severity"] =
1473                             translateSeverityDbusToRedfish(*severity);
1474                         thisEntry["Created"] =
1475                             crow::utility::getDateTimeUintMs(*timestamp);
1476                         thisEntry["Modified"] =
1477                             crow::utility::getDateTimeUintMs(*updateTimestamp);
1478                         if (filePath != nullptr)
1479                         {
1480                             thisEntry["AdditionalDataURI"] =
1481                                 "/redfish/v1/Systems/system/LogServices/EventLog/Entries/" +
1482                                 std::to_string(*id) + "/attachment";
1483                         }
1484                     }
1485                     std::sort(entriesArray.begin(), entriesArray.end(),
1486                               [](const nlohmann::json& left,
1487                                  const nlohmann::json& right) {
1488                                   return (left["Id"] <= right["Id"]);
1489                               });
1490                     asyncResp->res.jsonValue["Members@odata.count"] =
1491                         entriesArray.size();
1492                 },
1493                 "xyz.openbmc_project.Logging", "/xyz/openbmc_project/logging",
1494                 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
1495         });
1496 }
1497 
1498 inline void requestRoutesDBusEventLogEntry(App& app)
1499 {
1500     BMCWEB_ROUTE(
1501         app, "/redfish/v1/Systems/system/LogServices/EventLog/Entries/<str>/")
1502         .privileges(redfish::privileges::getLogEntry)
1503         .methods(boost::beast::http::verb::get)(
1504             [](const crow::Request&,
1505                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1506                const std::string& param)
1507 
1508             {
1509                 std::string entryID = param;
1510                 dbus::utility::escapePathForDbus(entryID);
1511 
1512                 // DBus implementation of EventLog/Entries
1513                 // Make call to Logging Service to find all log entry objects
1514                 crow::connections::systemBus->async_method_call(
1515                     [asyncResp, entryID](const boost::system::error_code ec,
1516                                          const GetManagedPropertyType& resp) {
1517                         if (ec.value() == EBADR)
1518                         {
1519                             messages::resourceNotFound(
1520                                 asyncResp->res, "EventLogEntry", entryID);
1521                             return;
1522                         }
1523                         if (ec)
1524                         {
1525                             BMCWEB_LOG_ERROR
1526                                 << "EventLogEntry (DBus) resp_handler got error "
1527                                 << ec;
1528                             messages::internalError(asyncResp->res);
1529                             return;
1530                         }
1531                         const uint32_t* id = nullptr;
1532                         const uint64_t* timestamp = nullptr;
1533                         const uint64_t* updateTimestamp = nullptr;
1534                         const std::string* severity = nullptr;
1535                         const std::string* message = nullptr;
1536                         const std::string* filePath = nullptr;
1537                         bool resolved = false;
1538 
1539                         for (auto& propertyMap : resp)
1540                         {
1541                             if (propertyMap.first == "Id")
1542                             {
1543                                 id = std::get_if<uint32_t>(&propertyMap.second);
1544                             }
1545                             else if (propertyMap.first == "Timestamp")
1546                             {
1547                                 timestamp =
1548                                     std::get_if<uint64_t>(&propertyMap.second);
1549                             }
1550                             else if (propertyMap.first == "UpdateTimestamp")
1551                             {
1552                                 updateTimestamp =
1553                                     std::get_if<uint64_t>(&propertyMap.second);
1554                             }
1555                             else if (propertyMap.first == "Severity")
1556                             {
1557                                 severity = std::get_if<std::string>(
1558                                     &propertyMap.second);
1559                             }
1560                             else if (propertyMap.first == "Message")
1561                             {
1562                                 message = std::get_if<std::string>(
1563                                     &propertyMap.second);
1564                             }
1565                             else if (propertyMap.first == "Resolved")
1566                             {
1567                                 const bool* resolveptr =
1568                                     std::get_if<bool>(&propertyMap.second);
1569                                 if (resolveptr == nullptr)
1570                                 {
1571                                     messages::internalError(asyncResp->res);
1572                                     return;
1573                                 }
1574                                 resolved = *resolveptr;
1575                             }
1576                             else if (propertyMap.first == "Path")
1577                             {
1578                                 filePath = std::get_if<std::string>(
1579                                     &propertyMap.second);
1580                             }
1581                         }
1582                         if (id == nullptr || message == nullptr ||
1583                             severity == nullptr || timestamp == nullptr ||
1584                             updateTimestamp == nullptr)
1585                         {
1586                             messages::internalError(asyncResp->res);
1587                             return;
1588                         }
1589                         asyncResp->res.jsonValue["@odata.type"] =
1590                             "#LogEntry.v1_8_0.LogEntry";
1591                         asyncResp->res.jsonValue["@odata.id"] =
1592                             "/redfish/v1/Systems/system/LogServices/EventLog/Entries/" +
1593                             std::to_string(*id);
1594                         asyncResp->res.jsonValue["Name"] =
1595                             "System Event Log Entry";
1596                         asyncResp->res.jsonValue["Id"] = std::to_string(*id);
1597                         asyncResp->res.jsonValue["Message"] = *message;
1598                         asyncResp->res.jsonValue["Resolved"] = resolved;
1599                         asyncResp->res.jsonValue["EntryType"] = "Event";
1600                         asyncResp->res.jsonValue["Severity"] =
1601                             translateSeverityDbusToRedfish(*severity);
1602                         asyncResp->res.jsonValue["Created"] =
1603                             crow::utility::getDateTimeUintMs(*timestamp);
1604                         asyncResp->res.jsonValue["Modified"] =
1605                             crow::utility::getDateTimeUintMs(*updateTimestamp);
1606                         if (filePath != nullptr)
1607                         {
1608                             asyncResp->res.jsonValue["AdditionalDataURI"] =
1609                                 "/redfish/v1/Systems/system/LogServices/EventLog/attachment/" +
1610                                 std::to_string(*id);
1611                         }
1612                     },
1613                     "xyz.openbmc_project.Logging",
1614                     "/xyz/openbmc_project/logging/entry/" + entryID,
1615                     "org.freedesktop.DBus.Properties", "GetAll", "");
1616             });
1617 
1618     BMCWEB_ROUTE(
1619         app, "/redfish/v1/Systems/system/LogServices/EventLog/Entries/<str>/")
1620         .privileges(redfish::privileges::patchLogEntry)
1621         .methods(boost::beast::http::verb::patch)(
1622             [](const crow::Request& req,
1623                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1624                const std::string& entryId) {
1625                 std::optional<bool> resolved;
1626 
1627                 if (!json_util::readJson(req, asyncResp->res, "Resolved",
1628                                          resolved))
1629                 {
1630                     return;
1631                 }
1632                 BMCWEB_LOG_DEBUG << "Set Resolved";
1633 
1634                 crow::connections::systemBus->async_method_call(
1635                     [asyncResp, entryId](const boost::system::error_code ec) {
1636                         if (ec)
1637                         {
1638                             BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
1639                             messages::internalError(asyncResp->res);
1640                             return;
1641                         }
1642                     },
1643                     "xyz.openbmc_project.Logging",
1644                     "/xyz/openbmc_project/logging/entry/" + entryId,
1645                     "org.freedesktop.DBus.Properties", "Set",
1646                     "xyz.openbmc_project.Logging.Entry", "Resolved",
1647                     dbus::utility::DbusVariantType(*resolved));
1648             });
1649 
1650     BMCWEB_ROUTE(
1651         app, "/redfish/v1/Systems/system/LogServices/EventLog/Entries/<str>/")
1652         .privileges(redfish::privileges::deleteLogEntry)
1653 
1654         .methods(boost::beast::http::verb::delete_)(
1655             [](const crow::Request&,
1656                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1657                const std::string& param)
1658 
1659             {
1660                 BMCWEB_LOG_DEBUG << "Do delete single event entries.";
1661 
1662                 std::string entryID = param;
1663 
1664                 dbus::utility::escapePathForDbus(entryID);
1665 
1666                 // Process response from Logging service.
1667                 auto respHandler = [asyncResp, entryID](
1668                                        const boost::system::error_code ec) {
1669                     BMCWEB_LOG_DEBUG
1670                         << "EventLogEntry (DBus) doDelete callback: Done";
1671                     if (ec)
1672                     {
1673                         if (ec.value() == EBADR)
1674                         {
1675                             messages::resourceNotFound(asyncResp->res,
1676                                                        "LogEntry", entryID);
1677                             return;
1678                         }
1679                         // TODO Handle for specific error code
1680                         BMCWEB_LOG_ERROR
1681                             << "EventLogEntry (DBus) doDelete respHandler got error "
1682                             << ec;
1683                         asyncResp->res.result(
1684                             boost::beast::http::status::internal_server_error);
1685                         return;
1686                     }
1687 
1688                     asyncResp->res.result(boost::beast::http::status::ok);
1689                 };
1690 
1691                 // Make call to Logging service to request Delete Log
1692                 crow::connections::systemBus->async_method_call(
1693                     respHandler, "xyz.openbmc_project.Logging",
1694                     "/xyz/openbmc_project/logging/entry/" + entryID,
1695                     "xyz.openbmc_project.Object.Delete", "Delete");
1696             });
1697 }
1698 
1699 inline void requestRoutesDBusEventLogEntryDownload(App& app)
1700 {
1701     BMCWEB_ROUTE(
1702         app,
1703         "/redfish/v1/Systems/system/LogServices/EventLog/Entries/<str>/attachment")
1704         .privileges(redfish::privileges::getLogEntry)
1705         .methods(boost::beast::http::verb::get)(
1706             [](const crow::Request& req,
1707                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1708                const std::string& param)
1709 
1710             {
1711                 if (!http_helpers::isOctetAccepted(
1712                         req.getHeaderValue("Accept")))
1713                 {
1714                     asyncResp->res.result(
1715                         boost::beast::http::status::bad_request);
1716                     return;
1717                 }
1718 
1719                 std::string entryID = param;
1720                 dbus::utility::escapePathForDbus(entryID);
1721 
1722                 crow::connections::systemBus->async_method_call(
1723                     [asyncResp,
1724                      entryID](const boost::system::error_code ec,
1725                               const sdbusplus::message::unix_fd& unixfd) {
1726                         if (ec.value() == EBADR)
1727                         {
1728                             messages::resourceNotFound(
1729                                 asyncResp->res, "EventLogAttachment", entryID);
1730                             return;
1731                         }
1732                         if (ec)
1733                         {
1734                             BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
1735                             messages::internalError(asyncResp->res);
1736                             return;
1737                         }
1738 
1739                         int fd = -1;
1740                         fd = dup(unixfd);
1741                         if (fd == -1)
1742                         {
1743                             messages::internalError(asyncResp->res);
1744                             return;
1745                         }
1746 
1747                         long long int size = lseek(fd, 0, SEEK_END);
1748                         if (size == -1)
1749                         {
1750                             messages::internalError(asyncResp->res);
1751                             return;
1752                         }
1753 
1754                         // Arbitrary max size of 64kb
1755                         constexpr int maxFileSize = 65536;
1756                         if (size > maxFileSize)
1757                         {
1758                             BMCWEB_LOG_ERROR
1759                                 << "File size exceeds maximum allowed size of "
1760                                 << maxFileSize;
1761                             messages::internalError(asyncResp->res);
1762                             return;
1763                         }
1764                         std::vector<char> data(static_cast<size_t>(size));
1765                         long long int rc = lseek(fd, 0, SEEK_SET);
1766                         if (rc == -1)
1767                         {
1768                             messages::internalError(asyncResp->res);
1769                             return;
1770                         }
1771                         rc = read(fd, data.data(), data.size());
1772                         if ((rc == -1) || (rc != size))
1773                         {
1774                             messages::internalError(asyncResp->res);
1775                             return;
1776                         }
1777                         close(fd);
1778 
1779                         std::string_view strData(data.data(), data.size());
1780                         std::string output =
1781                             crow::utility::base64encode(strData);
1782 
1783                         asyncResp->res.addHeader("Content-Type",
1784                                                  "application/octet-stream");
1785                         asyncResp->res.addHeader("Content-Transfer-Encoding",
1786                                                  "Base64");
1787                         asyncResp->res.body() = std::move(output);
1788                     },
1789                     "xyz.openbmc_project.Logging",
1790                     "/xyz/openbmc_project/logging/entry/" + entryID,
1791                     "xyz.openbmc_project.Logging.Entry", "GetEntry");
1792             });
1793 }
1794 
1795 constexpr const char* hostLoggerFolderPath = "/var/log/console";
1796 
1797 inline bool
1798     getHostLoggerFiles(const std::string& hostLoggerFilePath,
1799                        std::vector<std::filesystem::path>& hostLoggerFiles)
1800 {
1801     std::error_code ec;
1802     std::filesystem::directory_iterator logPath(hostLoggerFilePath, ec);
1803     if (ec)
1804     {
1805         BMCWEB_LOG_ERROR << ec.message();
1806         return false;
1807     }
1808     for (const std::filesystem::directory_entry& it : logPath)
1809     {
1810         std::string filename = it.path().filename();
1811         // Prefix of each log files is "log". Find the file and save the
1812         // path
1813         if (boost::starts_with(filename, "log"))
1814         {
1815             hostLoggerFiles.emplace_back(it.path());
1816         }
1817     }
1818     // As the log files rotate, they are appended with a ".#" that is higher for
1819     // the older logs. Since we start from oldest logs, sort the name in
1820     // descending order.
1821     std::sort(hostLoggerFiles.rbegin(), hostLoggerFiles.rend(),
1822               AlphanumLess<std::string>());
1823 
1824     return true;
1825 }
1826 
1827 inline bool
1828     getHostLoggerEntries(std::vector<std::filesystem::path>& hostLoggerFiles,
1829                          uint64_t& skip, uint64_t& top,
1830                          std::vector<std::string>& logEntries, size_t& logCount)
1831 {
1832     GzFileReader logFile;
1833 
1834     // Go though all log files and expose host logs.
1835     for (const std::filesystem::path& it : hostLoggerFiles)
1836     {
1837         if (!logFile.gzGetLines(it.string(), skip, top, logEntries, logCount))
1838         {
1839             BMCWEB_LOG_ERROR << "fail to expose host logs";
1840             return false;
1841         }
1842     }
1843     // Get lastMessage from constructor by getter
1844     std::string lastMessage = logFile.getLastMessage();
1845     if (!lastMessage.empty())
1846     {
1847         logCount++;
1848         if (logCount > skip && logCount <= (skip + top))
1849         {
1850             logEntries.push_back(lastMessage);
1851         }
1852     }
1853     return true;
1854 }
1855 
1856 inline void fillHostLoggerEntryJson(const std::string& logEntryID,
1857                                     const std::string& msg,
1858                                     nlohmann::json& logEntryJson)
1859 {
1860     // Fill in the log entry with the gathered data.
1861     logEntryJson = {
1862         {"@odata.type", "#LogEntry.v1_4_0.LogEntry"},
1863         {"@odata.id",
1864          "/redfish/v1/Systems/system/LogServices/HostLogger/Entries/" +
1865              logEntryID},
1866         {"Name", "Host Logger Entry"},
1867         {"Id", logEntryID},
1868         {"Message", msg},
1869         {"EntryType", "Oem"},
1870         {"Severity", "OK"},
1871         {"OemRecordFormat", "Host Logger Entry"}};
1872 }
1873 
1874 inline void requestRoutesSystemHostLogger(App& app)
1875 {
1876     BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/HostLogger/")
1877         .privileges(redfish::privileges::getLogService)
1878         .methods(
1879             boost::beast::http::verb::
1880                 get)([](const crow::Request&,
1881                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
1882             asyncResp->res.jsonValue["@odata.id"] =
1883                 "/redfish/v1/Systems/system/LogServices/HostLogger";
1884             asyncResp->res.jsonValue["@odata.type"] =
1885                 "#LogService.v1_1_0.LogService";
1886             asyncResp->res.jsonValue["Name"] = "Host Logger Service";
1887             asyncResp->res.jsonValue["Description"] = "Host Logger Service";
1888             asyncResp->res.jsonValue["Id"] = "HostLogger";
1889             asyncResp->res.jsonValue["Entries"] = {
1890                 {"@odata.id",
1891                  "/redfish/v1/Systems/system/LogServices/HostLogger/Entries"}};
1892         });
1893 }
1894 
1895 inline void requestRoutesSystemHostLoggerCollection(App& app)
1896 {
1897     BMCWEB_ROUTE(app,
1898                  "/redfish/v1/Systems/system/LogServices/HostLogger/Entries/")
1899         .privileges(redfish::privileges::getLogEntry)
1900         .methods(
1901             boost::beast::http::verb::
1902                 get)([](const crow::Request& req,
1903                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
1904             uint64_t skip = 0;
1905             uint64_t top = maxEntriesPerPage; // Show max 1000 entries by
1906                                               // default, allow range 1 to
1907                                               // 1000 entries per page.
1908             if (!getSkipParam(asyncResp, req, skip))
1909             {
1910                 return;
1911             }
1912             if (!getTopParam(asyncResp, req, top))
1913             {
1914                 return;
1915             }
1916             asyncResp->res.jsonValue["@odata.id"] =
1917                 "/redfish/v1/Systems/system/LogServices/HostLogger/Entries";
1918             asyncResp->res.jsonValue["@odata.type"] =
1919                 "#LogEntryCollection.LogEntryCollection";
1920             asyncResp->res.jsonValue["Name"] = "HostLogger Entries";
1921             asyncResp->res.jsonValue["Description"] =
1922                 "Collection of HostLogger Entries";
1923             nlohmann::json& logEntryArray = asyncResp->res.jsonValue["Members"];
1924             logEntryArray = nlohmann::json::array();
1925             asyncResp->res.jsonValue["Members@odata.count"] = 0;
1926 
1927             std::vector<std::filesystem::path> hostLoggerFiles;
1928             if (!getHostLoggerFiles(hostLoggerFolderPath, hostLoggerFiles))
1929             {
1930                 BMCWEB_LOG_ERROR << "fail to get host log file path";
1931                 return;
1932             }
1933 
1934             size_t logCount = 0;
1935             // This vector only store the entries we want to expose that
1936             // control by skip and top.
1937             std::vector<std::string> logEntries;
1938             if (!getHostLoggerEntries(hostLoggerFiles, skip, top, logEntries,
1939                                       logCount))
1940             {
1941                 messages::internalError(asyncResp->res);
1942                 return;
1943             }
1944             // If vector is empty, that means skip value larger than total
1945             // log count
1946             if (logEntries.empty())
1947             {
1948                 asyncResp->res.jsonValue["Members@odata.count"] = logCount;
1949                 return;
1950             }
1951             if (!logEntries.empty())
1952             {
1953                 for (size_t i = 0; i < logEntries.size(); i++)
1954                 {
1955                     logEntryArray.push_back({});
1956                     nlohmann::json& hostLogEntry = logEntryArray.back();
1957                     fillHostLoggerEntryJson(std::to_string(skip + i),
1958                                             logEntries[i], hostLogEntry);
1959                 }
1960 
1961                 asyncResp->res.jsonValue["Members@odata.count"] = logCount;
1962                 if (skip + top < logCount)
1963                 {
1964                     asyncResp->res.jsonValue["Members@odata.nextLink"] =
1965                         "/redfish/v1/Systems/system/LogServices/HostLogger/Entries?$skip=" +
1966                         std::to_string(skip + top);
1967                 }
1968             }
1969         });
1970 }
1971 
1972 inline void requestRoutesSystemHostLoggerLogEntry(App& app)
1973 {
1974     BMCWEB_ROUTE(
1975         app, "/redfish/v1/Systems/system/LogServices/HostLogger/Entries/<str>/")
1976         .privileges(redfish::privileges::getLogEntry)
1977         .methods(boost::beast::http::verb::get)(
1978             [](const crow::Request&,
1979                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1980                const std::string& param) {
1981                 const std::string& targetID = param;
1982 
1983                 uint64_t idInt = 0;
1984 
1985                 // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
1986                 const char* end = targetID.data() + targetID.size();
1987 
1988                 auto [ptr, ec] = std::from_chars(targetID.data(), end, idInt);
1989                 if (ec == std::errc::invalid_argument)
1990                 {
1991                     messages::resourceMissingAtURI(asyncResp->res, targetID);
1992                     return;
1993                 }
1994                 if (ec == std::errc::result_out_of_range)
1995                 {
1996                     messages::resourceMissingAtURI(asyncResp->res, targetID);
1997                     return;
1998                 }
1999 
2000                 std::vector<std::filesystem::path> hostLoggerFiles;
2001                 if (!getHostLoggerFiles(hostLoggerFolderPath, hostLoggerFiles))
2002                 {
2003                     BMCWEB_LOG_ERROR << "fail to get host log file path";
2004                     return;
2005                 }
2006 
2007                 size_t logCount = 0;
2008                 uint64_t top = 1;
2009                 std::vector<std::string> logEntries;
2010                 // We can get specific entry by skip and top. For example, if we
2011                 // want to get nth entry, we can set skip = n-1 and top = 1 to
2012                 // get that entry
2013                 if (!getHostLoggerEntries(hostLoggerFiles, idInt, top,
2014                                           logEntries, logCount))
2015                 {
2016                     messages::internalError(asyncResp->res);
2017                     return;
2018                 }
2019 
2020                 if (!logEntries.empty())
2021                 {
2022                     fillHostLoggerEntryJson(targetID, logEntries[0],
2023                                             asyncResp->res.jsonValue);
2024                     return;
2025                 }
2026 
2027                 // Requested ID was not found
2028                 messages::resourceMissingAtURI(asyncResp->res, targetID);
2029             });
2030 }
2031 
2032 inline void requestRoutesBMCLogServiceCollection(App& app)
2033 {
2034     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/")
2035         .privileges(redfish::privileges::getLogServiceCollection)
2036         .methods(boost::beast::http::verb::get)(
2037             [](const crow::Request&,
2038                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2039                 // Collections don't include the static data added by SubRoute
2040                 // because it has a duplicate entry for members
2041                 asyncResp->res.jsonValue["@odata.type"] =
2042                     "#LogServiceCollection.LogServiceCollection";
2043                 asyncResp->res.jsonValue["@odata.id"] =
2044                     "/redfish/v1/Managers/bmc/LogServices";
2045                 asyncResp->res.jsonValue["Name"] =
2046                     "Open BMC Log Services Collection";
2047                 asyncResp->res.jsonValue["Description"] =
2048                     "Collection of LogServices for this Manager";
2049                 nlohmann::json& logServiceArray =
2050                     asyncResp->res.jsonValue["Members"];
2051                 logServiceArray = nlohmann::json::array();
2052 #ifdef BMCWEB_ENABLE_REDFISH_DUMP_LOG
2053                 logServiceArray.push_back(
2054                     {{"@odata.id",
2055                       "/redfish/v1/Managers/bmc/LogServices/Dump"}});
2056 #endif
2057 #ifdef BMCWEB_ENABLE_REDFISH_BMC_JOURNAL
2058                 logServiceArray.push_back(
2059                     {{"@odata.id",
2060                       "/redfish/v1/Managers/bmc/LogServices/Journal"}});
2061 #endif
2062                 asyncResp->res.jsonValue["Members@odata.count"] =
2063                     logServiceArray.size();
2064             });
2065 }
2066 
2067 inline void requestRoutesBMCJournalLogService(App& app)
2068 {
2069     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Journal/")
2070         .privileges(redfish::privileges::getLogService)
2071         .methods(boost::beast::http::verb::get)(
2072             [](const crow::Request&,
2073                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2074 
2075             {
2076                 asyncResp->res.jsonValue["@odata.type"] =
2077                     "#LogService.v1_1_0.LogService";
2078                 asyncResp->res.jsonValue["@odata.id"] =
2079                     "/redfish/v1/Managers/bmc/LogServices/Journal";
2080                 asyncResp->res.jsonValue["Name"] =
2081                     "Open BMC Journal Log Service";
2082                 asyncResp->res.jsonValue["Description"] =
2083                     "BMC Journal Log Service";
2084                 asyncResp->res.jsonValue["Id"] = "BMC Journal";
2085                 asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull";
2086 
2087                 std::pair<std::string, std::string> redfishDateTimeOffset =
2088                     crow::utility::getDateTimeOffsetNow();
2089                 asyncResp->res.jsonValue["DateTime"] =
2090                     redfishDateTimeOffset.first;
2091                 asyncResp->res.jsonValue["DateTimeLocalOffset"] =
2092                     redfishDateTimeOffset.second;
2093 
2094                 asyncResp->res.jsonValue["Entries"] = {
2095                     {"@odata.id",
2096                      "/redfish/v1/Managers/bmc/LogServices/Journal/Entries"}};
2097             });
2098 }
2099 
2100 static int fillBMCJournalLogEntryJson(const std::string& bmcJournalLogEntryID,
2101                                       sd_journal* journal,
2102                                       nlohmann::json& bmcJournalLogEntryJson)
2103 {
2104     // Get the Log Entry contents
2105     int ret = 0;
2106 
2107     std::string message;
2108     std::string_view syslogID;
2109     ret = getJournalMetadata(journal, "SYSLOG_IDENTIFIER", syslogID);
2110     if (ret < 0)
2111     {
2112         BMCWEB_LOG_ERROR << "Failed to read SYSLOG_IDENTIFIER field: "
2113                          << strerror(-ret);
2114     }
2115     if (!syslogID.empty())
2116     {
2117         message += std::string(syslogID) + ": ";
2118     }
2119 
2120     std::string_view msg;
2121     ret = getJournalMetadata(journal, "MESSAGE", msg);
2122     if (ret < 0)
2123     {
2124         BMCWEB_LOG_ERROR << "Failed to read MESSAGE field: " << strerror(-ret);
2125         return 1;
2126     }
2127     message += std::string(msg);
2128 
2129     // Get the severity from the PRIORITY field
2130     long int severity = 8; // Default to an invalid priority
2131     ret = getJournalMetadata(journal, "PRIORITY", 10, severity);
2132     if (ret < 0)
2133     {
2134         BMCWEB_LOG_ERROR << "Failed to read PRIORITY field: " << strerror(-ret);
2135     }
2136 
2137     // Get the Created time from the timestamp
2138     std::string entryTimeStr;
2139     if (!getEntryTimestamp(journal, entryTimeStr))
2140     {
2141         return 1;
2142     }
2143 
2144     // Fill in the log entry with the gathered data
2145     bmcJournalLogEntryJson = {
2146         {"@odata.type", "#LogEntry.v1_8_0.LogEntry"},
2147         {"@odata.id", "/redfish/v1/Managers/bmc/LogServices/Journal/Entries/" +
2148                           bmcJournalLogEntryID},
2149         {"Name", "BMC Journal Entry"},
2150         {"Id", bmcJournalLogEntryID},
2151         {"Message", std::move(message)},
2152         {"EntryType", "Oem"},
2153         {"Severity", severity <= 2   ? "Critical"
2154                      : severity <= 4 ? "Warning"
2155                                      : "OK"},
2156         {"OemRecordFormat", "BMC Journal Entry"},
2157         {"Created", std::move(entryTimeStr)}};
2158     return 0;
2159 }
2160 
2161 inline void requestRoutesBMCJournalLogEntryCollection(App& app)
2162 {
2163     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Journal/Entries/")
2164         .privileges(redfish::privileges::getLogEntryCollection)
2165         .methods(
2166             boost::beast::http::verb::
2167                 get)([](const crow::Request& req,
2168                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2169             static constexpr const long maxEntriesPerPage = 1000;
2170             uint64_t skip = 0;
2171             uint64_t top = maxEntriesPerPage; // Show max entries by default
2172             if (!getSkipParam(asyncResp, req, skip))
2173             {
2174                 return;
2175             }
2176             if (!getTopParam(asyncResp, req, top))
2177             {
2178                 return;
2179             }
2180             // Collections don't include the static data added by SubRoute
2181             // because it has a duplicate entry for members
2182             asyncResp->res.jsonValue["@odata.type"] =
2183                 "#LogEntryCollection.LogEntryCollection";
2184             asyncResp->res.jsonValue["@odata.id"] =
2185                 "/redfish/v1/Managers/bmc/LogServices/Journal/Entries";
2186             asyncResp->res.jsonValue["Name"] = "Open BMC Journal Entries";
2187             asyncResp->res.jsonValue["Description"] =
2188                 "Collection of BMC Journal Entries";
2189             nlohmann::json& logEntryArray = asyncResp->res.jsonValue["Members"];
2190             logEntryArray = nlohmann::json::array();
2191 
2192             // Go through the journal and use the timestamp to create a
2193             // unique ID for each entry
2194             sd_journal* journalTmp = nullptr;
2195             int ret = sd_journal_open(&journalTmp, SD_JOURNAL_LOCAL_ONLY);
2196             if (ret < 0)
2197             {
2198                 BMCWEB_LOG_ERROR << "failed to open journal: "
2199                                  << strerror(-ret);
2200                 messages::internalError(asyncResp->res);
2201                 return;
2202             }
2203             std::unique_ptr<sd_journal, decltype(&sd_journal_close)> journal(
2204                 journalTmp, sd_journal_close);
2205             journalTmp = nullptr;
2206             uint64_t entryCount = 0;
2207             // Reset the unique ID on the first entry
2208             bool firstEntry = true;
2209             SD_JOURNAL_FOREACH(journal.get())
2210             {
2211                 entryCount++;
2212                 // Handle paging using skip (number of entries to skip from
2213                 // the start) and top (number of entries to display)
2214                 if (entryCount <= skip || entryCount > skip + top)
2215                 {
2216                     continue;
2217                 }
2218 
2219                 std::string idStr;
2220                 if (!getUniqueEntryID(journal.get(), idStr, firstEntry))
2221                 {
2222                     continue;
2223                 }
2224 
2225                 if (firstEntry)
2226                 {
2227                     firstEntry = false;
2228                 }
2229 
2230                 logEntryArray.push_back({});
2231                 nlohmann::json& bmcJournalLogEntry = logEntryArray.back();
2232                 if (fillBMCJournalLogEntryJson(idStr, journal.get(),
2233                                                bmcJournalLogEntry) != 0)
2234                 {
2235                     messages::internalError(asyncResp->res);
2236                     return;
2237                 }
2238             }
2239             asyncResp->res.jsonValue["Members@odata.count"] = entryCount;
2240             if (skip + top < entryCount)
2241             {
2242                 asyncResp->res.jsonValue["Members@odata.nextLink"] =
2243                     "/redfish/v1/Managers/bmc/LogServices/Journal/Entries?$skip=" +
2244                     std::to_string(skip + top);
2245             }
2246         });
2247 }
2248 
2249 inline void requestRoutesBMCJournalLogEntry(App& app)
2250 {
2251     BMCWEB_ROUTE(app,
2252                  "/redfish/v1/Managers/bmc/LogServices/Journal/Entries/<str>/")
2253         .privileges(redfish::privileges::getLogEntry)
2254         .methods(boost::beast::http::verb::get)(
2255             [](const crow::Request&,
2256                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2257                const std::string& entryID) {
2258                 // Convert the unique ID back to a timestamp to find the entry
2259                 uint64_t ts = 0;
2260                 uint64_t index = 0;
2261                 if (!getTimestampFromID(asyncResp, entryID, ts, index))
2262                 {
2263                     return;
2264                 }
2265 
2266                 sd_journal* journalTmp = nullptr;
2267                 int ret = sd_journal_open(&journalTmp, SD_JOURNAL_LOCAL_ONLY);
2268                 if (ret < 0)
2269                 {
2270                     BMCWEB_LOG_ERROR << "failed to open journal: "
2271                                      << strerror(-ret);
2272                     messages::internalError(asyncResp->res);
2273                     return;
2274                 }
2275                 std::unique_ptr<sd_journal, decltype(&sd_journal_close)>
2276                     journal(journalTmp, sd_journal_close);
2277                 journalTmp = nullptr;
2278                 // Go to the timestamp in the log and move to the entry at the
2279                 // index tracking the unique ID
2280                 std::string idStr;
2281                 bool firstEntry = true;
2282                 ret = sd_journal_seek_realtime_usec(journal.get(), ts);
2283                 if (ret < 0)
2284                 {
2285                     BMCWEB_LOG_ERROR << "failed to seek to an entry in journal"
2286                                      << strerror(-ret);
2287                     messages::internalError(asyncResp->res);
2288                     return;
2289                 }
2290                 for (uint64_t i = 0; i <= index; i++)
2291                 {
2292                     sd_journal_next(journal.get());
2293                     if (!getUniqueEntryID(journal.get(), idStr, firstEntry))
2294                     {
2295                         messages::internalError(asyncResp->res);
2296                         return;
2297                     }
2298                     if (firstEntry)
2299                     {
2300                         firstEntry = false;
2301                     }
2302                 }
2303                 // Confirm that the entry ID matches what was requested
2304                 if (idStr != entryID)
2305                 {
2306                     messages::resourceMissingAtURI(asyncResp->res, entryID);
2307                     return;
2308                 }
2309 
2310                 if (fillBMCJournalLogEntryJson(entryID, journal.get(),
2311                                                asyncResp->res.jsonValue) != 0)
2312                 {
2313                     messages::internalError(asyncResp->res);
2314                     return;
2315                 }
2316             });
2317 }
2318 
2319 inline void requestRoutesBMCDumpService(App& app)
2320 {
2321     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Dump/")
2322         .privileges(redfish::privileges::getLogService)
2323         .methods(
2324             boost::beast::http::verb::
2325                 get)([](const crow::Request&,
2326                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2327             asyncResp->res.jsonValue["@odata.id"] =
2328                 "/redfish/v1/Managers/bmc/LogServices/Dump";
2329             asyncResp->res.jsonValue["@odata.type"] =
2330                 "#LogService.v1_2_0.LogService";
2331             asyncResp->res.jsonValue["Name"] = "Dump LogService";
2332             asyncResp->res.jsonValue["Description"] = "BMC Dump LogService";
2333             asyncResp->res.jsonValue["Id"] = "Dump";
2334             asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull";
2335 
2336             std::pair<std::string, std::string> redfishDateTimeOffset =
2337                 crow::utility::getDateTimeOffsetNow();
2338             asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
2339             asyncResp->res.jsonValue["DateTimeLocalOffset"] =
2340                 redfishDateTimeOffset.second;
2341 
2342             asyncResp->res.jsonValue["Entries"] = {
2343                 {"@odata.id",
2344                  "/redfish/v1/Managers/bmc/LogServices/Dump/Entries"}};
2345             asyncResp->res.jsonValue["Actions"] = {
2346                 {"#LogService.ClearLog",
2347                  {{"target",
2348                    "/redfish/v1/Managers/bmc/LogServices/Dump/Actions/LogService.ClearLog"}}},
2349                 {"#LogService.CollectDiagnosticData",
2350                  {{"target",
2351                    "/redfish/v1/Managers/bmc/LogServices/Dump/Actions/LogService.CollectDiagnosticData"}}}};
2352         });
2353 }
2354 
2355 inline void requestRoutesBMCDumpEntryCollection(App& app)
2356 {
2357 
2358     /**
2359      * Functions triggers appropriate requests on DBus
2360      */
2361     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/")
2362         .privileges(redfish::privileges::getLogEntryCollection)
2363         .methods(boost::beast::http::verb::get)(
2364             [](const crow::Request&,
2365                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2366                 asyncResp->res.jsonValue["@odata.type"] =
2367                     "#LogEntryCollection.LogEntryCollection";
2368                 asyncResp->res.jsonValue["@odata.id"] =
2369                     "/redfish/v1/Managers/bmc/LogServices/Dump/Entries";
2370                 asyncResp->res.jsonValue["Name"] = "BMC Dump Entries";
2371                 asyncResp->res.jsonValue["Description"] =
2372                     "Collection of BMC Dump Entries";
2373 
2374                 getDumpEntryCollection(asyncResp, "BMC");
2375             });
2376 }
2377 
2378 inline void requestRoutesBMCDumpEntry(App& app)
2379 {
2380     BMCWEB_ROUTE(app,
2381                  "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/<str>/")
2382         .privileges(redfish::privileges::getLogEntry)
2383         .methods(boost::beast::http::verb::get)(
2384             [](const crow::Request&,
2385                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2386                const std::string& param) {
2387                 getDumpEntryById(asyncResp, param, "BMC");
2388             });
2389     BMCWEB_ROUTE(app,
2390                  "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/<str>/")
2391         .privileges(redfish::privileges::deleteLogEntry)
2392         .methods(boost::beast::http::verb::delete_)(
2393             [](const crow::Request&,
2394                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2395                const std::string& param) {
2396                 deleteDumpEntry(asyncResp, param, "bmc");
2397             });
2398 }
2399 
2400 inline void requestRoutesBMCDumpCreate(App& app)
2401 {
2402 
2403     BMCWEB_ROUTE(
2404         app,
2405         "/redfish/v1/Managers/bmc/LogServices/Dump/Actions/LogService.CollectDiagnosticData/")
2406         .privileges(redfish::privileges::postLogService)
2407         .methods(boost::beast::http::verb::post)(
2408             [](const crow::Request& req,
2409                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2410                 createDump(asyncResp, req, "BMC");
2411             });
2412 }
2413 
2414 inline void requestRoutesBMCDumpClear(App& app)
2415 {
2416     BMCWEB_ROUTE(
2417         app,
2418         "/redfish/v1/Managers/bmc/LogServices/Dump/Actions/LogService.ClearLog/")
2419         .privileges(redfish::privileges::postLogService)
2420         .methods(boost::beast::http::verb::post)(
2421             [](const crow::Request&,
2422                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2423                 clearDump(asyncResp, "BMC");
2424             });
2425 }
2426 
2427 inline void requestRoutesSystemDumpService(App& app)
2428 {
2429     BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/Dump/")
2430         .privileges(redfish::privileges::getLogService)
2431         .methods(boost::beast::http::verb::get)(
2432             [](const crow::Request&,
2433                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2434 
2435             {
2436                 asyncResp->res.jsonValue["@odata.id"] =
2437                     "/redfish/v1/Systems/system/LogServices/Dump";
2438                 asyncResp->res.jsonValue["@odata.type"] =
2439                     "#LogService.v1_2_0.LogService";
2440                 asyncResp->res.jsonValue["Name"] = "Dump LogService";
2441                 asyncResp->res.jsonValue["Description"] =
2442                     "System Dump LogService";
2443                 asyncResp->res.jsonValue["Id"] = "Dump";
2444                 asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull";
2445 
2446                 std::pair<std::string, std::string> redfishDateTimeOffset =
2447                     crow::utility::getDateTimeOffsetNow();
2448                 asyncResp->res.jsonValue["DateTime"] =
2449                     redfishDateTimeOffset.first;
2450                 asyncResp->res.jsonValue["DateTimeLocalOffset"] =
2451                     redfishDateTimeOffset.second;
2452 
2453                 asyncResp->res.jsonValue["Entries"] = {
2454                     {"@odata.id",
2455                      "/redfish/v1/Systems/system/LogServices/Dump/Entries"}};
2456                 asyncResp->res.jsonValue["Actions"] = {
2457                     {"#LogService.ClearLog",
2458                      {{"target",
2459                        "/redfish/v1/Systems/system/LogServices/Dump/Actions/LogService.ClearLog"}}},
2460                     {"#LogService.CollectDiagnosticData",
2461                      {{"target",
2462                        "/redfish/v1/Systems/system/LogServices/Dump/Actions/LogService.CollectDiagnosticData"}}}};
2463             });
2464 }
2465 
2466 inline void requestRoutesSystemDumpEntryCollection(App& app)
2467 {
2468 
2469     /**
2470      * Functions triggers appropriate requests on DBus
2471      */
2472     BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/Dump/Entries/")
2473         .privileges(redfish::privileges::getLogEntryCollection)
2474         .methods(boost::beast::http::verb::get)(
2475             [](const crow::Request&,
2476                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2477                 asyncResp->res.jsonValue["@odata.type"] =
2478                     "#LogEntryCollection.LogEntryCollection";
2479                 asyncResp->res.jsonValue["@odata.id"] =
2480                     "/redfish/v1/Systems/system/LogServices/Dump/Entries";
2481                 asyncResp->res.jsonValue["Name"] = "System Dump Entries";
2482                 asyncResp->res.jsonValue["Description"] =
2483                     "Collection of System Dump Entries";
2484 
2485                 getDumpEntryCollection(asyncResp, "System");
2486             });
2487 }
2488 
2489 inline void requestRoutesSystemDumpEntry(App& app)
2490 {
2491     BMCWEB_ROUTE(app,
2492                  "/redfish/v1/Systems/system/LogServices/Dump/Entries/<str>/")
2493         .privileges(redfish::privileges::getLogEntry)
2494 
2495         .methods(boost::beast::http::verb::get)(
2496             [](const crow::Request&,
2497                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2498                const std::string& param) {
2499                 getDumpEntryById(asyncResp, param, "System");
2500             });
2501 
2502     BMCWEB_ROUTE(app,
2503                  "/redfish/v1/Systems/system/LogServices/Dump/Entries/<str>/")
2504         .privileges(redfish::privileges::deleteLogEntry)
2505         .methods(boost::beast::http::verb::delete_)(
2506             [](const crow::Request&,
2507                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2508                const std::string& param) {
2509                 deleteDumpEntry(asyncResp, param, "system");
2510             });
2511 }
2512 
2513 inline void requestRoutesSystemDumpCreate(App& app)
2514 {
2515     BMCWEB_ROUTE(
2516         app,
2517         "/redfish/v1/Systems/system/LogServices/Dump/Actions/LogService.CollectDiagnosticData/")
2518         .privileges(redfish::privileges::postLogService)
2519         .methods(boost::beast::http::verb::post)(
2520             [](const crow::Request& req,
2521                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2522 
2523             { createDump(asyncResp, req, "System"); });
2524 }
2525 
2526 inline void requestRoutesSystemDumpClear(App& app)
2527 {
2528     BMCWEB_ROUTE(
2529         app,
2530         "/redfish/v1/Systems/system/LogServices/Dump/Actions/LogService.ClearLog/")
2531         .privileges(redfish::privileges::postLogService)
2532         .methods(boost::beast::http::verb::post)(
2533             [](const crow::Request&,
2534                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2535 
2536             { clearDump(asyncResp, "System"); });
2537 }
2538 
2539 inline void requestRoutesCrashdumpService(App& app)
2540 {
2541     // Note: Deviated from redfish privilege registry for GET & HEAD
2542     // method for security reasons.
2543     /**
2544      * Functions triggers appropriate requests on DBus
2545      */
2546     BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/Crashdump/")
2547         // This is incorrect, should be:
2548         //.privileges(redfish::privileges::getLogService)
2549         .privileges({{"ConfigureManager"}})
2550         .methods(
2551             boost::beast::http::verb::
2552                 get)([](const crow::Request&,
2553                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2554             // Copy over the static data to include the entries added by
2555             // SubRoute
2556             asyncResp->res.jsonValue["@odata.id"] =
2557                 "/redfish/v1/Systems/system/LogServices/Crashdump";
2558             asyncResp->res.jsonValue["@odata.type"] =
2559                 "#LogService.v1_2_0.LogService";
2560             asyncResp->res.jsonValue["Name"] = "Open BMC Oem Crashdump Service";
2561             asyncResp->res.jsonValue["Description"] = "Oem Crashdump Service";
2562             asyncResp->res.jsonValue["Id"] = "Oem Crashdump";
2563             asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull";
2564             asyncResp->res.jsonValue["MaxNumberOfRecords"] = 3;
2565 
2566             std::pair<std::string, std::string> redfishDateTimeOffset =
2567                 crow::utility::getDateTimeOffsetNow();
2568             asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
2569             asyncResp->res.jsonValue["DateTimeLocalOffset"] =
2570                 redfishDateTimeOffset.second;
2571 
2572             asyncResp->res.jsonValue["Entries"] = {
2573                 {"@odata.id",
2574                  "/redfish/v1/Systems/system/LogServices/Crashdump/Entries"}};
2575             asyncResp->res.jsonValue["Actions"] = {
2576                 {"#LogService.ClearLog",
2577                  {{"target",
2578                    "/redfish/v1/Systems/system/LogServices/Crashdump/Actions/LogService.ClearLog"}}},
2579                 {"#LogService.CollectDiagnosticData",
2580                  {{"target",
2581                    "/redfish/v1/Systems/system/LogServices/Crashdump/Actions/LogService.CollectDiagnosticData"}}}};
2582         });
2583 }
2584 
2585 void inline requestRoutesCrashdumpClear(App& app)
2586 {
2587     BMCWEB_ROUTE(
2588         app,
2589         "/redfish/v1/Systems/system/LogServices/Crashdump/Actions/LogService.ClearLog/")
2590         // This is incorrect, should be:
2591         //.privileges(redfish::privileges::postLogService)
2592         .privileges({{"ConfigureComponents"}})
2593         .methods(boost::beast::http::verb::post)(
2594             [](const crow::Request&,
2595                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2596                 crow::connections::systemBus->async_method_call(
2597                     [asyncResp](const boost::system::error_code ec,
2598                                 const std::string&) {
2599                         if (ec)
2600                         {
2601                             messages::internalError(asyncResp->res);
2602                             return;
2603                         }
2604                         messages::success(asyncResp->res);
2605                     },
2606                     crashdumpObject, crashdumpPath, deleteAllInterface,
2607                     "DeleteAll");
2608             });
2609 }
2610 
2611 static void
2612     logCrashdumpEntry(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2613                       const std::string& logID, nlohmann::json& logEntryJson)
2614 {
2615     auto getStoredLogCallback =
2616         [asyncResp, logID, &logEntryJson](
2617             const boost::system::error_code ec,
2618             const std::vector<
2619                 std::pair<std::string, dbus::utility::DbusVariantType>>&
2620                 params) {
2621             if (ec)
2622             {
2623                 BMCWEB_LOG_DEBUG << "failed to get log ec: " << ec.message();
2624                 if (ec.value() ==
2625                     boost::system::linux_error::bad_request_descriptor)
2626                 {
2627                     messages::resourceNotFound(asyncResp->res, "LogEntry",
2628                                                logID);
2629                 }
2630                 else
2631                 {
2632                     messages::internalError(asyncResp->res);
2633                 }
2634                 return;
2635             }
2636 
2637             std::string timestamp{};
2638             std::string filename{};
2639             std::string logfile{};
2640             parseCrashdumpParameters(params, filename, timestamp, logfile);
2641 
2642             if (filename.empty() || timestamp.empty())
2643             {
2644                 messages::resourceMissingAtURI(asyncResp->res, logID);
2645                 return;
2646             }
2647 
2648             std::string crashdumpURI =
2649                 "/redfish/v1/Systems/system/LogServices/Crashdump/Entries/" +
2650                 logID + "/" + filename;
2651             logEntryJson = {{"@odata.type", "#LogEntry.v1_7_0.LogEntry"},
2652                             {"@odata.id", "/redfish/v1/Systems/system/"
2653                                           "LogServices/Crashdump/Entries/" +
2654                                               logID},
2655                             {"Name", "CPU Crashdump"},
2656                             {"Id", logID},
2657                             {"EntryType", "Oem"},
2658                             {"AdditionalDataURI", std::move(crashdumpURI)},
2659                             {"DiagnosticDataType", "OEM"},
2660                             {"OEMDiagnosticDataType", "PECICrashdump"},
2661                             {"Created", std::move(timestamp)}};
2662         };
2663     crow::connections::systemBus->async_method_call(
2664         std::move(getStoredLogCallback), crashdumpObject,
2665         crashdumpPath + std::string("/") + logID,
2666         "org.freedesktop.DBus.Properties", "GetAll", crashdumpInterface);
2667 }
2668 
2669 inline void requestRoutesCrashdumpEntryCollection(App& app)
2670 {
2671     // Note: Deviated from redfish privilege registry for GET & HEAD
2672     // method for security reasons.
2673     /**
2674      * Functions triggers appropriate requests on DBus
2675      */
2676     BMCWEB_ROUTE(app,
2677                  "/redfish/v1/Systems/system/LogServices/Crashdump/Entries/")
2678         // This is incorrect, should be.
2679         //.privileges(redfish::privileges::postLogEntryCollection)
2680         .privileges({{"ConfigureComponents"}})
2681         .methods(
2682             boost::beast::http::verb::
2683                 get)([](const crow::Request&,
2684                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2685             // Collections don't include the static data added by SubRoute
2686             // because it has a duplicate entry for members
2687             auto getLogEntriesCallback = [asyncResp](
2688                                              const boost::system::error_code ec,
2689                                              const std::vector<std::string>&
2690                                                  resp) {
2691                 if (ec)
2692                 {
2693                     if (ec.value() !=
2694                         boost::system::errc::no_such_file_or_directory)
2695                     {
2696                         BMCWEB_LOG_DEBUG << "failed to get entries ec: "
2697                                          << ec.message();
2698                         messages::internalError(asyncResp->res);
2699                         return;
2700                     }
2701                 }
2702                 asyncResp->res.jsonValue["@odata.type"] =
2703                     "#LogEntryCollection.LogEntryCollection";
2704                 asyncResp->res.jsonValue["@odata.id"] =
2705                     "/redfish/v1/Systems/system/LogServices/Crashdump/Entries";
2706                 asyncResp->res.jsonValue["Name"] = "Open BMC Crashdump Entries";
2707                 asyncResp->res.jsonValue["Description"] =
2708                     "Collection of Crashdump Entries";
2709                 nlohmann::json& logEntryArray =
2710                     asyncResp->res.jsonValue["Members"];
2711                 logEntryArray = nlohmann::json::array();
2712                 std::vector<std::string> logIDs;
2713                 // Get the list of log entries and build up an empty array big
2714                 // enough to hold them
2715                 for (const std::string& objpath : resp)
2716                 {
2717                     // Get the log ID
2718                     std::size_t lastPos = objpath.rfind('/');
2719                     if (lastPos == std::string::npos)
2720                     {
2721                         continue;
2722                     }
2723                     logIDs.emplace_back(objpath.substr(lastPos + 1));
2724 
2725                     // Add a space for the log entry to the array
2726                     logEntryArray.push_back({});
2727                 }
2728                 // Now go through and set up async calls to fill in the entries
2729                 size_t index = 0;
2730                 for (const std::string& logID : logIDs)
2731                 {
2732                     // Add the log entry to the array
2733                     logCrashdumpEntry(asyncResp, logID, logEntryArray[index++]);
2734                 }
2735                 asyncResp->res.jsonValue["Members@odata.count"] =
2736                     logEntryArray.size();
2737             };
2738             crow::connections::systemBus->async_method_call(
2739                 std::move(getLogEntriesCallback),
2740                 "xyz.openbmc_project.ObjectMapper",
2741                 "/xyz/openbmc_project/object_mapper",
2742                 "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths", "", 0,
2743                 std::array<const char*, 1>{crashdumpInterface});
2744         });
2745 }
2746 
2747 inline void requestRoutesCrashdumpEntry(App& app)
2748 {
2749     // Note: Deviated from redfish privilege registry for GET & HEAD
2750     // method for security reasons.
2751 
2752     BMCWEB_ROUTE(
2753         app, "/redfish/v1/Systems/system/LogServices/Crashdump/Entries/<str>/")
2754         // this is incorrect, should be
2755         // .privileges(redfish::privileges::getLogEntry)
2756         .privileges({{"ConfigureComponents"}})
2757         .methods(boost::beast::http::verb::get)(
2758             [](const crow::Request&,
2759                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2760                const std::string& param) {
2761                 const std::string& logID = param;
2762                 logCrashdumpEntry(asyncResp, logID, asyncResp->res.jsonValue);
2763             });
2764 }
2765 
2766 inline void requestRoutesCrashdumpFile(App& app)
2767 {
2768     // Note: Deviated from redfish privilege registry for GET & HEAD
2769     // method for security reasons.
2770     BMCWEB_ROUTE(
2771         app,
2772         "/redfish/v1/Systems/system/LogServices/Crashdump/Entries/<str>/<str>/")
2773         .privileges(redfish::privileges::getLogEntry)
2774         .methods(boost::beast::http::verb::get)(
2775             [](const crow::Request&,
2776                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2777                const std::string& logID, const std::string& fileName) {
2778                 auto getStoredLogCallback =
2779                     [asyncResp, logID, fileName](
2780                         const boost::system::error_code ec,
2781                         const std::vector<std::pair<
2782                             std::string, dbus::utility::DbusVariantType>>&
2783                             resp) {
2784                         if (ec)
2785                         {
2786                             BMCWEB_LOG_DEBUG << "failed to get log ec: "
2787                                              << ec.message();
2788                             messages::internalError(asyncResp->res);
2789                             return;
2790                         }
2791 
2792                         std::string dbusFilename{};
2793                         std::string dbusTimestamp{};
2794                         std::string dbusFilepath{};
2795 
2796                         parseCrashdumpParameters(resp, dbusFilename,
2797                                                  dbusTimestamp, dbusFilepath);
2798 
2799                         if (dbusFilename.empty() || dbusTimestamp.empty() ||
2800                             dbusFilepath.empty())
2801                         {
2802                             messages::resourceMissingAtURI(asyncResp->res,
2803                                                            fileName);
2804                             return;
2805                         }
2806 
2807                         // Verify the file name parameter is correct
2808                         if (fileName != dbusFilename)
2809                         {
2810                             messages::resourceMissingAtURI(asyncResp->res,
2811                                                            fileName);
2812                             return;
2813                         }
2814 
2815                         if (!std::filesystem::exists(dbusFilepath))
2816                         {
2817                             messages::resourceMissingAtURI(asyncResp->res,
2818                                                            fileName);
2819                             return;
2820                         }
2821                         std::ifstream ifs(dbusFilepath,
2822                                           std::ios::in | std::ios::binary);
2823                         asyncResp->res.body() = std::string(
2824                             std::istreambuf_iterator<char>{ifs}, {});
2825 
2826                         // Configure this to be a file download when accessed
2827                         // from a browser
2828                         asyncResp->res.addHeader("Content-Disposition",
2829                                                  "attachment");
2830                     };
2831                 crow::connections::systemBus->async_method_call(
2832                     std::move(getStoredLogCallback), crashdumpObject,
2833                     crashdumpPath + std::string("/") + logID,
2834                     "org.freedesktop.DBus.Properties", "GetAll",
2835                     crashdumpInterface);
2836             });
2837 }
2838 
2839 inline void requestRoutesCrashdumpCollect(App& app)
2840 {
2841     // Note: Deviated from redfish privilege registry for GET & HEAD
2842     // method for security reasons.
2843     BMCWEB_ROUTE(
2844         app,
2845         "/redfish/v1/Systems/system/LogServices/Crashdump/Actions/LogService.CollectDiagnosticData/")
2846         // The below is incorrect;  Should be ConfigureManager
2847         //.privileges(redfish::privileges::postLogService)
2848         .privileges({{"ConfigureComponents"}})
2849         .methods(
2850             boost::beast::http::verb::
2851                 post)([](const crow::Request& req,
2852                          const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2853             std::string diagnosticDataType;
2854             std::string oemDiagnosticDataType;
2855             if (!redfish::json_util::readJson(
2856                     req, asyncResp->res, "DiagnosticDataType",
2857                     diagnosticDataType, "OEMDiagnosticDataType",
2858                     oemDiagnosticDataType))
2859             {
2860                 return;
2861             }
2862 
2863             if (diagnosticDataType != "OEM")
2864             {
2865                 BMCWEB_LOG_ERROR
2866                     << "Only OEM DiagnosticDataType supported for Crashdump";
2867                 messages::actionParameterValueFormatError(
2868                     asyncResp->res, diagnosticDataType, "DiagnosticDataType",
2869                     "CollectDiagnosticData");
2870                 return;
2871             }
2872 
2873             auto collectCrashdumpCallback = [asyncResp,
2874                                              payload(task::Payload(req))](
2875                                                 const boost::system::error_code
2876                                                     ec,
2877                                                 const std::string&) mutable {
2878                 if (ec)
2879                 {
2880                     if (ec.value() ==
2881                         boost::system::errc::operation_not_supported)
2882                     {
2883                         messages::resourceInStandby(asyncResp->res);
2884                     }
2885                     else if (ec.value() ==
2886                              boost::system::errc::device_or_resource_busy)
2887                     {
2888                         messages::serviceTemporarilyUnavailable(asyncResp->res,
2889                                                                 "60");
2890                     }
2891                     else
2892                     {
2893                         messages::internalError(asyncResp->res);
2894                     }
2895                     return;
2896                 }
2897                 std::shared_ptr<task::TaskData> task = task::TaskData::createTask(
2898                     [](boost::system::error_code err,
2899                        sdbusplus::message::message&,
2900                        const std::shared_ptr<task::TaskData>& taskData) {
2901                         if (!err)
2902                         {
2903                             taskData->messages.emplace_back(
2904                                 messages::taskCompletedOK(
2905                                     std::to_string(taskData->index)));
2906                             taskData->state = "Completed";
2907                         }
2908                         return task::completed;
2909                     },
2910                     "type='signal',interface='org.freedesktop.DBus."
2911                     "Properties',"
2912                     "member='PropertiesChanged',arg0namespace='com.intel.crashdump'");
2913                 task->startTimer(std::chrono::minutes(5));
2914                 task->populateResp(asyncResp->res);
2915                 task->payload.emplace(std::move(payload));
2916             };
2917 
2918             if (oemDiagnosticDataType == "OnDemand")
2919             {
2920                 crow::connections::systemBus->async_method_call(
2921                     std::move(collectCrashdumpCallback), crashdumpObject,
2922                     crashdumpPath, crashdumpOnDemandInterface,
2923                     "GenerateOnDemandLog");
2924             }
2925             else if (oemDiagnosticDataType == "Telemetry")
2926             {
2927                 crow::connections::systemBus->async_method_call(
2928                     std::move(collectCrashdumpCallback), crashdumpObject,
2929                     crashdumpPath, crashdumpTelemetryInterface,
2930                     "GenerateTelemetryLog");
2931             }
2932             else
2933             {
2934                 BMCWEB_LOG_ERROR << "Unsupported OEMDiagnosticDataType: "
2935                                  << oemDiagnosticDataType;
2936                 messages::actionParameterValueFormatError(
2937                     asyncResp->res, oemDiagnosticDataType,
2938                     "OEMDiagnosticDataType", "CollectDiagnosticData");
2939                 return;
2940             }
2941         });
2942 }
2943 
2944 /**
2945  * DBusLogServiceActionsClear class supports POST method for ClearLog action.
2946  */
2947 inline void requestRoutesDBusLogServiceActionsClear(App& app)
2948 {
2949     /**
2950      * Function handles POST method request.
2951      * The Clear Log actions does not require any parameter.The action deletes
2952      * all entries found in the Entries collection for this Log Service.
2953      */
2954 
2955     BMCWEB_ROUTE(
2956         app,
2957         "/redfish/v1/Systems/system/LogServices/EventLog/Actions/LogService.ClearLog/")
2958         .privileges(redfish::privileges::postLogService)
2959         .methods(boost::beast::http::verb::post)(
2960             [](const crow::Request&,
2961                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2962                 BMCWEB_LOG_DEBUG << "Do delete all entries.";
2963 
2964                 // Process response from Logging service.
2965                 auto respHandler = [asyncResp](
2966                                        const boost::system::error_code ec) {
2967                     BMCWEB_LOG_DEBUG
2968                         << "doClearLog resp_handler callback: Done";
2969                     if (ec)
2970                     {
2971                         // TODO Handle for specific error code
2972                         BMCWEB_LOG_ERROR << "doClearLog resp_handler got error "
2973                                          << ec;
2974                         asyncResp->res.result(
2975                             boost::beast::http::status::internal_server_error);
2976                         return;
2977                     }
2978 
2979                     asyncResp->res.result(
2980                         boost::beast::http::status::no_content);
2981                 };
2982 
2983                 // Make call to Logging service to request Clear Log
2984                 crow::connections::systemBus->async_method_call(
2985                     respHandler, "xyz.openbmc_project.Logging",
2986                     "/xyz/openbmc_project/logging",
2987                     "xyz.openbmc_project.Collection.DeleteAll", "DeleteAll");
2988             });
2989 }
2990 
2991 /****************************************************
2992  * Redfish PostCode interfaces
2993  * using DBUS interface: getPostCodesTS
2994  ******************************************************/
2995 inline void requestRoutesPostCodesLogService(App& app)
2996 {
2997     BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/PostCodes/")
2998         .privileges(redfish::privileges::getLogService)
2999         .methods(
3000             boost::beast::http::verb::
3001                 get)([](const crow::Request&,
3002                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
3003             asyncResp->res.jsonValue = {
3004                 {"@odata.id",
3005                  "/redfish/v1/Systems/system/LogServices/PostCodes"},
3006                 {"@odata.type", "#LogService.v1_1_0.LogService"},
3007                 {"Name", "POST Code Log Service"},
3008                 {"Description", "POST Code Log Service"},
3009                 {"Id", "BIOS POST Code Log"},
3010                 {"OverWritePolicy", "WrapsWhenFull"},
3011                 {"Entries",
3012                  {{"@odata.id",
3013                    "/redfish/v1/Systems/system/LogServices/PostCodes/Entries"}}}};
3014 
3015             std::pair<std::string, std::string> redfishDateTimeOffset =
3016                 crow::utility::getDateTimeOffsetNow();
3017             asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
3018             asyncResp->res.jsonValue["DateTimeLocalOffset"] =
3019                 redfishDateTimeOffset.second;
3020 
3021             asyncResp->res.jsonValue["Actions"]["#LogService.ClearLog"] = {
3022                 {"target",
3023                  "/redfish/v1/Systems/system/LogServices/PostCodes/Actions/LogService.ClearLog"}};
3024         });
3025 }
3026 
3027 inline void requestRoutesPostCodesClear(App& app)
3028 {
3029     BMCWEB_ROUTE(
3030         app,
3031         "/redfish/v1/Systems/system/LogServices/PostCodes/Actions/LogService.ClearLog/")
3032         // The following privilege is incorrect;  It should be ConfigureManager
3033         //.privileges(redfish::privileges::postLogService)
3034         .privileges({{"ConfigureComponents"}})
3035         .methods(boost::beast::http::verb::post)(
3036             [](const crow::Request&,
3037                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
3038                 BMCWEB_LOG_DEBUG << "Do delete all postcodes entries.";
3039 
3040                 // Make call to post-code service to request clear all
3041                 crow::connections::systemBus->async_method_call(
3042                     [asyncResp](const boost::system::error_code ec) {
3043                         if (ec)
3044                         {
3045                             // TODO Handle for specific error code
3046                             BMCWEB_LOG_ERROR
3047                                 << "doClearPostCodes resp_handler got error "
3048                                 << ec;
3049                             asyncResp->res.result(boost::beast::http::status::
3050                                                       internal_server_error);
3051                             messages::internalError(asyncResp->res);
3052                             return;
3053                         }
3054                     },
3055                     "xyz.openbmc_project.State.Boot.PostCode0",
3056                     "/xyz/openbmc_project/State/Boot/PostCode0",
3057                     "xyz.openbmc_project.Collection.DeleteAll", "DeleteAll");
3058             });
3059 }
3060 
3061 static void fillPostCodeEntry(
3062     const std::shared_ptr<bmcweb::AsyncResp>& aResp,
3063     const boost::container::flat_map<
3064         uint64_t, std::tuple<uint64_t, std::vector<uint8_t>>>& postcode,
3065     const uint16_t bootIndex, const uint64_t codeIndex = 0,
3066     const uint64_t skip = 0, const uint64_t top = 0)
3067 {
3068     // Get the Message from the MessageRegistry
3069     const message_registries::Message* message =
3070         message_registries::getMessage("OpenBMC.0.2.BIOSPOSTCode");
3071 
3072     uint64_t currentCodeIndex = 0;
3073     nlohmann::json& logEntryArray = aResp->res.jsonValue["Members"];
3074 
3075     uint64_t firstCodeTimeUs = 0;
3076     for (const std::pair<uint64_t, std::tuple<uint64_t, std::vector<uint8_t>>>&
3077              code : postcode)
3078     {
3079         currentCodeIndex++;
3080         std::string postcodeEntryID =
3081             "B" + std::to_string(bootIndex) + "-" +
3082             std::to_string(currentCodeIndex); // 1 based index in EntryID string
3083 
3084         uint64_t usecSinceEpoch = code.first;
3085         uint64_t usTimeOffset = 0;
3086 
3087         if (1 == currentCodeIndex)
3088         { // already incremented
3089             firstCodeTimeUs = code.first;
3090         }
3091         else
3092         {
3093             usTimeOffset = code.first - firstCodeTimeUs;
3094         }
3095 
3096         // skip if no specific codeIndex is specified and currentCodeIndex does
3097         // not fall between top and skip
3098         if ((codeIndex == 0) &&
3099             (currentCodeIndex <= skip || currentCodeIndex > top))
3100         {
3101             continue;
3102         }
3103 
3104         // skip if a specific codeIndex is specified and does not match the
3105         // currentIndex
3106         if ((codeIndex > 0) && (currentCodeIndex != codeIndex))
3107         {
3108             // This is done for simplicity. 1st entry is needed to calculate
3109             // time offset. To improve efficiency, one can get to the entry
3110             // directly (possibly with flatmap's nth method)
3111             continue;
3112         }
3113 
3114         // currentCodeIndex is within top and skip or equal to specified code
3115         // index
3116 
3117         // Get the Created time from the timestamp
3118         std::string entryTimeStr;
3119         entryTimeStr =
3120             crow::utility::getDateTimeUint(usecSinceEpoch / 1000 / 1000);
3121 
3122         // assemble messageArgs: BootIndex, TimeOffset(100us), PostCode(hex)
3123         std::ostringstream hexCode;
3124         hexCode << "0x" << std::setfill('0') << std::setw(2) << std::hex
3125                 << std::get<0>(code.second);
3126         std::ostringstream timeOffsetStr;
3127         // Set Fixed -Point Notation
3128         timeOffsetStr << std::fixed;
3129         // Set precision to 4 digits
3130         timeOffsetStr << std::setprecision(4);
3131         // Add double to stream
3132         timeOffsetStr << static_cast<double>(usTimeOffset) / 1000 / 1000;
3133         std::vector<std::string> messageArgs = {
3134             std::to_string(bootIndex), timeOffsetStr.str(), hexCode.str()};
3135 
3136         // Get MessageArgs template from message registry
3137         std::string msg;
3138         if (message != nullptr)
3139         {
3140             msg = message->message;
3141 
3142             // fill in this post code value
3143             int i = 0;
3144             for (const std::string& messageArg : messageArgs)
3145             {
3146                 std::string argStr = "%" + std::to_string(++i);
3147                 size_t argPos = msg.find(argStr);
3148                 if (argPos != std::string::npos)
3149                 {
3150                     msg.replace(argPos, argStr.length(), messageArg);
3151                 }
3152             }
3153         }
3154 
3155         // Get Severity template from message registry
3156         std::string severity;
3157         if (message != nullptr)
3158         {
3159             severity = message->severity;
3160         }
3161 
3162         // add to AsyncResp
3163         logEntryArray.push_back({});
3164         nlohmann::json& bmcLogEntry = logEntryArray.back();
3165         bmcLogEntry = {
3166             {"@odata.type", "#LogEntry.v1_8_0.LogEntry"},
3167             {"@odata.id",
3168              "/redfish/v1/Systems/system/LogServices/PostCodes/Entries/" +
3169                  postcodeEntryID},
3170             {"Name", "POST Code Log Entry"},
3171             {"Id", postcodeEntryID},
3172             {"Message", std::move(msg)},
3173             {"MessageId", "OpenBMC.0.2.BIOSPOSTCode"},
3174             {"MessageArgs", std::move(messageArgs)},
3175             {"EntryType", "Event"},
3176             {"Severity", std::move(severity)},
3177             {"Created", entryTimeStr}};
3178         if (!std::get<std::vector<uint8_t>>(code.second).empty())
3179         {
3180             bmcLogEntry["AdditionalDataURI"] =
3181                 "/redfish/v1/Systems/system/LogServices/PostCodes/Entries/" +
3182                 postcodeEntryID + "/attachment";
3183         }
3184     }
3185 }
3186 
3187 static void getPostCodeForEntry(const std::shared_ptr<bmcweb::AsyncResp>& aResp,
3188                                 const uint16_t bootIndex,
3189                                 const uint64_t codeIndex)
3190 {
3191     crow::connections::systemBus->async_method_call(
3192         [aResp, bootIndex,
3193          codeIndex](const boost::system::error_code ec,
3194                     const boost::container::flat_map<
3195                         uint64_t, std::tuple<uint64_t, std::vector<uint8_t>>>&
3196                         postcode) {
3197             if (ec)
3198             {
3199                 BMCWEB_LOG_DEBUG << "DBUS POST CODE PostCode response error";
3200                 messages::internalError(aResp->res);
3201                 return;
3202             }
3203 
3204             // skip the empty postcode boots
3205             if (postcode.empty())
3206             {
3207                 return;
3208             }
3209 
3210             fillPostCodeEntry(aResp, postcode, bootIndex, codeIndex);
3211 
3212             aResp->res.jsonValue["Members@odata.count"] =
3213                 aResp->res.jsonValue["Members"].size();
3214         },
3215         "xyz.openbmc_project.State.Boot.PostCode0",
3216         "/xyz/openbmc_project/State/Boot/PostCode0",
3217         "xyz.openbmc_project.State.Boot.PostCode", "GetPostCodesWithTimeStamp",
3218         bootIndex);
3219 }
3220 
3221 static void getPostCodeForBoot(const std::shared_ptr<bmcweb::AsyncResp>& aResp,
3222                                const uint16_t bootIndex,
3223                                const uint16_t bootCount,
3224                                const uint64_t entryCount, const uint64_t skip,
3225                                const uint64_t top)
3226 {
3227     crow::connections::systemBus->async_method_call(
3228         [aResp, bootIndex, bootCount, entryCount, skip,
3229          top](const boost::system::error_code ec,
3230               const boost::container::flat_map<
3231                   uint64_t, std::tuple<uint64_t, std::vector<uint8_t>>>&
3232                   postcode) {
3233             if (ec)
3234             {
3235                 BMCWEB_LOG_DEBUG << "DBUS POST CODE PostCode response error";
3236                 messages::internalError(aResp->res);
3237                 return;
3238             }
3239 
3240             uint64_t endCount = entryCount;
3241             if (!postcode.empty())
3242             {
3243                 endCount = entryCount + postcode.size();
3244 
3245                 if ((skip < endCount) && ((top + skip) > entryCount))
3246                 {
3247                     uint64_t thisBootSkip =
3248                         std::max(skip, entryCount) - entryCount;
3249                     uint64_t thisBootTop =
3250                         std::min(top + skip, endCount) - entryCount;
3251 
3252                     fillPostCodeEntry(aResp, postcode, bootIndex, 0,
3253                                       thisBootSkip, thisBootTop);
3254                 }
3255                 aResp->res.jsonValue["Members@odata.count"] = endCount;
3256             }
3257 
3258             // continue to previous bootIndex
3259             if (bootIndex < bootCount)
3260             {
3261                 getPostCodeForBoot(aResp, static_cast<uint16_t>(bootIndex + 1),
3262                                    bootCount, endCount, skip, top);
3263             }
3264             else
3265             {
3266                 aResp->res.jsonValue["Members@odata.nextLink"] =
3267                     "/redfish/v1/Systems/system/LogServices/PostCodes/Entries?$skip=" +
3268                     std::to_string(skip + top);
3269             }
3270         },
3271         "xyz.openbmc_project.State.Boot.PostCode0",
3272         "/xyz/openbmc_project/State/Boot/PostCode0",
3273         "xyz.openbmc_project.State.Boot.PostCode", "GetPostCodesWithTimeStamp",
3274         bootIndex);
3275 }
3276 
3277 static void
3278     getCurrentBootNumber(const std::shared_ptr<bmcweb::AsyncResp>& aResp,
3279                          const uint64_t skip, const uint64_t top)
3280 {
3281     uint64_t entryCount = 0;
3282     sdbusplus::asio::getProperty<uint16_t>(
3283         *crow::connections::systemBus,
3284         "xyz.openbmc_project.State.Boot.PostCode0",
3285         "/xyz/openbmc_project/State/Boot/PostCode0",
3286         "xyz.openbmc_project.State.Boot.PostCode", "CurrentBootCycleCount",
3287         [aResp, entryCount, skip, top](const boost::system::error_code ec,
3288                                        const uint16_t bootCount) {
3289             if (ec)
3290             {
3291                 BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
3292                 messages::internalError(aResp->res);
3293                 return;
3294             }
3295             getPostCodeForBoot(aResp, 1, bootCount, entryCount, skip, top);
3296         });
3297 }
3298 
3299 inline void requestRoutesPostCodesEntryCollection(App& app)
3300 {
3301     BMCWEB_ROUTE(app,
3302                  "/redfish/v1/Systems/system/LogServices/PostCodes/Entries/")
3303         .privileges(redfish::privileges::getLogEntryCollection)
3304         .methods(boost::beast::http::verb::get)(
3305             [](const crow::Request& req,
3306                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
3307                 asyncResp->res.jsonValue["@odata.type"] =
3308                     "#LogEntryCollection.LogEntryCollection";
3309                 asyncResp->res.jsonValue["@odata.id"] =
3310                     "/redfish/v1/Systems/system/LogServices/PostCodes/Entries";
3311                 asyncResp->res.jsonValue["Name"] = "BIOS POST Code Log Entries";
3312                 asyncResp->res.jsonValue["Description"] =
3313                     "Collection of POST Code Log Entries";
3314                 asyncResp->res.jsonValue["Members"] = nlohmann::json::array();
3315                 asyncResp->res.jsonValue["Members@odata.count"] = 0;
3316 
3317                 uint64_t skip = 0;
3318                 uint64_t top = maxEntriesPerPage; // Show max entries by default
3319                 if (!getSkipParam(asyncResp, req, skip))
3320                 {
3321                     return;
3322                 }
3323                 if (!getTopParam(asyncResp, req, top))
3324                 {
3325                     return;
3326                 }
3327                 getCurrentBootNumber(asyncResp, skip, top);
3328             });
3329 }
3330 
3331 /**
3332  * @brief Parse post code ID and get the current value and index value
3333  *        eg: postCodeID=B1-2, currentValue=1, index=2
3334  *
3335  * @param[in]  postCodeID     Post Code ID
3336  * @param[out] currentValue   Current value
3337  * @param[out] index          Index value
3338  *
3339  * @return bool true if the parsing is successful, false the parsing fails
3340  */
3341 inline static bool parsePostCode(const std::string& postCodeID,
3342                                  uint64_t& currentValue, uint16_t& index)
3343 {
3344     std::vector<std::string> split;
3345     boost::algorithm::split(split, postCodeID, boost::is_any_of("-"));
3346     if (split.size() != 2 || split[0].length() < 2 || split[0].front() != 'B')
3347     {
3348         return false;
3349     }
3350 
3351     // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
3352     const char* start = split[0].data() + 1;
3353     // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
3354     const char* end = split[0].data() + split[0].size();
3355     auto [ptrIndex, ecIndex] = std::from_chars(start, end, index);
3356 
3357     if (ptrIndex != end || ecIndex != std::errc())
3358     {
3359         return false;
3360     }
3361 
3362     start = split[1].data();
3363 
3364     // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
3365     end = split[1].data() + split[1].size();
3366     auto [ptrValue, ecValue] = std::from_chars(start, end, currentValue);
3367     if (ptrValue != end || ecValue != std::errc())
3368     {
3369         return false;
3370     }
3371 
3372     return true;
3373 }
3374 
3375 inline void requestRoutesPostCodesEntryAdditionalData(App& app)
3376 {
3377     BMCWEB_ROUTE(
3378         app,
3379         "/redfish/v1/Systems/system/LogServices/PostCodes/Entries/<str>/attachment/")
3380         .privileges(redfish::privileges::getLogEntry)
3381         .methods(boost::beast::http::verb::get)(
3382             [](const crow::Request& req,
3383                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3384                const std::string& postCodeID) {
3385                 if (!http_helpers::isOctetAccepted(
3386                         req.getHeaderValue("Accept")))
3387                 {
3388                     asyncResp->res.result(
3389                         boost::beast::http::status::bad_request);
3390                     return;
3391                 }
3392 
3393                 uint64_t currentValue = 0;
3394                 uint16_t index = 0;
3395                 if (!parsePostCode(postCodeID, currentValue, index))
3396                 {
3397                     messages::resourceNotFound(asyncResp->res, "LogEntry",
3398                                                postCodeID);
3399                     return;
3400                 }
3401 
3402                 crow::connections::systemBus->async_method_call(
3403                     [asyncResp, postCodeID, currentValue](
3404                         const boost::system::error_code ec,
3405                         const std::vector<std::tuple<
3406                             uint64_t, std::vector<uint8_t>>>& postcodes) {
3407                         if (ec.value() == EBADR)
3408                         {
3409                             messages::resourceNotFound(asyncResp->res,
3410                                                        "LogEntry", postCodeID);
3411                             return;
3412                         }
3413                         if (ec)
3414                         {
3415                             BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
3416                             messages::internalError(asyncResp->res);
3417                             return;
3418                         }
3419 
3420                         size_t value = static_cast<size_t>(currentValue) - 1;
3421                         if (value == std::string::npos ||
3422                             postcodes.size() < currentValue)
3423                         {
3424                             BMCWEB_LOG_ERROR << "Wrong currentValue value";
3425                             messages::resourceNotFound(asyncResp->res,
3426                                                        "LogEntry", postCodeID);
3427                             return;
3428                         }
3429 
3430                         auto& [tID, c] = postcodes[value];
3431                         if (c.empty())
3432                         {
3433                             BMCWEB_LOG_INFO << "No found post code data";
3434                             messages::resourceNotFound(asyncResp->res,
3435                                                        "LogEntry", postCodeID);
3436                             return;
3437                         }
3438                         // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
3439                         const char* d = reinterpret_cast<const char*>(c.data());
3440                         std::string_view strData(d, c.size());
3441 
3442                         asyncResp->res.addHeader("Content-Type",
3443                                                  "application/octet-stream");
3444                         asyncResp->res.addHeader("Content-Transfer-Encoding",
3445                                                  "Base64");
3446                         asyncResp->res.body() =
3447                             crow::utility::base64encode(strData);
3448                     },
3449                     "xyz.openbmc_project.State.Boot.PostCode0",
3450                     "/xyz/openbmc_project/State/Boot/PostCode0",
3451                     "xyz.openbmc_project.State.Boot.PostCode", "GetPostCodes",
3452                     index);
3453             });
3454 }
3455 
3456 inline void requestRoutesPostCodesEntry(App& app)
3457 {
3458     BMCWEB_ROUTE(
3459         app, "/redfish/v1/Systems/system/LogServices/PostCodes/Entries/<str>/")
3460         .privileges(redfish::privileges::getLogEntry)
3461         .methods(boost::beast::http::verb::get)(
3462             [](const crow::Request&,
3463                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3464                const std::string& targetID) {
3465                 uint16_t bootIndex = 0;
3466                 uint64_t codeIndex = 0;
3467                 if (!parsePostCode(targetID, codeIndex, bootIndex))
3468                 {
3469                     // Requested ID was not found
3470                     messages::resourceMissingAtURI(asyncResp->res, targetID);
3471                     return;
3472                 }
3473                 if (bootIndex == 0 || codeIndex == 0)
3474                 {
3475                     BMCWEB_LOG_DEBUG << "Get Post Code invalid entry string "
3476                                      << targetID;
3477                 }
3478 
3479                 asyncResp->res.jsonValue["@odata.type"] =
3480                     "#LogEntry.v1_4_0.LogEntry";
3481                 asyncResp->res.jsonValue["@odata.id"] =
3482                     "/redfish/v1/Systems/system/LogServices/PostCodes/Entries";
3483                 asyncResp->res.jsonValue["Name"] = "BIOS POST Code Log Entries";
3484                 asyncResp->res.jsonValue["Description"] =
3485                     "Collection of POST Code Log Entries";
3486                 asyncResp->res.jsonValue["Members"] = nlohmann::json::array();
3487                 asyncResp->res.jsonValue["Members@odata.count"] = 0;
3488 
3489                 getPostCodeForEntry(asyncResp, bootIndex, codeIndex);
3490             });
3491 }
3492 
3493 } // namespace redfish
3494