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