1 /*
2  * Copyright 2018 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "updater.hpp"
18 
19 #include "firmware_handler.hpp"
20 #include "status.hpp"
21 #include "tool_errors.hpp"
22 #include "util.hpp"
23 
24 #include <algorithm>
25 #include <blobs-ipmid/blobs.hpp>
26 #include <cstring>
27 #include <ipmiblob/blob_errors.hpp>
28 #include <memory>
29 #include <string>
30 #include <thread>
31 #include <vector>
32 
33 namespace host_tool
34 {
35 
36 bool UpdateHandler::checkAvailable(const std::string& goalFirmware)
37 {
38     std::vector<std::string> blobs = blob->getBlobList();
39 
40     auto blobInst = std::find_if(
41         blobs.begin(), blobs.end(), [&goalFirmware](const std::string& iter) {
42             /* Running into weird scenarios where the string comparison doesn't
43              * work.  TODO: revisit.
44              */
45             return (0 == std::memcmp(goalFirmware.c_str(), iter.c_str(),
46                                      goalFirmware.length()));
47             // return (goalFirmware.compare(iter));
48         });
49     if (blobInst == blobs.end())
50     {
51         std::fprintf(stderr, "%s not found\n", goalFirmware.c_str());
52         return false;
53     }
54 
55     /* Call stat on /flash/image (or /flash/tarball) and check if data interface
56      * is supported.
57      */
58     ipmiblob::StatResponse stat;
59 
60     try
61     {
62         stat = blob->getStat(goalFirmware);
63     }
64     catch (const ipmiblob::BlobException& b)
65     {
66         std::fprintf(stderr, "Received exception '%s' on getStat\n", b.what());
67         return false;
68     }
69 
70     auto supported = handler->supportedType();
71     if ((stat.blob_state & supported) == 0)
72     {
73         std::fprintf(stderr, "data interface selected not supported.\n");
74         return false;
75     }
76 
77     return true;
78 }
79 
80 void UpdateHandler::sendFile(const std::string& target, const std::string& path)
81 {
82     std::uint16_t session;
83     auto supported = handler->supportedType();
84 
85     try
86     {
87         session = blob->openBlob(
88             target, static_cast<std::uint16_t>(supported) |
89                         static_cast<std::uint16_t>(blobs::OpenFlags::write));
90     }
91     catch (const ipmiblob::BlobException& b)
92     {
93         throw ToolException("blob exception received: " +
94                             std::string(b.what()));
95     }
96 
97     if (!handler->sendContents(path, session))
98     {
99         /* Need to close the session on failure, or it's stuck open (until the
100          * blob handler timeout is implemented, and even then, why make it wait.
101          */
102         blob->closeBlob(session);
103         throw ToolException("Failed to send contents of " + path);
104     }
105 
106     blob->closeBlob(session);
107 }
108 
109 /* Poll an open verification session.  Handling closing the session is not yet
110  * owned by this method. */
111 bool pollStatus(std::uint16_t session, ipmiblob::BlobInterface* blob)
112 {
113     using namespace std::chrono_literals;
114 
115     static constexpr auto verificationSleep = 5s;
116     ipmi_flash::ActionStatus result = ipmi_flash::ActionStatus::unknown;
117 
118     try
119     {
120         static constexpr int commandAttempts = 20;
121         int attempts = 0;
122         bool exitLoop = false;
123 
124         /* Reach back the current status from the verification service output.
125          */
126         while (attempts++ < commandAttempts)
127         {
128             ipmiblob::StatResponse resp = blob->getStat(session);
129 
130             if (resp.metadata.size() != sizeof(std::uint8_t))
131             {
132                 /* TODO: How do we want to handle the verification failures,
133                  * because closing the session to the verify blob has a special
134                  * as-of-yet not fully defined behavior.
135                  */
136                 std::fprintf(stderr, "Received invalid metadata response!!!\n");
137             }
138 
139             result = static_cast<ipmi_flash::ActionStatus>(resp.metadata[0]);
140 
141             switch (result)
142             {
143                 case ipmi_flash::ActionStatus::failed:
144                     std::fprintf(stderr, "failed\n");
145                     exitLoop = true;
146                     break;
147                 case ipmi_flash::ActionStatus::unknown:
148                     std::fprintf(stderr, "other\n");
149                     break;
150                 case ipmi_flash::ActionStatus::running:
151                     std::fprintf(stderr, "running\n");
152                     break;
153                 case ipmi_flash::ActionStatus::success:
154                     std::fprintf(stderr, "success\n");
155                     exitLoop = true;
156                     break;
157                 default:
158                     std::fprintf(stderr, "wat\n");
159             }
160 
161             if (exitLoop)
162             {
163                 break;
164             }
165             std::this_thread::sleep_for(verificationSleep);
166         }
167     }
168     catch (const ipmiblob::BlobException& b)
169     {
170         throw ToolException("blob exception received: " +
171                             std::string(b.what()));
172     }
173 
174     /* TODO: If this is reached and it's not success, it may be worth just
175      * throwing a ToolException with a timeout message specifying the final
176      * read's value.
177      *
178      * TODO: Given that excepting from certain points leaves the BMC update
179      * state machine in an inconsistent state, we need to carefully evaluate
180      * which exceptions from the lower layers allow one to try and delete the
181      * blobs to rollback the state and progress.
182      */
183     return (result == ipmi_flash::ActionStatus::success);
184 }
185 
186 bool UpdateHandler::verifyFile(const std::string& target)
187 {
188     std::uint16_t session;
189     bool success = false;
190 
191     try
192     {
193         session = blob->openBlob(
194             target, static_cast<std::uint16_t>(blobs::OpenFlags::write));
195     }
196     catch (const ipmiblob::BlobException& b)
197     {
198         throw ToolException("blob exception received: " +
199                             std::string(b.what()));
200     }
201 
202     std::fprintf(stderr, "Committing to %s to trigger service\n",
203                  target.c_str());
204 
205     try
206     {
207         blob->commit(session, {});
208     }
209     catch (const ipmiblob::BlobException& b)
210     {
211         throw ToolException("blob exception received: " +
212                             std::string(b.what()));
213     }
214 
215     std::fprintf(stderr, "Calling stat on %s session to check status\n",
216                  target.c_str());
217 
218     if (pollStatus(session, blob))
219     {
220         std::fprintf(stderr, "Returned success\n");
221         success = true;
222     }
223     else
224     {
225         std::fprintf(stderr, "Returned non-success (could still "
226                              "be running (unlikely))\n");
227     }
228 
229     blob->closeBlob(session);
230     return (success == true);
231 }
232 
233 void updaterMain(UpdateHandler* updater, const std::string& imagePath,
234                  const std::string& signaturePath)
235 {
236     /* TODO(venture): Add optional parameter to specify the flash type, default
237      * to legacy for now.
238      */
239     bool goalSupported =
240         updater->checkAvailable(ipmi_flash::staticLayoutBlobId);
241     if (!goalSupported)
242     {
243         throw ToolException("Goal firmware or interface not supported");
244     }
245 
246     /* Yay, our data handler is supported. */
247 
248     /* Send over the firmware image. */
249     std::fprintf(stderr, "Sending over the firmware image.\n");
250     updater->sendFile(ipmi_flash::staticLayoutBlobId, imagePath);
251 
252     /* Send over the hash contents. */
253     std::fprintf(stderr, "Sending over the hash file.\n");
254     updater->sendFile(ipmi_flash::hashBlobId, signaturePath);
255 
256     /* Trigger the verification by opening and committing the verify file. */
257     std::fprintf(stderr, "Opening the verification file\n");
258     if (updater->verifyFile(ipmi_flash::verifyBlobId))
259     {
260         std::fprintf(stderr, "succeeded\n");
261     }
262     else
263     {
264         std::fprintf(stderr, "failed\n");
265         throw ToolException("Verification failed");
266     }
267 
268     /* Trigger the update by opening and committing the update file. */
269     std::fprintf(stderr, "Opening the update file\n");
270     if (updater->verifyFile(ipmi_flash::updateBlobId))
271     {
272         std::fprintf(stderr, "succeeded\n");
273     }
274     else
275     {
276         /* Depending on the update mechanism used, this may be uninteresting.
277          * For instance, for the static layout, we use the reboot update
278          * mechanism.  Which doesn't always lead to a successful return before
279          * the BMC starts shutting down services.
280          */
281         std::fprintf(stderr, "failed\n");
282         throw ToolException("Update failed");
283     }
284 }
285 
286 } // namespace host_tool
287