diff --git a/.mbedignore b/.mbedignore new file mode 100644 index 0000000..ab097e5 --- /dev/null +++ b/.mbedignore @@ -0,0 +1 @@ +test_modules/* diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d05251..cbe459f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ ## Changelog for Pelion Device Management Client Lite +### Release 1.2.0-lite (19.08.2020) + +* Fixed an issue where Client Lite would trigger sleep-callback during the bootstrapping process. +* Changed the notification handler to send a notification only when crossing the "less than" or "greater than" notification threshold values. + ### Release 1.1.1-lite (05.06.2020) Client Lite 1.1.0 sends an additional component update object (/14) as part of its registration message even though the client does not support it yet. The update service has changed recently to handle the client differently, so there is no backward compatibility. Client Lite 1.1.0 cannot successfully update firmware. As part of this patch release, component update is behind a feature flag that is disabled in Client Lite release. diff --git a/DOXYGEN_FRONTPAGE.md b/DOXYGEN_FRONTPAGE.md index 2ef23eb..d38e8c8 100644 --- a/DOXYGEN_FRONTPAGE.md +++ b/DOXYGEN_FRONTPAGE.md @@ -12,3 +12,48 @@ These APIs enable you to: - Provide functionality to update the devices over the air remotely controlled from the service side. The API (C code) allows quick application development and portability. + +## Running the Device Management client + +Client Lite runs on top of event loop, originating from project called Nanostack. This event handler is sometimes referred as `ns_hal` and sometimes as `eventOS`, so any functions prefixed with those, are part of the same eventing system. +See \ref nanostack-eventloop for its API description. + +To use the Client Lite, we must first create an event handler, by calling following function: + +```c +int8_t eventOS_event_handler_create(void (*handler_func_ptr)(arm_event_t *), uint8_t init_event_type); +``` + +The `handler_func_ptr` is our callback function, and the return value of the call is our event handler's identifier. First parameter to our callback is event structure, that usually contain just some 8-bit type number to notify which event happened, but might carry other data as well. When creating the event handler, the event loop issues a call to the given function with type set to match `init_event_type`. + +Now that the even loop is initialized, we may initialise the Client Lite and give our callbacks ID for it that we received from the event loop. + +```c +pdmc_connect_init(my_event_id); +``` + +When the client is running, all the actions happen through events that are coming to our callback. The event handler that we gave for the client, might look like this: + +```c +void pdmc_event_handler(arm_event_t *event) +{ + if (event->event_type == 0 && event->event_id == 0) { + // Ignore the initial event. + return; + } + + if (event->event_id == LWM2M_INTERFACE_OBSERVER_EVENT_BOOTSTRAP_DONE) { + printf("Client bootstrapped\n"); + } else if (event->event_id == M2M_CLIENT_EVENT_SETUP_COMPLETED) { + pdmc_connect_register(get_network_interface()); + } +} +``` + +Final step for the application is then to start the even loop, which usually is just: +```c +eventOS_scheduler_run(); +``` + +Please refer to [Device Management Client Lite Developer Guide](https://www.pelion.com/docs/pelion-client-lite/latest/developer-guide/index.html) for in depth tutorials how to use the client. +Also, see any of the given example applications for full OS specific applications. Code snippets in this page are simplified and uncomplete. diff --git a/Doxyfile b/Doxyfile index 901399d..b4131e3 100644 --- a/Doxyfile +++ b/Doxyfile @@ -38,7 +38,7 @@ PROJECT_NAME = "Device Management Client Lite" # could be handy for archiving the generated documentation or if some version # control system is used. -PROJECT_NUMBER = +PROJECT_NUMBER = # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a @@ -51,14 +51,14 @@ PROJECT_BRIEF = "Device Management Client Lite library enables low memo # pixels and the maximum width should not exceed 200 pixels. Doxygen will copy # the logo to the output directory. -PROJECT_LOGO = +PROJECT_LOGO = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path # into which the generated documentation will be written. If a relative path is # entered, it will be relative to the location where doxygen was started. If # left blank the current directory will be used. -OUTPUT_DIRECTORY = +OUTPUT_DIRECTORY = # If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- # directories (in 2 levels) under the output directory of each output format and @@ -118,7 +118,7 @@ REPEAT_BRIEF = YES # the entity):The $name class, The $name widget, The $name file, is, provides, # specifies, contains, represents, a, an and the. -ABBREVIATE_BRIEF = +ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # doxygen will generate a detailed section even if there is only a brief @@ -152,7 +152,7 @@ FULL_PATH_NAMES = YES # will be relative from the directory where doxygen is started. # This tag requires that the tag FULL_PATH_NAMES is set to YES. -STRIP_FROM_PATH = +STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the # path mentioned in the documentation of a class, which tells the reader which @@ -161,7 +161,7 @@ STRIP_FROM_PATH = # specify the list of include paths that are normally passed to the compiler # using the -I flag. -STRIP_FROM_INC_PATH = +STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but # less readable) file names. This can be useful is your file systems doesn't @@ -177,7 +177,7 @@ SHORT_NAMES = NO # description.) # The default value is: NO. -JAVADOC_AUTOBRIEF = NO +JAVADOC_AUTOBRIEF = YES # If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first # line (until the first dot) of a Qt-style comment as the brief description. If @@ -185,7 +185,7 @@ JAVADOC_AUTOBRIEF = NO # requiring an explicit \brief command for a brief description.) # The default value is: NO. -QT_AUTOBRIEF = NO +QT_AUTOBRIEF = YES # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a # multi-line C++ special comment block (i.e. a block of //! or /// comments) as @@ -228,13 +228,13 @@ TAB_SIZE = 4 # "Side Effects:". You can put \n's in the value part of an alias to insert # newlines. -ALIASES = +ALIASES = # This tag can be used to specify a number of word-keyword mappings (TCL only). # A mapping has the form "name=value". For example adding "class=itcl::class" # will allow you to use the command class in the itcl::class meaning. -TCL_SUBST = +TCL_SUBST = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources # only. Doxygen will then generate output that is more tailored for C. For @@ -281,7 +281,7 @@ OPTIMIZE_OUTPUT_VHDL = NO # Note that for custom extensions you also need to set FILE_PATTERNS otherwise # the files are not read by doxygen. -EXTENSION_MAPPING = +EXTENSION_MAPPING = # If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments # according to the Markdown format, which allows for more readable @@ -638,7 +638,7 @@ GENERATE_DEPRECATEDLIST= YES # sections, marked by \if ... \endif and \cond # ... \endcond blocks. -ENABLED_SECTIONS = +ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the # initial value of a variable or macro / define can have for it to appear in the @@ -680,7 +680,7 @@ SHOW_NAMESPACES = YES # by doxygen. Whatever the program writes to standard output is used as the file # version. For an example see the documentation. -FILE_VERSION_FILTER = +FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated @@ -693,7 +693,7 @@ FILE_VERSION_FILTER = # DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE # tag is left empty. -LAYOUT_FILE = +LAYOUT_FILE = # The CITE_BIB_FILES tag can be used to specify one or more bib files containing # the reference definitions. This must be a list of .bib files. The .bib @@ -703,7 +703,7 @@ LAYOUT_FILE = # LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the # search path. See also \cite for info how to create references. -CITE_BIB_FILES = +CITE_BIB_FILES = #--------------------------------------------------------------------------- # Configuration options related to warning and progress messages @@ -768,7 +768,7 @@ WARN_FORMAT = "$file:$line: $text" # messages should be written. If left blank the output is written to standard # error (stderr). -WARN_LOGFILE = +WARN_LOGFILE = #--------------------------------------------------------------------------- # Configuration options related to the input files @@ -781,8 +781,11 @@ WARN_LOGFILE = # Note: If this tag is empty the current directory is searched. INPUT = DOXYGEN_FRONTPAGE.md \ + device-management-client \ mbed-client/mbed-client \ - mbed-cloud-client + mbed-client/mbed-protocol-manager/mbed-protocol-manager \ + libs/nanostack-libservice/mbed-client-libservice \ + libs/sal-stack-nanostack-eventloop/nanostack-event-loop # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses @@ -807,7 +810,7 @@ INPUT_ENCODING = UTF-8 # *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, # *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf and *.qsf. -FILE_PATTERNS = +FILE_PATTERNS = # The RECURSIVE tag can be used to specify whether or not subdirectories should # be searched for input files as well. @@ -822,7 +825,7 @@ RECURSIVE = YES # Note that relative paths are relative to the directory from which doxygen is # run. -EXCLUDE = +EXCLUDE = # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded @@ -838,7 +841,7 @@ EXCLUDE_SYMLINKS = NO # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories for example use the pattern */test/* -EXCLUDE_PATTERNS = +EXCLUDE_PATTERNS = # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the @@ -849,20 +852,20 @@ EXCLUDE_PATTERNS = # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories use the pattern */test/* -EXCLUDE_SYMBOLS = +EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or directories # that contain example code fragments that are included (see the \include # command). -EXAMPLE_PATH = +EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and # *.h) to filter out the source-files in the directories. If left blank all # files are included. -EXAMPLE_PATTERNS = +EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude commands @@ -875,7 +878,7 @@ EXAMPLE_RECURSIVE = NO # that contain images that are to be included in the documentation (see the # \image command). -IMAGE_PATH = +IMAGE_PATH = mbed-client/mbed-protocol-manager/docs/diagrams # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program @@ -896,7 +899,7 @@ IMAGE_PATH = # need to set EXTENSION_MAPPING for the extension otherwise the files are not # properly processed by doxygen. -INPUT_FILTER = +INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. Doxygen will compare the file name with each pattern and apply the @@ -909,7 +912,7 @@ INPUT_FILTER = # need to set EXTENSION_MAPPING for the extension otherwise the files are not # properly processed by doxygen. -FILTER_PATTERNS = +FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will also be used to filter the input files that are used for @@ -924,7 +927,7 @@ FILTER_SOURCE_FILES = NO # *.ext= (so without naming a filter). # This tag requires that the tag FILTER_SOURCE_FILES is set to YES. -FILTER_SOURCE_PATTERNS = +FILTER_SOURCE_PATTERNS = # If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that # is part of the input, its contents will be placed on the main page @@ -1036,7 +1039,7 @@ CLANG_ASSISTED_PARSING = NO # specified with INPUT and INCLUDE_PATH. # This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES. -CLANG_OPTIONS = +CLANG_OPTIONS = # If clang assisted parsing is enabled you can provide the clang parser with the # path to the compilation database (see: @@ -1073,7 +1076,7 @@ COLS_IN_ALPHA_INDEX = 5 # while generating the index headers. # This tag requires that the tag ALPHABETICAL_INDEX is set to YES. -IGNORE_PREFIX = +IGNORE_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the HTML output @@ -1117,7 +1120,7 @@ HTML_FILE_EXTENSION = .html # of the possible markers and block names see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_HEADER = +HTML_HEADER = # The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each # generated HTML page. If the tag is left blank doxygen will generate a standard @@ -1127,7 +1130,7 @@ HTML_HEADER = # that doxygen normally uses. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_FOOTER = +HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading style # sheet that is used by each HTML page. It can be used to fine-tune the look of @@ -1139,7 +1142,7 @@ HTML_FOOTER = # obsolete. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_STYLESHEET = +HTML_STYLESHEET = # The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined # cascading style sheets that are included after the standard style sheets @@ -1152,7 +1155,7 @@ HTML_STYLESHEET = # list). For an example see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_EXTRA_STYLESHEET = +HTML_EXTRA_STYLESHEET = # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note @@ -1162,7 +1165,7 @@ HTML_EXTRA_STYLESHEET = # files will be copied as-is; there are no commands or markers available. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_EXTRA_FILES = +HTML_EXTRA_FILES = # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen # will adjust the colors in the style sheet and background images according to @@ -1302,7 +1305,7 @@ GENERATE_HTMLHELP = NO # written to the html output directory. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. -CHM_FILE = +CHM_FILE = # The HHC_LOCATION tag can be used to specify the location (absolute path # including file name) of the HTML help compiler (hhc.exe). If non-empty, @@ -1310,7 +1313,7 @@ CHM_FILE = # The file has to be specified with full path. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. -HHC_LOCATION = +HHC_LOCATION = # The GENERATE_CHI flag controls if a separate .chi index file is generated # (YES) or that it should be included in the master .chm file (NO). @@ -1323,7 +1326,7 @@ GENERATE_CHI = NO # and project file content. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. -CHM_INDEX_ENCODING = +CHM_INDEX_ENCODING = # The BINARY_TOC flag controls whether a binary table of contents is generated # (YES) or a normal table of contents (NO) in the .chm file. Furthermore it @@ -1354,7 +1357,7 @@ GENERATE_QHP = NO # the HTML output folder. # This tag requires that the tag GENERATE_QHP is set to YES. -QCH_FILE = +QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help # Project output. For more information please see Qt Help Project / Namespace @@ -1377,28 +1380,28 @@ QHP_VIRTUAL_FOLDER = doc # Filters (see: http://doc.qt.io/qt-4.8/qthelpproject.html#custom-filters). # This tag requires that the tag GENERATE_QHP is set to YES. -QHP_CUST_FILTER_NAME = +QHP_CUST_FILTER_NAME = # The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see Qt Help Project / Custom # Filters (see: http://doc.qt.io/qt-4.8/qthelpproject.html#custom-filters). # This tag requires that the tag GENERATE_QHP is set to YES. -QHP_CUST_FILTER_ATTRS = +QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's filter section matches. Qt Help Project / Filter Attributes (see: # http://doc.qt.io/qt-4.8/qthelpproject.html#filter-attributes). # This tag requires that the tag GENERATE_QHP is set to YES. -QHP_SECT_FILTER_ATTRS = +QHP_SECT_FILTER_ATTRS = # The QHG_LOCATION tag can be used to specify the location of Qt's # qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the # generated .qhp file. # This tag requires that the tag GENERATE_QHP is set to YES. -QHG_LOCATION = +QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be # generated, together with the HTML files, they form an Eclipse help plugin. To @@ -1531,7 +1534,7 @@ MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest # MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols # This tag requires that the tag USE_MATHJAX is set to YES. -MATHJAX_EXTENSIONS = +MATHJAX_EXTENSIONS = # The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces # of code that will be used on startup of the MathJax code. See the MathJax site @@ -1539,7 +1542,7 @@ MATHJAX_EXTENSIONS = # example see the documentation. # This tag requires that the tag USE_MATHJAX is set to YES. -MATHJAX_CODEFILE = +MATHJAX_CODEFILE = # When the SEARCHENGINE tag is enabled doxygen will generate a search box for # the HTML output. The underlying search engine uses javascript and DHTML and @@ -1599,7 +1602,7 @@ EXTERNAL_SEARCH = NO # Searching" for details. # This tag requires that the tag SEARCHENGINE is set to YES. -SEARCHENGINE_URL = +SEARCHENGINE_URL = # When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed # search data is written to a file for indexing by an external tool. With the @@ -1615,7 +1618,7 @@ SEARCHDATA_FILE = searchdata.xml # projects and redirect the results back to the right project. # This tag requires that the tag SEARCHENGINE is set to YES. -EXTERNAL_SEARCH_ID = +EXTERNAL_SEARCH_ID = # The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen # projects other than the one defined by this configuration file, but that are @@ -1625,7 +1628,7 @@ EXTERNAL_SEARCH_ID = # EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ... # This tag requires that the tag SEARCHENGINE is set to YES. -EXTRA_SEARCH_MAPPINGS = +EXTRA_SEARCH_MAPPINGS = #--------------------------------------------------------------------------- # Configuration options related to the LaTeX output @@ -1689,7 +1692,7 @@ PAPER_TYPE = a4 # If left blank no extra packages will be included. # This tag requires that the tag GENERATE_LATEX is set to YES. -EXTRA_PACKAGES = +EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for the # generated LaTeX document. The header should contain everything until the first @@ -1705,7 +1708,7 @@ EXTRA_PACKAGES = # to HTML_HEADER. # This tag requires that the tag GENERATE_LATEX is set to YES. -LATEX_HEADER = +LATEX_HEADER = # The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the # generated LaTeX document. The footer should contain everything after the last @@ -1716,7 +1719,7 @@ LATEX_HEADER = # Note: Only use a user-defined footer if you know what you are doing! # This tag requires that the tag GENERATE_LATEX is set to YES. -LATEX_FOOTER = +LATEX_FOOTER = # The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined # LaTeX style sheets that are included after the standard style sheets created @@ -1727,7 +1730,7 @@ LATEX_FOOTER = # list). # This tag requires that the tag GENERATE_LATEX is set to YES. -LATEX_EXTRA_STYLESHEET = +LATEX_EXTRA_STYLESHEET = # The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the LATEX_OUTPUT output @@ -1735,7 +1738,7 @@ LATEX_EXTRA_STYLESHEET = # markers available. # This tag requires that the tag GENERATE_LATEX is set to YES. -LATEX_EXTRA_FILES = +LATEX_EXTRA_FILES = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is # prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will @@ -1843,14 +1846,14 @@ RTF_HYPERLINKS = NO # default style sheet that doxygen normally uses. # This tag requires that the tag GENERATE_RTF is set to YES. -RTF_STYLESHEET_FILE = +RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an RTF document. Syntax is # similar to doxygen's config file. A template extensions file can be generated # using doxygen -e rtf extensionFile. # This tag requires that the tag GENERATE_RTF is set to YES. -RTF_EXTENSIONS_FILE = +RTF_EXTENSIONS_FILE = # If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code # with syntax highlighting in the RTF output. @@ -1895,7 +1898,7 @@ MAN_EXTENSION = .3 # MAN_EXTENSION with the initial . removed. # This tag requires that the tag GENERATE_MAN is set to YES. -MAN_SUBDIR = +MAN_SUBDIR = # If the MAN_LINKS tag is set to YES and doxygen generates man output, then it # will generate one additional man file for each entity documented in the real @@ -2008,7 +2011,7 @@ PERLMOD_PRETTY = YES # overwrite each other's variables. # This tag requires that the tag GENERATE_PERLMOD is set to YES. -PERLMOD_MAKEVAR_PREFIX = +PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor @@ -2049,7 +2052,7 @@ SEARCH_INCLUDES = YES # preprocessor. # This tag requires that the tag SEARCH_INCLUDES is set to YES. -INCLUDE_PATH = +INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the @@ -2057,7 +2060,7 @@ INCLUDE_PATH = # used. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. -INCLUDE_FILE_PATTERNS = +INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that are # defined before the preprocessor is started (similar to the -D option of e.g. @@ -2067,7 +2070,7 @@ INCLUDE_FILE_PATTERNS = # recursively expanded use the := operator instead of the = operator. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. -PREDEFINED = +PREDEFINED = __DOXYGEN__ # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this # tag can be used to specify a list of macro names that should be expanded. The @@ -2076,7 +2079,7 @@ PREDEFINED = # definition found in the source code. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. -EXPAND_AS_DEFINED = +EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will # remove all references to function-like macros that are alone on a line, have @@ -2105,13 +2108,13 @@ SKIP_FUNCTION_MACROS = YES # the path). If a tag file is not located in the directory in which doxygen is # run, you must also specify the path to the tagfile here. -TAGFILES = +TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create a # tag file that is based on the input files it reads. See section "Linking to # external documentation" for more information about the usage of tag files. -GENERATE_TAGFILE = +GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES, all external class will be listed in # the class index. If set to NO, only the inherited external classes will be @@ -2160,14 +2163,14 @@ CLASS_DIAGRAMS = YES # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. -MSCGEN_PATH = +MSCGEN_PATH = # You can include diagrams made with dia in doxygen documentation. Doxygen will # then run dia to produce the diagram and insert it in the documentation. The # DIA_PATH tag allows you to specify the directory where the dia binary resides. # If left empty dia is assumed to be found in the default search path. -DIA_PATH = +DIA_PATH = # If set to YES the inheritance and collaboration graphs will hide inheritance # and usage relations if the target is undocumented or is not a class. @@ -2216,7 +2219,7 @@ DOT_FONTSIZE = 10 # the path where dot can find it using this tag. # This tag requires that the tag HAVE_DOT is set to YES. -DOT_FONTPATH = +DOT_FONTPATH = # If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for # each documented class showing the direct and indirect inheritance relations. @@ -2248,7 +2251,7 @@ GROUP_GRAPHS = YES # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. -UML_LOOK = NO +UML_LOOK = YES # If the UML_LOOK tag is enabled, the fields and methods are shown inside the # class node. If there are many fields or methods and many nodes the graph may @@ -2299,7 +2302,7 @@ INCLUDED_BY_GRAPH = YES # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. -CALL_GRAPH = NO +CALL_GRAPH = YES # If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller # dependency graph for every global function or class method. @@ -2360,26 +2363,26 @@ INTERACTIVE_SVG = NO # found. If left blank, it is assumed the dot tool can be found in the path. # This tag requires that the tag HAVE_DOT is set to YES. -DOT_PATH = "../../Program Files (x86)/Graphviz2.38/bin" +DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the \dotfile # command). # This tag requires that the tag HAVE_DOT is set to YES. -DOTFILE_DIRS = +DOTFILE_DIRS = # The MSCFILE_DIRS tag can be used to specify one or more directories that # contain msc files that are included in the documentation (see the \mscfile # command). -MSCFILE_DIRS = +MSCFILE_DIRS = # The DIAFILE_DIRS tag can be used to specify one or more directories that # contain dia files that are included in the documentation (see the \diafile # command). -DIAFILE_DIRS = +DIAFILE_DIRS = # When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the # path where java can find the plantuml.jar file. If left blank, it is assumed @@ -2387,17 +2390,17 @@ DIAFILE_DIRS = # generate a warning when it encounters a \startuml command in this case and # will not generate output for the diagram. -PLANTUML_JAR_PATH = +PLANTUML_JAR_PATH = ./plantuml.jar # When using plantuml, the PLANTUML_CFG_FILE tag can be used to specify a # configuration file for plantuml. -PLANTUML_CFG_FILE = +PLANTUML_CFG_FILE = # When using plantuml, the specified paths are searched for files specified by # the !include statement in a plantuml block. -PLANTUML_INCLUDE_PATH = +PLANTUML_INCLUDE_PATH = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes # that will be shown in the graph. If the number of nodes in a graph becomes diff --git a/device-management-client/dmc_connect_api.h b/device-management-client/dmc_connect_api.h index 312564c..c0764c9 100644 --- a/device-management-client/dmc_connect_api.h +++ b/device-management-client/dmc_connect_api.h @@ -109,9 +109,11 @@ lwm2m_interface_t *pdmc_connect_get_interface(void); * \param callback A `registry_callback_t` type of a callback that will be notified on changes in a Resource. * \return `1` in success. */ +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY int pdmc_connect_add_cloud_resource(registry_t *registry, registry_path_t *path, const uint16_t object, const uint16_t object_instance, const uint16_t resource, bool auto_observable, registry_callback_t callback); +#endif /** * \brief Get information on a connected endpoint. @@ -120,6 +122,23 @@ int pdmc_connect_add_cloud_resource(registry_t *registry, registry_path_t *path, */ bool pdmc_connect_endpoint_info(pdmc_endpoint_info_s *endpoint_info); +/** +* \brief Get endpoint name. +* Can be called before connecting, but must only be called after `pdmc_connect_init()`. +* \param endpoint_name Output buffer that on a succesful call will contain the endpoint name as a C string. +* \param size The size of the `endpoint_name` buffer. Any data that doesn't fit will be discarded. +* \return True in success, false in failure. +*/ +bool pdmc_connect_get_endpoint_name(char *endpoint_name, size_t size); + +/** +* \brief Get device id of a connected device. +* \param device_id Output buffer that on a succesful call will contain the device id as a C string. +* \param size The size of the `device_id` buffer. Any data that doesn't fit will be discarded. +* \return True in success, false in failure. +*/ +bool pdmc_connect_get_device_id(char *device_id, size_t size); + /** * \brief Pause Device Management Client's timed functionality and close network connection * to Device Management. After a successful call, you can continue the operation diff --git a/device-management-client/lwm2m_registry_handler.h b/device-management-client/lwm2m_registry_handler.h index d7674f5..2b3429e 100644 --- a/device-management-client/lwm2m_registry_handler.h +++ b/device-management-client/lwm2m_registry_handler.h @@ -17,9 +17,6 @@ #ifndef LWM2M_REGISTRY_HANDLER_H #define LWM2M_REGISTRY_HANDLER_H -#include "lwm2m_registry.h" -#include "lwm2m_endpoint.h" - #include "ns_list.h" #include "ns_types.h" #include "sn_coap_header.h" @@ -90,6 +87,19 @@ void send_execute_response(const registry_path_t *path, */ void response_message_send(endpoint_t *endpoint); +#ifdef MBED_CLOUD_CLIENT_DISABLE_REGISTRY +/** + * \brief Queue a callback to be called. + * + * \param path Pointer to resource path. + * \param received_coap_header Pointer to CoAP data from the CoAP library. + * \param type Event type. + */ +bool send_callback_data(const registry_path_t *path, + const sn_coap_hdr_s *received_coap_header, + const uint8_t type); +#endif + #ifdef __cplusplus } #endif diff --git a/fota/fota.c b/fota/fota.c index 8c4f407..672aa5e 100644 --- a/fota/fota.c +++ b/fota/fota.c @@ -1,4 +1,5 @@ -// Copyright 2018-2019 ARM Ltd. +// ---------------------------------------------------------------------------- +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -19,6 +20,8 @@ #ifdef MBED_CLOUD_CLIENT_FOTA_ENABLE +#define TRACE_GROUP "FOTA" + #include "fota/fota.h" #include "fota/fota_status.h" #include "fota/fota_internal.h" @@ -36,8 +39,6 @@ #include "fota/fota_candidate.h" #include "fota/fota_component.h" #include "fota/fota_component_internal.h" -#include "mbedtls/x509_crt.h" -#include "mbedtls/x509.h" #include #include @@ -45,6 +46,10 @@ #include "mbed_power_mgmt.h" #endif +#if (MBED_CLOUD_CLIENT_FOTA_RESUME_SUPPORT == FOTA_RESUME_SUPPORT_RESUME) && !FOTA_HEADER_HAS_CANDIDATE_READY +#error Full resume feature is not supported for legacy/external images +#endif + #define MAIN_COMP_NUM 0 static fota_context_t *fota_ctx = NULL; @@ -52,9 +57,16 @@ static fota_context_t *fota_ctx = NULL; static int handle_fw_fragment(uint8_t *buf, size_t size, bool last); static void handle_manifest(uint8_t *manifest_buf, size_t manifest_size, bool is_resume); static void on_reboot(void); +static int finalize_update(void); +static void fota_on_install_authorize(bool defer); static bool initialized = false; +fota_context_t *fota_get_context(void) +{ + return fota_ctx; +} + static void free_context_buffers(void) { if (!fota_ctx) { @@ -64,10 +76,6 @@ static void free_context_buffers(void) fota_ctx->fw_info = NULL; free(fota_ctx->page_buf); fota_ctx->page_buf = NULL; - free(fota_ctx->metadata_start_buf); - fota_ctx->metadata_start_buf = NULL; - free(fota_ctx->metadata_buf); - fota_ctx->metadata_buf = NULL; #if !defined(FOTA_DISABLE_DELTA) free(fota_ctx->delta_buf); @@ -120,9 +128,8 @@ static void abort_update__(int ret) fota_source_report_state(FOTA_SOURCE_STATE_PROCESSING_MANIFEST, NULL, NULL); } -#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) - fota_nvm_salt_delete(); -#endif + fota_nvm_fw_encryption_key_delete(); + const fota_component_desc_t *comp_desc; fota_component_get_desc(fota_ctx->comp_id, &comp_desc); fota_platform_abort_update_hook(comp_desc->name); @@ -140,26 +147,33 @@ bool fota_is_active_update(void) return (fota_ctx != NULL); } -fota_state_e fota_is_ready(uint8_t *data, size_t size) +int fota_is_ready(uint8_t *data, size_t size, fota_state_e *fota_state) { size_t manifest_size; uint8_t *manifest = malloc(FOTA_MANIFEST_MAX_SIZE); - FOTA_ASSERT(manifest); + if (!manifest) { + FOTA_TRACE_ERROR("FOTA manifest - allocation failed"); + *fota_state = FOTA_STATE_INVALID; + return FOTA_STATUS_OUT_OF_MEMORY; + } memset(manifest, 0, FOTA_MANIFEST_MAX_SIZE); - int ret = fota_nvm_manifest_get(manifest, FOTA_MANIFEST_MAX_SIZE, &manifest_size); if (ret) { // cannot find saved manifest - ready to start an update - free(manifest); - return FOTA_STATE_IDLE; + *fota_state = FOTA_STATE_IDLE; + goto CLEANUP; } - if ((size == manifest_size) && (0 == memcmp(manifest, data, manifest_size))) { + // manifest always saved with MAX size memcmp should be done on input size + if ((size <= manifest_size) && (0 == memcmp(manifest, data, size))) { // notify FOTA already handles same manifest - free(manifest); - return FOTA_STATE_DOWNLOADING; + *fota_state = FOTA_STATE_DOWNLOADING; + goto CLEANUP; } // fota is busy - different update is active + *fota_state = FOTA_STATE_INVALID; + +CLEANUP: free(manifest); - return FOTA_STATE_INVALID; + return FOTA_STATUS_SUCCESS; } static inline void fota_dev_init(void) @@ -174,24 +188,118 @@ static inline void fota_dev_init(void) FOTA_ASSERT(!ret); #endif -#if defined(MBED_CLOUD_DEV_UPDATE_CERT) && !defined(FOTA_USE_EXTERNAL_CERT) +#if defined(FOTA_USE_UPDATE_X509) && defined(MBED_CLOUD_DEV_UPDATE_CERT) && !defined(FOTA_USE_EXTERNAL_CERT) ret = fota_nvm_update_cert_set(); FOTA_ASSERT(!ret); #endif +#if defined(FOTA_USE_UPDATE_RAW_PUBLIC_KEY) && defined(MBED_CLOUD_DEV_UPDATE_RAW_PUBLIC_KEY) && !defined(FOTA_USE_EXTERNAL_UPDATE_RAW_PUBLIC_KEY) + ret = fota_nvm_set_update_public_key(); + FOTA_ASSERT(!ret); +#endif + (void)ret; // fix unused variable warning in production } -static int curr_fw_get_digest(uint8_t *buf) +#if (FOTA_NUM_COMPONENTS > 1) +int fota_install_verify(const fota_component_desc_t *comp_desc, unsigned int comp_id, uint64_t new_ver) +{ + int ret = FOTA_STATUS_SUCCESS; + if (comp_desc->desc_info.component_post_install_cb) { + // callback to check if installed succeded. + char nvm_semver[FOTA_COMPONENT_MAX_SEMVER_STR_SIZE] = {0}; + ret = fota_component_version_int_to_semver(new_ver, nvm_semver); + if (ret) { + FOTA_TRACE_ERROR("Failed to convert to sem version %d", ret); + return ret; + } + + ret = comp_desc->desc_info.component_post_install_cb(nvm_semver); + if (ret) { + FOTA_TRACE_ERROR("Failed to verify installation %d", ret); + return ret; + } + } + + // Successful finish actions + fota_component_set_curr_version(comp_id, new_ver); + // Not saving version for the MAIN component + fota_nvm_comp_version_set(comp_desc->name, new_ver); + return ret; +} +#endif // FOTA_NUM_COMPONENTS > 1 + +int fota_handle_post_install() { - fota_header_info_t curr_fw_info; - int ret = fota_curr_fw_read_header(&curr_fw_info); + int ret = FOTA_STATUS_SUCCESS; + +#if (FOTA_NUM_COMPONENTS > 1) + uint32_t bd_read_size; + uint32_t bd_prog_size; + unsigned int comp_id; + uint32_t addr; + fota_candidate_ready_header_t comp_header; + const fota_component_desc_t *comp_desc; + fota_header_info_t header; + + ret = fota_bd_init(); if (ret) { - FOTA_TRACE_ERROR("Failed to read current header"); - return ret; + FOTA_TRACE_ERROR("fota_bd_init failed %d.", ret); + goto fail; } - memcpy(buf, curr_fw_info.digest, FOTA_CRYPTO_HASH_SIZE); - return FOTA_STATUS_SUCCESS; + + ret = fota_bd_get_read_size(&bd_read_size); + if (ret) { + FOTA_TRACE_ERROR("fota_bd_get_read_size failed %d.", ret); + goto fail; + } + + ret = fota_bd_get_program_size(&bd_prog_size); + if (ret) { + FOTA_TRACE_ERROR("fota_bd_get_program_size failed %d.", ret); + goto fail; + } + // check what component was updated to call post install callback + // in case all done at candidate_post_install_cb, we can remove salt and report install complete + addr = fota_candidate_get_config()->storage_start_addr; + ret = fota_candidate_read_candidate_ready_header(&addr, bd_read_size, bd_prog_size, &comp_header); + if (ret) { + goto fail; + } + + ret = fota_component_name_to_id(comp_header.comp_name, &comp_id); + if (ret) { + goto fail; + } + + fota_component_get_desc(comp_id, &comp_desc); + ret = fota_candidate_read_header(&addr, bd_read_size, bd_prog_size, &header); + if (ret) { + FOTA_TRACE_ERROR("failed to read candidate header %d.", ret); + goto fail; + } + + FOTA_TRACE_DEBUG("install verify component name %s, version %" PRIu64 " ", comp_header.comp_name, header.version); + ret = fota_install_verify(comp_desc, comp_id, header.version); + +fail: +#endif // FOTA_NUM_COMPONENTS > 1 + +#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 0) + ret = fota_bd_init(); + if (ret) { + FOTA_TRACE_ERROR("fota_bd_init failed %d.", ret); + } else { + ret = fota_candidate_erase(); + if (ret) { + FOTA_TRACE_ERROR("fota_candidate_erase failed %d.", ret); + } + } +#endif + + // in case we failed prevent infinite loop, remove FW key and report failure as post installed failed + fota_nvm_fw_encryption_key_delete(); + return ret; } int fota_init(endpoint_t *in_endpoint) @@ -201,12 +309,9 @@ int fota_init(endpoint_t *in_endpoint) uint8_t *manifest = NULL; size_t manifest_size = 0; fota_source_state_e source_state = FOTA_SOURCE_STATE_IDLE; - fota_component_desc_t main_component_desc = {0}; - -#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) - uint8_t salt[FOTA_ENCRYPT_METADATA_SALT_LEN]; -#endif + fota_component_desc_info_t main_component_desc = {0}; + uint8_t fw_key[FOTA_ENCRYPT_KEY_SIZE]; int ret; bool after_upgrade = false; @@ -244,80 +349,71 @@ int fota_init(endpoint_t *in_endpoint) if (!ret) { source_state = FOTA_SOURCE_STATE_PROCESSING_MANIFEST; } else { -#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) - ret = fota_nvm_salt_get(salt); + ret = fota_nvm_fw_encryption_key_get(fw_key); + memset(fw_key, 0, sizeof(fw_key)); after_upgrade = !ret; - fota_nvm_salt_delete(); -#else - // TODO: check if candidate ready is present (need to take care of read size and bd init sequence) -#endif } free(manifest); - if (after_upgrade) { - FOTA_TRACE_INFO("After upgrade. Cleaning up."); - // TODO: verify the new FW version was actually installed by bootloader - fota_app_on_complete(FOTA_STATUS_SUCCESS); - } - ret = fota_source_init( in_endpoint, vendor_id, sizeof(vendor_id), class_id, sizeof(class_id), -#if FOTA_SOURCE_COMPONENT_BACKWARD_COMPATIBILITY_MODE header_info.digest, sizeof(header_info.digest), header_info.version, -#endif source_state); FOTA_ASSERT(!ret); - fota_component_init(); + fota_component_clean(); // register main component (should be done before platform init hook, which registers all other components). - strcpy(main_component_desc.name, FOTA_COMPONENT_MAIN_COMPONENT_NAME); // "Factory" version here is what we read from main firmware header, as we don't save it to NVM. - fota_component_version_int_to_semver(header_info.version, main_component_desc.factory_version); - main_component_desc.candidate_iterate_cb = NULL; + char factory_version[FOTA_COMPONENT_MAX_SEMVER_STR_SIZE]; + fota_component_version_int_to_semver(header_info.version, factory_version); main_component_desc.need_reboot = true; main_component_desc.support_delta = true; main_component_desc.curr_fw_read = fota_curr_fw_read; - main_component_desc.curr_fw_get_digest = curr_fw_get_digest; - ret = fota_component_add(&main_component_desc); + main_component_desc.curr_fw_get_digest = fota_curr_fw_get_digest; + ret = fota_component_add(&main_component_desc, FOTA_COMPONENT_MAIN_COMPONENT_NAME, factory_version); FOTA_DBG_ASSERT(!ret); #if (MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION >= 3) // Don't show that in legacy case - FOTA_TRACE_INFO("Registered %s component, version %s", main_component_desc.name, main_component_desc.factory_version); + FOTA_TRACE_INFO("Registered %s component, version %s", FOTA_COMPONENT_MAIN_COMPONENT_NAME, factory_version); #endif - fota_component_set_curr_version(MAIN_COMP_NUM, header_info.version); - - ret = fota_source_add_component(MAIN_COMP_NUM, main_component_desc.name, main_component_desc.factory_version); + ret = fota_source_add_component(MAIN_COMP_NUM, FOTA_COMPONENT_MAIN_COMPONENT_NAME, factory_version); FOTA_DBG_ASSERT(!ret); ret = fota_platform_init_hook(after_upgrade); FOTA_ASSERT(!ret); - // Code saving - only relevant if we have additional components other than the main one + if (after_upgrade) { + FOTA_TRACE_DEBUG("After upgrade, issuing post install actions"); + ret = fota_handle_post_install(); + if (ret) { + fota_source_report_update_result(FOTA_STATUS_FW_INSTALLATION_FAILED); + } + } + +// Code saving - only relevant if we have additional components other than the main one #if (FOTA_NUM_COMPONENTS > 1) // Now we should have all components registered, report them all unsigned int num_comps = fota_component_num_components(); for (unsigned int i = 1; i < num_comps; i++) { const fota_component_desc_t *comp_desc; - char nvm_semver[FOTA_COMPONENT_MAX_SEMVER_STR_SIZE] = {0}; + char semver[FOTA_COMPONENT_MAX_SEMVER_STR_SIZE] = {0}; fota_component_version_t version; - const char *semver; fota_component_get_desc(i, &comp_desc); ret = fota_nvm_comp_version_get(comp_desc->name, &version); - if (!ret) { - ret = fota_component_version_int_to_semver(version, nvm_semver); - semver = nvm_semver; - } else { - ret = fota_component_version_semver_to_int(comp_desc->factory_version, &version); - semver = comp_desc->factory_version; + // if not found, take factory version from comp_desc + if (ret != FOTA_STATUS_SUCCESS) { + version = comp_desc->version; } + ret = fota_component_version_int_to_semver(version, semver); + FOTA_DBG_ASSERT(!ret); - FOTA_TRACE_INFO("Registered %s component, version %s", comp_desc->name, semver); + FOTA_TRACE_DEBUG("Registered %s component, version %s", comp_desc->name, semver); ret = fota_source_add_component(i, comp_desc->name, semver); FOTA_DBG_ASSERT(!ret); fota_component_set_curr_version(i, version); @@ -340,6 +436,7 @@ int fota_deinit(void) FOTA_TRACE_DEBUG("fota_deinit"); update_cleanup(); + fota_component_clean(); fota_source_deinit(); fota_random_deinit(); fota_event_handler_deinit(); @@ -348,149 +445,53 @@ int fota_deinit(void) return FOTA_STATUS_SUCCESS; } -#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) - -static int init_encryption(size_t prog_size, size_t fw_size_in_storage) +static int init_encryption(void) { - int ret = FOTA_STATUS_INTERNAL_ERROR; - - fota_encrypt_config_t encrypt_config; - fota_ctx->page_buf_size = MAX(fota_candidate_get_config()->encrypt_block_size, fota_ctx->page_buf_size); - - fota_ctx->metadata_buf_size = MAX(prog_size, fota_align_up(FOTA_ENCRYPT_METADATA_MAX_SIZE, prog_size)); - fota_ctx->metadata_buf = malloc(fota_ctx->metadata_buf_size); - if (!fota_ctx->metadata_buf) { - FOTA_TRACE_DEBUG("FOTA encryption metadata - allocation failed"); - return FOTA_STATUS_OUT_OF_MEMORY; - } + int ret = FOTA_STATUS_NOT_FOUND; - fota_ctx->metadata_start_buf = malloc(FOTA_ENCRYPT_METADATA_START_SIZE); - if (!fota_ctx->metadata_start_buf) { - FOTA_TRACE_DEBUG("FOTA encryption start metadata - allocation failed"); - return FOTA_STATUS_OUT_OF_MEMORY; - } - - FOTA_ASSERT((fota_candidate_get_config()->encrypt_block_size % fota_ctx->page_buf_size) == 0); - - encrypt_config.encrypt_block_size = fota_candidate_get_config()->encrypt_block_size; + uint8_t fw_key[FOTA_ENCRYPT_KEY_SIZE]; - uint8_t fw_enc_key[FOTA_ENCRYPT_KEY_SIZE]; - uint8_t salt[FOTA_ENCRYPT_METADATA_SALT_LEN]; - uint8_t derived_key[FOTA_ENCRYPT_KEY_SIZE]; - - if (fota_gen_random(salt, sizeof(salt))) { - return FOTA_STATUS_INTERNAL_ERROR; +#if (MBED_CLOUD_CLIENT_FOTA_RESUME_SUPPORT == FOTA_RESUME_SUPPORT_RESUME) + if (fota_ctx->resume_state == FOTA_RESUME_STATE_STARTED) { + ret = fota_nvm_fw_encryption_key_get(fw_key); + if (!ret) { + FOTA_TRACE_DEBUG("Reloading saved FOTA key"); + } else { + FOTA_TRACE_DEBUG("FOTA key not found, resetting resume state"); + // Can't continue with resume if FW key can't be reloaded + fota_ctx->resume_state = FOTA_RESUME_STATE_INACTIVE; + } } +#endif - ret = fota_nvm_salt_set(salt); if (ret) { - return ret; - } - - FOTA_TRACE_DEBUG("FOTA encryption salt saved"); + if (fota_gen_random(fw_key, sizeof(fw_key))) { + FOTA_TRACE_ERROR("Unable to generate random FW key. ret %d", ret); + return ret; + } - ret = fota_nvm_fw_encryption_key_get(fw_enc_key); - if (ret == FOTA_STATUS_NOT_FOUND) { - ret = fota_gen_random(fw_enc_key, sizeof(fw_enc_key)); + ret = fota_nvm_fw_encryption_key_set(fw_key); if (ret) { + FOTA_TRACE_ERROR("Unable to set FW key. ret %d", ret); return ret; } - ret = fota_nvm_fw_encryption_key_set(fw_enc_key); - } - if (ret) { - return ret; - } - ret = fota_get_derived_key(fw_enc_key, sizeof(fw_enc_key), salt, sizeof(salt), derived_key); - if (ret) { - return ret; + FOTA_TRACE_DEBUG("New FOTA key saved"); } - FOTA_TRACE_DEBUG("FOTA encryption key generated"); - - ret = fota_encrypt_decrypt_start(&fota_ctx->enc_ctx, &encrypt_config, derived_key, - FOTA_ENCRYPT_KEY_SIZE, true); - if (ret) { - return ret; - } - ret = fota_encryption_metadata_start(fota_ctx->enc_ctx, salt, sizeof(salt), fw_size_in_storage, - fota_ctx->metadata_start_buf, fota_candidate_get_config()->encrypt_block_size, - &fota_ctx->metadata_start_size, &fota_ctx->metadata_tags_size); +#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) + ret = fota_encrypt_decrypt_start(&fota_ctx->enc_ctx, fw_key, sizeof(fw_key)); + memset(fw_key, 0, sizeof(fw_key)); if (ret) { + FOTA_TRACE_ERROR("Unable to start encryption engine. ret %d", ret); return ret; } - FOTA_TRACE_DEBUG("FOTA encryption engine initialized"); - - fota_ctx->fw_offset_in_storage += fota_align_up(fota_ctx->metadata_start_size, prog_size) + - fota_align_up(fota_ctx->metadata_tags_size, prog_size); - - return FOTA_STATUS_SUCCESS; -} - -static int write_initial_metadata(void) -{ - // Write initial metadata - if ((fota_ctx->metadata_start_size) && (fota_ctx->metadata_tags_size)) { - uint32_t metadata_header_size = fota_align_up(fota_ctx->metadata_start_size, fota_bd_get_program_size()); - fota_ctx->metadata_curr_addr = fota_candidate_get_config()->storage_start_addr + fota_ctx->candidate_header_size; - int ret = fota_bd_program(fota_ctx->metadata_start_buf, fota_ctx->metadata_curr_addr, metadata_header_size); - if (ret) { - FOTA_TRACE_ERROR("Metadata write to storage failed"); - return FOTA_STATUS_STORAGE_WRITE_FAILED; - } - fota_ctx->metadata_curr_addr += metadata_header_size; - } - - return FOTA_STATUS_SUCCESS; -} - -static int handle_metadata_fragment(uint8_t *buf, size_t size) -{ - uint8_t *source_buf = buf, *prog_buf; - uint32_t prog_size; - uint32_t chunk; - // Only need to flush if we have something in the page buffer - bool flush = ((size == 0) && (buf == 0)); - - while (size || flush) { - if (fota_ctx->metadata_buf_offset || (size < fota_ctx->metadata_buf_size)) { - chunk = MIN(fota_ctx->metadata_buf_size - fota_ctx->metadata_buf_offset, size); - prog_size = fota_ctx->metadata_buf_offset + chunk; - prog_buf = fota_ctx->metadata_buf; - memcpy(fota_ctx->metadata_buf + fota_ctx->metadata_buf_offset, source_buf, chunk); - if (flush) { - // May have a partial page here, align up to page - prog_size = fota_align_up(prog_size, fota_ctx->metadata_buf_size); - memset(prog_buf + fota_ctx->metadata_buf_offset + chunk, 0, - fota_ctx->metadata_buf_size - fota_ctx->metadata_buf_offset - chunk); - } - fota_ctx->metadata_buf_offset = (fota_ctx->metadata_buf_offset + chunk) % fota_ctx->metadata_buf_size; - } else { - chunk = fota_align_down(size, fota_ctx->metadata_buf_size); - prog_size = chunk; - prog_buf = source_buf; - source_buf += chunk; - } - if (prog_size >= fota_ctx->metadata_buf_size) { - int ret = fota_bd_program(prog_buf, fota_ctx->metadata_curr_addr, prog_size); - if (ret) { - FOTA_TRACE_ERROR("Write to storage failed, address %" PRIu32 ", size %" PRIu32, - fota_ctx->metadata_curr_addr, prog_size); - return FOTA_STATUS_STORAGE_WRITE_FAILED; - } - - fota_ctx->metadata_curr_addr += prog_size; - } - size -= chunk; - flush = false; - } +#endif return FOTA_STATUS_SUCCESS; } -#endif - static int init_header(size_t prog_size) { fota_ctx->fw_header_bd_size = fota_align_up(fota_get_header_size(), prog_size); @@ -502,7 +503,7 @@ static int init_header(size_t prog_size) fota_ctx->candidate_header_size = 0; #endif - fota_ctx->fw_offset_in_storage = fota_ctx->candidate_header_size + fota_ctx->fw_header_bd_size; + fota_ctx->storage_addr += fota_ctx->candidate_header_size + fota_ctx->fw_header_bd_size; return FOTA_STATUS_SUCCESS; } @@ -527,11 +528,6 @@ static void handle_manifest(uint8_t *manifest_buf, size_t manifest_size, bool is { int ret; int manifest_save_ret = FOTA_STATUS_INTERNAL_ERROR; - uint8_t *update_crt_data = NULL; - size_t update_crt_size; - mbedtls_x509_crt crt; - uint32_t prog_size; - uint32_t fw_size_in_storage; const fota_component_desc_t *comp_desc; fota_component_version_t curr_fw_version; uint8_t curr_fw_digest[FOTA_CRYPTO_HASH_SIZE] = {0}; @@ -545,21 +541,23 @@ static void handle_manifest(uint8_t *manifest_buf, size_t manifest_size, bool is fota_ctx = (fota_context_t *)malloc(sizeof(*fota_ctx)); if (!fota_ctx) { ret = FOTA_STATUS_OUT_OF_MEMORY; + FOTA_TRACE_ERROR("Unable to allocate FOTA context."); goto fail; } memset(fota_ctx, 0, sizeof(*fota_ctx)); fota_ctx->fw_info = (manifest_firmware_info_t *) malloc(sizeof(manifest_firmware_info_t)); if (!fota_ctx->fw_info) { + FOTA_TRACE_ERROR("Unable to allocate FW info."); ret = FOTA_STATUS_OUT_OF_MEMORY; goto fail; } - memset(fota_ctx->fw_info, 0, sizeof(manifest_firmware_info_t)); FOTA_TRACE_INFO("Firmware update initiated."); - - if (!is_resume) { + if (is_resume) { + fota_ctx->resume_state = FOTA_RESUME_STATE_STARTED; + } else { manifest_save_ret = fota_nvm_manifest_set(manifest_buf, manifest_size); if (manifest_save_ret) { FOTA_TRACE_ERROR("failed to persist manifest %d", manifest_save_ret); @@ -569,147 +567,63 @@ static void handle_manifest(uint8_t *manifest_buf, size_t manifest_size, bool is // MUST be done ONLY after persisting the manifest } - update_crt_data = (uint8_t *)malloc(FOTA_CERT_MAX_SIZE); - if (!update_crt_data) { - FOTA_TRACE_ERROR("failed to allocate storage for update certificate"); - ret = FOTA_STATUS_OUT_OF_MEMORY; - goto fail; - } - - ret = fota_nvm_get_update_certificate(update_crt_data, FOTA_CERT_MAX_SIZE, &update_crt_size); - if (ret) { - FOTA_TRACE_ERROR("failed to get update certificate %d", ret); - ret = FOTA_STATUS_CERT_NOT_FOUND; - goto fail; - } - - mbedtls_x509_crt_init(&crt); - - ret = mbedtls_x509_crt_parse_der_nocopy(&crt, update_crt_data, update_crt_size); - if (ret) { - FOTA_TRACE_ERROR("failed to parse update certificate %d", ret); - if (ret == MBEDTLS_ERR_X509_ALLOC_FAILED) { - ret = FOTA_STATUS_OUT_OF_MEMORY; - } else { - ret = FOTA_STATUS_INVALID_CERTIFICATE; - } - mbedtls_x509_crt_free(&crt); - free(update_crt_data); - goto fail; - } - FOTA_TRACE_DEBUG("Update certificate loaded successfully"); ret = fota_manifest_parse( manifest_buf, manifest_size, - fota_ctx->fw_info, - &crt); + fota_ctx->fw_info); - mbedtls_x509_crt_free(&crt); - free(update_crt_data); + // Reset manifest data, no need to keep it anymore + memset(manifest_buf, 0, manifest_size); if (ret) { FOTA_TRACE_DEBUG("Pelion FOTA manifest rejected %d", ret); goto fail; } - FOTA_TRACE_DEBUG("Pelion FOTA manifest is valid"); - // Reset manifest data, no need to keep it anymore - memset(manifest_buf, 0, manifest_size); + FOTA_TRACE_DEBUG("Pelion FOTA manifest is valid"); - // TODO: Extract component id from name in manifest. Currently fix it to main component. +#if (FOTA_NUM_COMPONENTS == 1) + //main component in case only one component. strcpy(fota_ctx->fw_info->component_name, FOTA_COMPONENT_MAIN_COMPONENT_NAME); +#endif ret = fota_component_name_to_id(fota_ctx->fw_info->component_name, &fota_ctx->comp_id); if (ret) { + FOTA_TRACE_ERROR("Manifest addresses unknown component %s", fota_ctx->fw_info->component_name); ret = FOTA_STATUS_MANIFEST_UNKNOWN_COMPONENT; goto fail; } fota_component_get_desc(fota_ctx->comp_id, &comp_desc); - ret = fota_platform_start_update_hook(comp_desc->name); - if (ret) { - FOTA_TRACE_ERROR("Platform start update hook failed"); - goto fail; - } - - if (comp_desc->curr_fw_get_digest) { - comp_desc->curr_fw_get_digest(curr_fw_digest); + if (comp_desc->desc_info.curr_fw_get_digest) { + comp_desc->desc_info.curr_fw_get_digest(curr_fw_digest); } fota_component_get_curr_version(fota_ctx->comp_id, &curr_fw_version); FOTA_FI_SAFE_COND(fota_ctx->fw_info->version > curr_fw_version, FOTA_STATUS_MANIFEST_VERSION_REJECTED, "Manifest payload-version rejected - too old"); - prog_size = fota_bd_get_program_size(); - FOTA_ASSERT(prog_size); - - ret = init_header(prog_size); - if (ret) { - goto fail; - } - - // Calculate space for FW image + header - fw_size_in_storage = fota_align_up(fota_ctx->fw_info->installed_size, prog_size); - - fota_ctx->page_buf_size = prog_size; - -#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) - init_encryption(prog_size, fw_size_in_storage); -#endif - - ret = fota_hash_start(&fota_ctx->curr_fw_hash_ctx); - if (ret) { - goto fail; - } + FOTA_TRACE_DEBUG("get manifest : curr version %" PRIu64 ", new version %" PRIu64 " ", curr_fw_version, fota_ctx->fw_info->version); if (fota_ctx->fw_info->payload_format == FOTA_MANIFEST_PAYLOAD_FORMAT_DELTA) { - if (!comp_desc->support_delta) { +#if defined(FOTA_DISABLE_DELTA) + ret = FOTA_STATUS_MANIFEST_PAYLOAD_UNSUPPORTED; + goto fail; +#else // defined(FOTA_DISABLE_DELTA) + if (!comp_desc->desc_info.support_delta) { ret = FOTA_STATUS_MANIFEST_PAYLOAD_UNSUPPORTED; + FOTA_TRACE_ERROR("Delta payload unsupported."); goto fail; } FOTA_FI_SAFE_MEMCMP(curr_fw_digest, fota_ctx->fw_info->precursor_digest, FOTA_CRYPTO_HASH_SIZE, FOTA_STATUS_MANIFEST_PRECURSOR_MISMATCH, "Precursor digest mismatch"); - -#if !defined(FOTA_DISABLE_DELTA) - fota_ctx->delta_buf = malloc(MBED_CLOUD_CLIENT_FOTA_DELTA_BLOCK_SIZE); - if (!fota_ctx->delta_buf) { - FOTA_TRACE_DEBUG("FOTA delta buffer - allocation failed"); - ret = FOTA_STATUS_OUT_OF_MEMORY; - goto fail; - } - - ret = fota_delta_start(&fota_ctx->delta_ctx, comp_desc->curr_fw_read); - if (ret) { - goto fail; - } - FOTA_TRACE_DEBUG("FOTA delta engine initialized"); -#else - ret = FOTA_STATUS_MANIFEST_PAYLOAD_UNSUPPORTED; - goto fail; -#endif +#endif // defined(FOTA_DISABLE_DELTA) } else { // If we have the current fw digest, place it in precursor for the case the installer needs it memcpy(fota_ctx->fw_info->precursor_digest, curr_fw_digest, FOTA_CRYPTO_HASH_SIZE); } - ret = fota_bd_init(); - if (ret) { - FOTA_TRACE_ERROR("Unable to initialize storage"); - ret = FOTA_STATUS_INSUFFICIENT_STORAGE; - goto fail; - } - FOTA_TRACE_DEBUG("FOTA BlockDevice initialized"); - - fota_ctx->storage_end_addr = fota_candidate_get_config()->storage_start_addr + fota_ctx->fw_offset_in_storage + fw_size_in_storage; - fota_ctx->storage_end_addr = fota_align_up(fota_ctx->storage_end_addr, fota_bd_get_erase_size(fota_ctx->storage_end_addr)); - - if ((fota_ctx->storage_end_addr - fota_candidate_get_config()->storage_start_addr) > fota_candidate_get_config()->storage_size) { - FOTA_TRACE_ERROR("Insufficient storage for firmware"); - ret = FOTA_STATUS_INSUFFICIENT_STORAGE; - goto fail; - } - ret = fota_gen_random((uint8_t *) &fota_ctx->auth_token, sizeof(fota_ctx->auth_token)); if (ret) { ret = FOTA_STATUS_INTERNAL_ERROR; @@ -764,6 +678,13 @@ void fota_on_defer(uint32_t token, int32_t status) FOTA_ASSERT(fota_ctx->auth_token == token); fota_ctx->auth_token = 0; + + if (fota_ctx->state == FOTA_STATE_AWAIT_INSTALL_AUTHORIZATION) { + FOTA_TRACE_INFO("Installation deferred by application."); + fota_on_install_authorize(true); + return; + } + abort_update(FOTA_STATUS_UPDATE_DEFERRED, "Update deferred by application"); } @@ -784,35 +705,65 @@ static void on_reboot(void) #endif } +#if FOTA_HEADER_HAS_CANDIDATE_READY static int write_candidate_ready(const char *comp_name) { + int ret; uint8_t *header_buf = malloc(fota_ctx->candidate_header_size); - + if (!header_buf) { + FOTA_TRACE_ERROR("FOTA header_buf - allocation failed"); + return FOTA_STATUS_OUT_OF_MEMORY; + } memset(header_buf, 0, fota_ctx->candidate_header_size); fota_candidate_ready_header_t *header = (fota_candidate_ready_header_t *) header_buf; - header->magic = FOTA_CANDIDATE_READY_MAGIC; - strcpy(header->comp_name, comp_name); - - int ret = fota_bd_program(header_buf, fota_candidate_get_config()->storage_start_addr, fota_ctx->candidate_header_size); - if (ret) { +#if MBED_CLOUD_CLIENT_FOTA_RESUME_SUPPORT == FOTA_RESUME_SUPPORT_RESUME + if (fota_ctx->resume_state == FOTA_RESUME_STATE_ONGOING) { + ret = fota_bd_read(header_buf, fota_candidate_get_config()->storage_start_addr, fota_ctx->candidate_header_size); + if (ret) { + ret = FOTA_STATUS_STORAGE_READ_FAILED; + goto finish; + } + if (header->footer == FOTA_CANDIDATE_READY_MAGIC) { + // Already programmed - no need to do anything. Return to normal state. + fota_ctx->resume_state = FOTA_RESUME_STATE_INACTIVE; + goto finish; + } + } +#endif + + header->magic = FOTA_CANDIDATE_READY_MAGIC; + header->footer = FOTA_CANDIDATE_READY_MAGIC; + strcpy(header->comp_name, comp_name); + + ret = fota_bd_program(header_buf, fota_candidate_get_config()->storage_start_addr, fota_ctx->candidate_header_size); + if (ret) { + FOTA_TRACE_ERROR("candidate_ready write to storage failed %d", ret); ret = FOTA_STATUS_STORAGE_WRITE_FAILED; - FOTA_TRACE_ERROR("candidate_ready write to storage failed"); + // Not really needed, just prevent warning if support resume is not configured + goto finish; } +finish: + free(header_buf); return ret; } +#endif static void install_component() { unsigned int comp_id = fota_ctx->comp_id; const fota_component_desc_t *comp_desc; + fota_nvm_manifest_delete(); + + // reading the version before free fota_ctx + // free fota_ctx before installation, saving RAM #if (FOTA_NUM_COMPONENTS > 1) fota_component_version_t new_ver; new_ver = fota_ctx->fw_info->version; -#endif +#endif // FOTA_NUM_COMPONENTS > 1 // At this point we don't need our fota context buffers any more. // Free them before installer starts working (to flatten memory allocation curve). @@ -827,23 +778,22 @@ static void install_component() if (comp_id != MAIN_COMP_NUM) { // Run the installer using the candidate iterate service int ret = fota_candidate_iterate_image(true, (bool) MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT, - comp_desc->name, comp_desc->candidate_iterate_cb); + comp_desc->name, comp_desc->desc_info.install_alignment, + comp_desc->desc_info.candidate_iterate_cb); if (ret) { abort_update(ret, "Failed on component update"); return; } - // Successful finish actions - fota_component_set_curr_version(comp_id, new_ver); - fota_nvm_comp_version_set(comp_desc->name, new_ver); -#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) - fota_nvm_salt_delete(); -#endif - fota_app_on_complete(FOTA_STATUS_SUCCESS); // notify application + if (!comp_desc->desc_info.need_reboot) { + ret = fota_install_verify(comp_desc, comp_id, new_ver); + fota_nvm_fw_encryption_key_delete(); + fota_app_on_complete(ret); //notify application on after install, no reset + } } #endif // FOTA_NUM_COMPONENTS > 1 - if (comp_desc->need_reboot) { + if (comp_desc->desc_info.need_reboot) { fota_source_report_state(FOTA_SOURCE_STATE_REBOOTING, on_reboot, on_reboot); return; } @@ -858,60 +808,46 @@ static int prepare_and_program_header() { int ret; fota_header_info_t header_info = { 0 }; - - uint8_t *header_buf = (uint8_t *) malloc(fota_ctx->fw_header_bd_size); - -#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) - uint32_t metadata_buf_size = 0; - uint8_t *src_buf = header_buf; - uint8_t *prog_buf = header_buf; -#endif size_t header_buf_actual_size = 0; - + uint8_t *header_buf = (uint8_t *) malloc(fota_ctx->fw_header_bd_size); if (!header_buf) { ret = FOTA_STATUS_OUT_OF_MEMORY; - FOTA_TRACE_DEBUG("FOTA scratch buffer - allocation failed"); + FOTA_TRACE_ERROR("FOTA scratch buffer - allocation failed"); goto fail; } + memset(&header_info, 0, sizeof(header_info)); fota_set_header_info_magic(&header_info); header_info.fw_size = fota_ctx->fw_info->installed_size; header_info.version = fota_ctx->fw_info->version; memcpy(header_info.digest, fota_ctx->fw_info->installed_digest, FOTA_CRYPTO_HASH_SIZE); memcpy(header_info.precursor, fota_ctx->fw_info->precursor_digest, FOTA_CRYPTO_HASH_SIZE); +#if defined(MBED_CLOUD_CLIENT_FOTA_SIGNED_IMAGE_SUPPORT) + memcpy(header_info.signature, fota_ctx->fw_info->installed_signature, FOTA_IMAGE_RAW_SIGNATURE_SIZE); +#endif // defined(MBED_CLOUD_CLIENT_FOTA_SIGNED_IMAGE_SUPPORT) - ret = fota_serialize_header(&header_info, header_buf, fota_ctx->fw_header_bd_size, &header_buf_actual_size); - if (ret) { - FOTA_TRACE_ERROR("serialize header failed"); - goto fail; - } - - FOTA_DBG_ASSERT(fota_ctx->fw_header_bd_size >= header_buf_actual_size); + header_info.block_size = MBED_CLOUD_CLIENT_FOTA_CANDIDATE_BLOCK_SIZE; #if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) + header_info.flags |= FOTA_HEADER_ENCRYPTED_FLAG; +#endif - ret = fota_encrypt_data(fota_ctx->enc_ctx, src_buf, header_buf_actual_size, prog_buf, - fota_ctx->metadata_start_buf, FOTA_ENCRYPT_METADATA_MAX_SIZE, &metadata_buf_size); - if (ret) { - FOTA_TRACE_ERROR("FW Header encryption failed"); - goto fail; - } +#if MBED_CLOUD_CLIENT_FOTA_RESUME_SUPPORT == FOTA_RESUME_SUPPORT_RESUME + header_info.flags |= FOTA_HEADER_SUPPORT_RESUME_FLAG; +#endif - ret = handle_metadata_fragment(fota_ctx->metadata_start_buf, metadata_buf_size); + ret = fota_serialize_header(&header_info, header_buf, fota_ctx->fw_header_bd_size, &header_buf_actual_size); if (ret) { - ret = FOTA_STATUS_STORAGE_WRITE_FAILED; - FOTA_TRACE_ERROR("Metadata write to storage failed"); + FOTA_TRACE_ERROR("serialize header failed"); goto fail; } - free(fota_ctx->metadata_start_buf); - fota_ctx->metadata_start_buf = NULL; -#endif + FOTA_DBG_ASSERT(fota_ctx->fw_header_bd_size >= header_buf_actual_size); ret = fota_bd_program(header_buf, fota_ctx->fw_header_offset, fota_ctx->fw_header_bd_size); if (ret) { + FOTA_TRACE_ERROR("header buf write to storage failed %d", ret); ret = FOTA_STATUS_STORAGE_WRITE_FAILED; - FOTA_TRACE_ERROR("header buf write to storage failed"); } fail: @@ -919,84 +855,363 @@ static int prepare_and_program_header() return ret; } -void fota_on_authorize(uint32_t token, int32_t status) +#if MBED_CLOUD_CLIENT_FOTA_RESUME_SUPPORT == FOTA_RESUME_SUPPORT_RESUME + +// Check whether a range is blank - should only be used by analyze_resume_state function +static int check_if_blank(uint32_t addr, uint32_t size, uint8_t erase_val, uint32_t *blank_start_offset) { - int ret; - (void)status; //unused warning + FOTA_DBG_ASSERT(fota_ctx->page_buf); + FOTA_DBG_ASSERT(size <= fota_ctx->page_buf_size); + FOTA_DBG_ASSERT(fota_ctx->resume_state != FOTA_RESUME_STATE_INACTIVE); - FOTA_ASSERT(fota_ctx); + int ret = fota_bd_read(fota_ctx->page_buf, addr, size); + if (ret) { + return FOTA_STATUS_STORAGE_READ_FAILED; + } - FOTA_ASSERT(fota_ctx->auth_token == token); - FOTA_ASSERT( - (fota_ctx->state == FOTA_STATE_AWAIT_DOWNLOAD_AUTHORIZATION) || - (fota_ctx->state == FOTA_STATE_AWAIT_INSTALL_AUTHORIZATION) - ) - fota_ctx->auth_token = 0; + for (*blank_start_offset = size; *blank_start_offset > 0; --(*blank_start_offset)) { + if (fota_ctx->page_buf[*blank_start_offset - 1] != erase_val) { + break; + } + } - if (fota_ctx->state == FOTA_STATE_AWAIT_INSTALL_AUTHORIZATION) { - const fota_component_desc_t *comp_desc; + return ret; +} - FOTA_TRACE_INFO("Install authorization granted."); +static int analyze_resume_state(fota_state_e *next_fota_state, uint32_t storage_available) +{ + int ret = FOTA_STATUS_SUCCESS; + int int_erase_val = 0; + uint8_t erase_val; + uint32_t blank_offs; + uint32_t num_blocks_available, num_blocks_left; + uint32_t save_storage_addr = fota_ctx->storage_addr; + uint8_t fw_key[FOTA_ENCRYPT_KEY_SIZE]; + +#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT != 1) + fota_candidate_block_checksum_t checksum = 0; +#endif - free(fota_ctx->page_buf); - fota_ctx->page_buf = NULL; + if (fota_ctx->resume_state == FOTA_RESUME_STATE_INACTIVE) { + return FOTA_STATUS_SUCCESS; + } - fota_component_get_desc(fota_ctx->comp_id, &comp_desc); + // Resume functionality available for full update only + if (fota_ctx->fw_info->payload_format == FOTA_MANIFEST_PAYLOAD_FORMAT_DELTA) { + FOTA_TRACE_DEBUG("Delta update resume is not supported"); + goto no_resume; + } -#if FOTA_HEADER_HAS_CANDIDATE_READY - ret = write_candidate_ready(comp_desc->name); + fota_ctx->page_buf = malloc(fota_ctx->page_buf_size); + if (!fota_ctx->page_buf) { + FOTA_TRACE_ERROR("Not enough memory for page_buf"); + ret = FOTA_STATUS_OUT_OF_MEMORY; + goto no_resume; + } + fota_ctx->effective_page_buf = fota_ctx->page_buf + fota_ctx->page_buf_size - fota_ctx->effective_page_buf_size; + + ret = fota_bd_get_erase_value(&int_erase_val); + if (ret || (int_erase_val < 0)) { + ret = FOTA_STATUS_INTERNAL_ERROR; + goto no_resume; + } + erase_val = (uint8_t) int_erase_val; + + // Now start analyzing candidate storage to figure resume state out + + // Note for upcoming logic in candidate ready header and further cases: + // After checking if blank, we should read the buffer to page_buf now in order to continue with data analysis. + // However, check_if_blank function already does that, so need to read again. + + ret = check_if_blank(fota_candidate_get_config()->storage_start_addr, fota_ctx->candidate_header_size, + erase_val, &blank_offs); + if (ret) { + goto no_resume; + } else if (blank_offs) { + fota_candidate_ready_header_t *header = (fota_candidate_ready_header_t *) fota_ctx->page_buf; + + if ((header->magic != FOTA_CANDIDATE_READY_MAGIC) || (header->footer != FOTA_CANDIDATE_READY_MAGIC)) { + // candidate header corrupt - no point resuming + FOTA_TRACE_DEBUG("Candidate header corrupt"); + goto no_resume; + } + + // Candidate header fully programmed - jump to install authorization + FOTA_TRACE_DEBUG("Candidate header found. Resuming FOTA from install stage."); + *next_fota_state = FOTA_STATE_AWAIT_INSTALL_AUTHORIZATION; + // Mark resume state as ongoing, in order for later stage to know we can + // move straight to download finish. + fota_ctx->resume_state = FOTA_RESUME_STATE_ONGOING; + goto finish; + } + + // If header is blank or not fully written then no point resuming (as it's written on an early stage anyway) + ret = check_if_blank(fota_ctx->fw_header_offset, fota_ctx->fw_header_bd_size, + erase_val, &blank_offs); + if (ret || (blank_offs < fota_ctx->fw_header_bd_size)) { + FOTA_TRACE_DEBUG("Header not programmed"); + goto no_resume; + } + + // Now traverse candidate data + + ret = fota_nvm_fw_encryption_key_get(fw_key); + if (ret) { + FOTA_TRACE_DEBUG("Encryption key not found"); + goto no_resume; + } + + num_blocks_available = storage_available / fota_ctx->page_buf_size; + num_blocks_left = fota_align_up(fota_ctx->fw_info->payload_size, fota_ctx->effective_page_buf_size) / + fota_ctx->effective_page_buf_size; + + while (num_blocks_left) { + + if (num_blocks_left > num_blocks_available) { + FOTA_TRACE_DEBUG("Not enough erased space left for resuming"); + goto no_resume; + } + + uint32_t chunk = MIN(fota_ctx->fw_info->payload_size - fota_ctx->payload_offset, fota_ctx->effective_page_buf_size); + + ret = check_if_blank(fota_ctx->storage_addr, fota_ctx->page_buf_size, erase_val, &blank_offs); if (ret) { - FOTA_TRACE_ERROR("FOTA write_candidate_ready - failed"); - goto fail; + goto no_resume; + } + + if (!blank_offs) { + // If block is blank, this means we can converge to the regular downloading state. + fota_ctx->resume_state = FOTA_RESUME_STATE_ONGOING; + *next_fota_state = FOTA_STATE_DOWNLOADING; + FOTA_TRACE_DEBUG("Resuming FOTA from download stage"); + goto finish; + } + +#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) + // decrypt data with tag (at the beginning of page_buf) + ret = fota_decrypt_data(fota_ctx->enc_ctx, fota_ctx->effective_page_buf, chunk, fota_ctx->effective_page_buf, + fota_ctx->page_buf); + if (ret) { + // Decryption failure - Skip the block + FOTA_TRACE_DEBUG("Bad encrypted block skipped"); + goto next_block; } + #else - ret = prepare_and_program_header(); + checksum = 0; + for (uint32_t i = 0; i < chunk; i++) { + checksum += fota_ctx->effective_page_buf[i]; + } + if (checksum != *(fota_candidate_block_checksum_t *) fota_ctx->page_buf) { + // Bad checksum - Skip the block + FOTA_TRACE_DEBUG("Bad checksum - block skipped"); + goto next_block; + } +#endif + + // Block verified as OK - update num blocks left, hash and IV (if encrypted) + ret = fota_hash_update(fota_ctx->curr_fw_hash_ctx, fota_ctx->effective_page_buf, chunk); if (ret) { - FOTA_TRACE_ERROR("prepare_and_program_header - failed"); - goto fail; + goto no_resume; } + num_blocks_left--; + fota_ctx->payload_offset += chunk; + fota_ctx->fw_bytes_written += chunk; + +next_block: + num_blocks_available--; + fota_ctx->storage_addr += fota_ctx->page_buf_size; + } + + // Got here means that the whole firmware has been written, but candidate ready header is blank. + // This means we can converge to the regular install authorization flow. + *next_fota_state = FOTA_STATE_AWAIT_INSTALL_AUTHORIZATION; + fota_ctx->resume_state = FOTA_RESUME_STATE_INACTIVE; + FOTA_TRACE_DEBUG("Resuming FOTA from install stage"); + goto finish; + +no_resume: + FOTA_TRACE_DEBUG("Full resume aborted, restarting FOTA"); + fota_ctx->resume_state = FOTA_RESUME_STATE_INACTIVE; + fota_ctx->storage_addr = save_storage_addr; + fota_ctx->fw_bytes_written = 0; + fota_ctx->payload_offset = 0; + fota_hash_finish(&fota_ctx->curr_fw_hash_ctx); + fota_hash_start(&fota_ctx->curr_fw_hash_ctx); +#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) + fota_encryption_stream_reset(fota_ctx->enc_ctx); #endif - fota_nvm_manifest_delete(); - fota_source_report_state(FOTA_SOURCE_STATE_UPDATING, install_component, on_state_set_failure); - return; +finish: + free(fota_ctx->page_buf); + fota_ctx->page_buf = NULL; + return ret; +} + +#endif // MBED_CLOUD_CLIENT_FOTA_RESUME_SUPPORT == FOTA_RESUME_SUPPORT_RESUME + +static void fota_on_download_authorize() +{ + int ret; + uint32_t prog_size; + uint32_t storage_needed, storage_available; + uint32_t storage_start_addr, storage_end_addr; + uint32_t erase_size; + const fota_component_desc_t *comp_desc; +#if MBED_CLOUD_CLIENT_FOTA_RESUME_SUPPORT == FOTA_RESUME_SUPPORT_RESUME + fota_state_e next_fota_state = FOTA_STATE_DOWNLOADING; +#endif + + fota_component_get_desc(fota_ctx->comp_id, &comp_desc); + + ret = fota_platform_start_update_hook(comp_desc->name); + if (ret) { + FOTA_TRACE_ERROR("Platform start update hook failed %d", ret); + goto fail; } - FOTA_TRACE_INFO("Download authorization granted."); + ret = fota_bd_init(); + if (ret) { + FOTA_TRACE_ERROR("Unable to initialize storage %d", ret); + ret = FOTA_STATUS_NOT_INITIALIZED; + goto fail; + } + FOTA_TRACE_DEBUG("FOTA BlockDevice initialized"); - // Erase storage - FOTA_TRACE_DEBUG("Erasing storage at 0x%lx, size %ld", - fota_candidate_get_config()->storage_start_addr, fota_ctx->storage_end_addr - fota_candidate_get_config()->storage_start_addr); - ret = fota_bd_erase(fota_candidate_get_config()->storage_start_addr, - fota_ctx->storage_end_addr - fota_candidate_get_config()->storage_start_addr); + ret = fota_bd_get_program_size(&prog_size); + if (ret) { + FOTA_TRACE_ERROR("Get program size failed. ret %d", ret); + goto fail; + } + + fota_ctx->storage_addr = fota_candidate_get_config()->storage_start_addr; + ret = init_header(prog_size); + if (ret) { + goto fail; + } + + fota_ctx->page_buf_size = fota_align_up(MBED_CLOUD_CLIENT_FOTA_CANDIDATE_BLOCK_SIZE, prog_size); + + ret = init_encryption(); if (ret) { - FOTA_TRACE_ERROR("Erase storage failed"); - ret = FOTA_STATUS_STORAGE_WRITE_FAILED; goto fail; } + fota_ctx->effective_page_buf_size = fota_ctx->page_buf_size; + #if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) - ret = write_initial_metadata(); + fota_ctx->effective_page_buf_size -= FOTA_ENCRYPT_TAG_SIZE; +#elif (MBED_CLOUD_CLIENT_FOTA_RESUME_SUPPORT == FOTA_RESUME_SUPPORT_RESUME) + // Reduce checksum size + fota_ctx->effective_page_buf_size -= sizeof(fota_candidate_block_checksum_t); #endif - fota_ctx->fw_header_offset = fota_candidate_get_config()->storage_start_addr + fota_ctx->fw_offset_in_storage - fota_ctx->fw_header_bd_size; + ret = fota_hash_start(&fota_ctx->curr_fw_hash_ctx); + if (ret) { + goto fail; + } - // In non legacy headers we can and should program the FW header already here, as the candidate ready header - // will be programmed at install phase, telling that the candidate is ready. -#if FOTA_HEADER_HAS_CANDIDATE_READY - ret = prepare_and_program_header(); + storage_start_addr = fota_candidate_get_config()->storage_start_addr; + storage_end_addr = storage_start_addr + fota_candidate_get_config()->storage_size; + ret = fota_bd_get_erase_size(storage_end_addr - 1, &erase_size); if (ret) { + FOTA_TRACE_ERROR("Get erase size failed. ret %d", ret); goto fail; } + + // Check for storage size misconfiguration + FOTA_ASSERT(storage_end_addr == fota_align_up(storage_end_addr, erase_size)); + storage_available = storage_end_addr - storage_start_addr; + + // Calculate needed space for FW data in storage: + // This will align the non-encrypted image up to page buf size and recalculate the storage space + // needed for interleaved data and tags in the encrypted case. + storage_needed = fota_ctx->storage_addr - storage_start_addr + + fota_align_up(fota_ctx->fw_info->installed_size, fota_ctx->effective_page_buf_size) / + fota_ctx->effective_page_buf_size * fota_ctx->page_buf_size; + + if (storage_needed > storage_available) { + FOTA_TRACE_ERROR("Insufficient storage for firmware"); + ret = FOTA_STATUS_INSUFFICIENT_STORAGE; + goto fail; + } + + fota_ctx->fw_header_offset = fota_ctx->storage_addr - fota_ctx->fw_header_bd_size; + +#if MBED_CLOUD_CLIENT_FOTA_RESUME_SUPPORT == FOTA_RESUME_SUPPORT_RESUME + ret = analyze_resume_state(&next_fota_state, storage_available); + if (!ret && next_fota_state == FOTA_STATE_AWAIT_INSTALL_AUTHORIZATION) { + finalize_update(); + return; + } +#else + fota_ctx->resume_state = FOTA_RESUME_STATE_INACTIVE; #endif + // Erase storage (if we're resuming, this has already been done) + if (fota_ctx->resume_state == FOTA_RESUME_STATE_INACTIVE) { + uint32_t total_erase_size; + + // In case we support resume, erase all available storage, covering bad blocks on the way. + // Otherwise, just erase needed storage. +#if MBED_CLOUD_CLIENT_FOTA_RESUME_SUPPORT == FOTA_RESUME_SUPPORT_RESUME + total_erase_size = storage_available; +#else + ret = fota_bd_get_erase_size(storage_start_addr + storage_needed - 1, &erase_size); + if (ret) { + FOTA_TRACE_ERROR("Get erase size failed %d", ret); + goto fail; + } + total_erase_size = fota_align_up(storage_needed, erase_size); +#endif + FOTA_TRACE_DEBUG("Erasing storage at 0x%lx, size %ld", storage_start_addr, total_erase_size); + ret = fota_bd_erase(storage_start_addr, total_erase_size); + if (ret) { + FOTA_TRACE_ERROR("Erase storage failed %d", ret); + ret = FOTA_STATUS_STORAGE_WRITE_FAILED; + goto fail; + } + + // In non legacy headers we can and should program the FW header already here, as the candidate ready header + // will be programmed at install phase, telling that the candidate is ready. +#if FOTA_HEADER_HAS_CANDIDATE_READY + ret = prepare_and_program_header(); + if (ret) { + goto fail; + } +#endif + } + + // At this point, we have converged to regular state, even if we were resuming + fota_ctx->resume_state = FOTA_RESUME_STATE_INACTIVE; + fota_ctx->page_buf = malloc(fota_ctx->page_buf_size); if (!fota_ctx->page_buf) { ret = FOTA_STATUS_OUT_OF_MEMORY; - FOTA_TRACE_DEBUG("FOTA scratch buffer - allocation failed"); + FOTA_TRACE_ERROR("FOTA scratch buffer - allocation failed"); goto fail; } + fota_ctx->effective_page_buf = fota_ctx->page_buf + fota_ctx->page_buf_size - fota_ctx->effective_page_buf_size; + +#if !defined(FOTA_DISABLE_DELTA) + if (fota_ctx->fw_info->payload_format == FOTA_MANIFEST_PAYLOAD_FORMAT_DELTA) { + fota_ctx->delta_buf = malloc(MBED_CLOUD_CLIENT_FOTA_DELTA_BLOCK_SIZE); + if (!fota_ctx->delta_buf) { + FOTA_TRACE_ERROR("FOTA delta buffer - allocation failed"); + ret = FOTA_STATUS_OUT_OF_MEMORY; + goto fail; + } + + ret = fota_delta_start(&fota_ctx->delta_ctx, comp_desc->desc_info.curr_fw_read); + if (ret) { + goto fail; + } + FOTA_TRACE_DEBUG("FOTA delta engine initialized"); + } +#endif // defined(FOTA_DISABLE_DELTA) + + fota_ctx->state = FOTA_STATE_DOWNLOADING; fota_source_report_state(FOTA_SOURCE_STATE_DOWNLOADING, NULL, NULL); ret = fota_source_firmware_request_fragment(fota_ctx->fw_info->uri, fota_ctx->payload_offset); @@ -1005,52 +1220,140 @@ void fota_on_authorize(uint32_t token, int32_t status) } return; + fail: + FOTA_TRACE_DEBUG("Failed on download event. ret code %d", ret); + abort_update(ret, "Failed on download authorization event"); +} + +static void fota_on_install_authorize(bool defer) +{ + int ret; + const fota_component_desc_t *comp_desc; + + fota_component_get_desc(fota_ctx->comp_id, &comp_desc); + free(fota_ctx->page_buf); fota_ctx->page_buf = NULL; - FOTA_TRACE_DEBUG("Failed on authorization event. ret code %d", ret); - abort_update(ret, "Failed on authorization event"); + +#if FOTA_HEADER_HAS_CANDIDATE_READY + ret = write_candidate_ready(comp_desc->name); + if (ret) { + FOTA_TRACE_ERROR("FOTA write_candidate_ready - failed %d", ret); + goto fail; + } +#else + ret = prepare_and_program_header(); + if (ret) { + FOTA_TRACE_ERROR("prepare_and_program_header - failed %d", ret); + goto fail; + } +#endif + + // Install defer means that we skip the installation for now + if (defer) { + if (fota_ctx->comp_id == MAIN_COMP_NUM) { + // Main component is a special case - bootloader will install the FW upon next reset, + // so no need to keep the manifest. + fota_nvm_manifest_delete(); + } else { + // All other components will use the resume flow for that, so manifest should be kept. +#if MBED_CLOUD_CLIENT_FOTA_RESUME_SUPPORT != FOTA_RESUME_SUPPORT_RESUME + abort_update(FOTA_STATUS_INSTALL_DEFER_UNSUPPORTED, + "Component install defer requires resume support"); + return; +#endif + } + update_cleanup(); + return; + } + + fota_source_report_state(FOTA_SOURCE_STATE_UPDATING, install_component, on_state_set_failure); + return; + +fail: + FOTA_TRACE_DEBUG("Failed on install authorization event. ret code %d", ret); + abort_update(ret, "Failed on install authorization event"); +} + +void fota_on_authorize(uint32_t token, int32_t status) +{ + (void)status; //unused warning + + FOTA_ASSERT(fota_ctx); + + FOTA_ASSERT(fota_ctx->auth_token == token); + FOTA_ASSERT( + (fota_ctx->state == FOTA_STATE_AWAIT_DOWNLOAD_AUTHORIZATION) || + (fota_ctx->state == FOTA_STATE_AWAIT_INSTALL_AUTHORIZATION) + ) + fota_ctx->auth_token = 0; + + if (fota_ctx->state == FOTA_STATE_AWAIT_INSTALL_AUTHORIZATION) { + FOTA_TRACE_INFO("Install authorization granted."); + fota_on_install_authorize(false); + return; + } + + FOTA_TRACE_INFO("Download authorization granted."); + fota_on_download_authorize(); } static int program_to_storage(uint8_t *buf, uint32_t addr, uint32_t size) { + uint32_t data_size = size; uint32_t prog_size = size; uint8_t *src_buf = buf; uint8_t *prog_buf = buf; int ret; -#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) - uint32_t metadata_actual_size; - uint8_t metadata_buf[FOTA_ENCRYPT_METADATA_MAX_SIZE]; - prog_size = MIN(fota_candidate_get_config()->encrypt_block_size, size); -#endif + if (fota_ctx->effective_page_buf_size < fota_ctx->page_buf_size) { + data_size = MIN(fota_ctx->effective_page_buf_size, size); + prog_size = fota_ctx->page_buf_size; + prog_buf = fota_ctx->page_buf; + } - while (size) { + // simple while-loop instead of check + do-while would take tens of bytes more from ROM + if (!size) { + goto exit; + } + + do { #if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) - ret = fota_encrypt_data(fota_ctx->enc_ctx, src_buf, prog_size, prog_buf, - metadata_buf, FOTA_ENCRYPT_METADATA_MAX_SIZE, - &metadata_actual_size); + uint8_t *tag = fota_ctx->page_buf; + ret = fota_encrypt_data(fota_ctx->enc_ctx, src_buf, data_size, src_buf, tag); if (ret) { + FOTA_TRACE_ERROR("encryption failed %d", ret); return FOTA_STATUS_INTERNAL_ERROR; } - - ret = handle_metadata_fragment(metadata_buf, metadata_actual_size); - if (ret) { - return FOTA_STATUS_INTERNAL_ERROR; +#elif MBED_CLOUD_CLIENT_FOTA_RESUME_SUPPORT == FOTA_RESUME_SUPPORT_RESUME + fota_candidate_block_checksum_t *checksum = (fota_candidate_block_checksum_t *) fota_ctx->page_buf; + *checksum = 0; + for (uint32_t i = 0; i < data_size; i++) { + *checksum += fota_ctx->effective_page_buf[i]; } #endif + if (prog_size < fota_ctx->page_buf_size) { + memset(fota_ctx->page_buf + prog_size, 0, fota_ctx->page_buf_size - prog_size); + // We are on the very last page, align up to page buffer size + prog_size = fota_align_up(prog_size, fota_ctx->page_buf_size); + } ret = fota_bd_program(prog_buf, addr, prog_size); if (ret) { - FOTA_TRACE_ERROR("Write to storage failed, address %" PRIu32 ", size %" PRIu32, - addr, size); + FOTA_TRACE_ERROR("Write to storage failed, address %" PRIu32 ", size %" PRIu32 " %d", + addr, size, ret); return FOTA_STATUS_STORAGE_WRITE_FAILED; } - src_buf += prog_size; + src_buf += data_size; addr += prog_size; - size -= prog_size; - } + size -= data_size; + fota_ctx->fw_bytes_written += data_size; + fota_ctx->storage_addr += prog_size; + } while (size); + +exit: return FOTA_STATUS_SUCCESS; } @@ -1066,32 +1369,33 @@ static int handle_fw_fragment(uint8_t *buf, size_t size, bool last) } while (size) { - if (fota_ctx->page_buf_offset || (size < fota_ctx->page_buf_size)) { - chunk = MIN(fota_ctx->page_buf_size - fota_ctx->page_buf_offset, size); + // Two cases here: + // 1. The "hard" one - If our fragment is not aligned to a whole page: + // In this case, just pull the remaining bytes into the page buf to complete the page. + // 2. The "easy" one - fragment is aligned to a whole page: + // In this case, use source buffer directly and push as many pages as possible. + if ((fota_ctx->effective_page_buf_size < fota_ctx->page_buf_size) || + fota_ctx->page_buf_offset || (size < fota_ctx->effective_page_buf_size)) { + chunk = MIN(fota_ctx->effective_page_buf_size - fota_ctx->page_buf_offset, size); prog_size = fota_ctx->page_buf_offset + chunk; - prog_buf = fota_ctx->page_buf; - memcpy(fota_ctx->page_buf + fota_ctx->page_buf_offset, source_buf, chunk); - fota_ctx->page_buf_offset = (fota_ctx->page_buf_offset + chunk) % fota_ctx->page_buf_size; - if (last) { - prog_size = fota_align_up(prog_size, fota_bd_get_program_size()); - } + prog_buf = fota_ctx->effective_page_buf; + memcpy(fota_ctx->effective_page_buf + fota_ctx->page_buf_offset, source_buf, chunk); + fota_ctx->page_buf_offset = (fota_ctx->page_buf_offset + chunk) % fota_ctx->effective_page_buf_size; } else { - chunk = fota_align_down(size, fota_ctx->page_buf_size); + chunk = fota_align_down(size, fota_ctx->effective_page_buf_size); prog_size = chunk; prog_buf = source_buf; } source_buf += chunk; - if ((prog_size >= fota_ctx->page_buf_size) || last) { + if ((prog_size >= fota_ctx->effective_page_buf_size) || last) { ret = program_to_storage(prog_buf, - fota_candidate_get_config()->storage_start_addr + fota_ctx->fw_offset_in_storage + - fota_ctx->fw_bytes_written, + fota_ctx->storage_addr, prog_size); if (ret) { - return ret; + FOTA_TRACE_ERROR("Failed writing to storage %d", ret); + return FOTA_STATUS_STORAGE_WRITE_FAILED; } - - fota_ctx->fw_bytes_written += prog_size; } size -= chunk; } @@ -1112,21 +1416,41 @@ static int finalize_update(void) int ret; uint8_t curr_fw_hash_buf[FOTA_CRYPTO_HASH_SIZE]; + // Ongoing resume state here means that all authentication has been done before. + // Can jump straight to finish. + if (fota_ctx->resume_state == FOTA_RESUME_STATE_ONGOING) { + goto finished; + } + ret = fota_hash_result(fota_ctx->curr_fw_hash_ctx, curr_fw_hash_buf); if (ret) { return ret; } - +#if defined(MBED_CLOUD_CLIENT_FOTA_SIGNED_IMAGE_SUPPORT) + ret = fota_verify_signature_prehashed( + curr_fw_hash_buf, + fota_ctx->fw_info->installed_signature, FOTA_IMAGE_RAW_SIGNATURE_SIZE + ); + FOTA_FI_SAFE_COND( + (ret == FOTA_STATUS_SUCCESS), + FOTA_STATUS_MANIFEST_PAYLOAD_CORRUPTED, + "Candidate image is not authentic" + ); +#else FOTA_FI_SAFE_MEMCMP(curr_fw_hash_buf, fota_ctx->fw_info->installed_digest, FOTA_CRYPTO_HASH_SIZE, FOTA_STATUS_MANIFEST_PAYLOAD_CORRUPTED, "Downloaded FW hash does not match manifest hash"); +#endif +finished: #if !defined(FOTA_DISABLE_DELTA) - ret = fota_delta_finalize(&fota_ctx->delta_ctx); - if (ret) { - return ret; + if (fota_ctx->fw_info->payload_format == FOTA_MANIFEST_PAYLOAD_FORMAT_DELTA) { + ret = fota_delta_finalize(&fota_ctx->delta_ctx); + if (ret) { + return ret; + } + fota_ctx->delta_ctx = 0; } - fota_ctx->delta_ctx = 0; #endif FOTA_TRACE_INFO("Firmware download finished"); @@ -1180,6 +1504,10 @@ void fota_on_fragment(uint8_t *buf, size_t size) uint32_t actual_frag_size; if (payload_bytes_left) { ret = fota_delta_new_payload_frag(fota_ctx->delta_ctx, buf, size); + if (ret == FOTA_STATUS_FW_DELTA_REQUIRED_MORE_DATA) { + payload_bytes_left -= size; + break; + } } else { ret = fota_delta_payload_finished(fota_ctx->delta_ctx); size = 0; @@ -1221,13 +1549,9 @@ void fota_on_fragment(uint8_t *buf, size_t size) fota_ctx->payload_offset += size; + memset(buf, 0, size); + if (!payload_bytes_left) { -#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) - ret = handle_metadata_fragment(0, 0); - if (ret) { - goto fail; - } -#endif ret = finalize_update(); if (ret) { goto fail; @@ -1239,25 +1563,31 @@ void fota_on_fragment(uint8_t *buf, size_t size) if (ret) { goto fail; } - return; fail: + memset(buf, 0, size); abort_update(ret, "Failed on fragment event"); } -void fota_on_resume(uint8_t *data, size_t size) +void fota_on_resume(uint32_t token, int32_t status) { - (void)data; // unused - (void)size; // unused + (void)token; // unused + (void)status; // unused if (fota_ctx) { return; // FOTA is already running - ignore } size_t manifest_size; uint8_t *manifest = malloc(FOTA_MANIFEST_MAX_SIZE); - FOTA_ASSERT(manifest); + + if (!manifest) { + FOTA_TRACE_ERROR("FOTA manifest - allocation failed"); + abort_update(FOTA_STATUS_OUT_OF_MEMORY, "fota_on_resume"); + return; + } + memset(manifest, 0, FOTA_MANIFEST_MAX_SIZE); int ret = fota_nvm_manifest_get(manifest, FOTA_MANIFEST_MAX_SIZE, &manifest_size); diff --git a/fota/fota.h b/fota/fota.h index c0c3157..1c0172b 100644 --- a/fota/fota.h +++ b/fota/fota.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -53,76 +53,6 @@ int fota_init(endpoint_t *in_endpoint); */ int fota_deinit(void); - -/* - +--------------------------------------------------------------------------------+-------------------------------------------------------------------------------+ - | Update candidate layout on storage with encryption | Update candidate layout on storage without encryption | - | | | - | +---------------------------+ <- MBED_CLOUD_CLIENT_FOTA_STORAGE_START_ADDR | +---------------------------+ <- MBED_CLOUD_CLIENT_FOTA_STORAGE_START_ADDR | - | | Candidate Ready Header | * Alignment to BD program size * | | Candidate Ready Header | * Alignment to BD program size * | - | +---------------------------+ <- Encryption Metadata structure start | +---------------------------+ <- Encryption Metadata structure end | - | | | * Alignment to BD program size * | | | <- FW header Stucture start | - | | | | | Firmware Header | * Alignment to BD program size * | - | | Encryption Metadta | | | | | - | | | | +---------------------------+ <- FW header Stucture end | - | | | | | | * Alignment to BD program size * | - | +---------------------------+ <- Encryption Metadata structure end | | | | - | | | <- FW header Stucture start | | | | - | | Firmware Header | * Alignment to BD program size * | | Firmware | | - | | | | | | | - | +---------------------------+ <- FW header Stucture end | | | | - | | | * Alignment to BD program size * | | | | - | | | | +---------------------------+ <- fota_ctx.storage_end_addr | - | | | | * Alignment to BD erase size * | - | | Firmware | | | - | | | | | - | | | | | - | | | | | - | +---------------------------+ <- fota_ctx.storage_end_addr | | - | * Alignment to BD erase size * | | - +----------------------------------------------------------------------------+-----------------------------------------------------------------------------------+ - | | - | +---------------------------+ +-------------------------+----------------------------------------------+ | - | | Candidate Ready Header +-----------------------> | Magic (8 Bytes) | Component name (8 bytes) | | - | +---------------------------+ +-------------------------+----------------------------------------------+ | - | | | | - | | | +-------------------------+----------------------------------------------+ | - | | Encryption Metadata +-----------------------> | Magic (4 Bytes) | Tags area length (4 Bytes) | | - | | | +-------------------------+----------------------------------------------+ | - | | | | | | - | +---------------------------+ | Salt (16 Bytes) | | - | | | | | | - | | Firmware Header +---------------+ +------------------------------------------------------------------------+ | - | | | | | | | - | +---------------------------+ | | | | - | | | | | Tags Area | | - | | | | | (Aligned to BD program size) | | - | | | | | Holds fw-size / MBED_CLOUD_CLIENT_FOTA_ENCRYPT_BLOCK_SIZE + 2 Tags | | - | | Firmware | | | Each tag is FOTA_ENCRYPT_METADATA_MAX_SIZE | | - | | | | | | | - | | | | | | | - | | | | +------------------------------------------------------------------------+ | - | +---------------------------+ | | - | | +-------------------------+----------------------------------------------+ | - | +-------> | Magic (4 Bytes) | FW size (4 Bytes) | | - | +-------------------------+----------------------------------------------+ | - | | FW Version (8 Bytes) | | - | +------------------------------------------------------------------------+ | - | | | | - | | FW Digest (SHA-256) (32 Bytes) | | - | | | | - | | | | - | +------------------------------------------------------------------------+ | - | | | | - | | Precursor Digest (SHA-256) ( 32 Bytes) | | - | | | | - | | | | - | +------------------------------------------------------------------------+ | - | | - +----------------------------------------------------------------------------------------------------------------------------------------------------------------+ -*/ - - #ifdef __cplusplus } #endif diff --git a/fota/fota_app_ifs.c b/fota/fota_app_ifs.c index 4bce41e..8c24f67 100644 --- a/fota/fota_app_ifs.c +++ b/fota/fota_app_ifs.c @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -19,10 +19,14 @@ #ifdef MBED_CLOUD_CLIENT_FOTA_ENABLE +#define TRACE_GROUP "FOTA" + #include "fota/fota.h" #include "fota/fota_source.h" #include "fota/fota_internal.h" #include "fota/fota_event_handler.h" +#include "fota/fota_component_defs.h" +#include "fota/fota_component.h" #include @@ -43,10 +47,11 @@ void fota_app_defer(uint32_t token) void fota_app_resume(void) { - fota_event_handler_defer_with_data(fota_on_resume, NULL, 0); + fota_event_handler_defer_with_result(fota_on_resume, 0, 0); } -FOTA_WEAK void fota_app_on_download_progress(uint32_t downloaded_size, uint32_t current_chunk_size, uint32_t total_size) +#if FOTA_DEFAULT_APP_IFS +void fota_app_on_download_progress(uint32_t downloaded_size, uint32_t current_chunk_size, uint32_t total_size) { FOTA_ASSERT(total_size); static const uint32_t print_range_percent = 5; @@ -63,7 +68,7 @@ FOTA_WEAK void fota_app_on_download_progress(uint32_t downloaded_size, uint32_t * dismiss any update running dialogs. * */ -FOTA_WEAK int fota_app_on_complete(int32_t status) +int fota_app_on_complete(int32_t status) { return FOTA_STATUS_SUCCESS; } @@ -76,7 +81,7 @@ FOTA_WEAK int fota_app_on_complete(int32_t status) Note: the authorization call can be postponed and called later. This doesn't affect the performance of the Cloud Client. */ -FOTA_WEAK int fota_app_on_install_authorization(uint32_t token) +int fota_app_on_install_authorization(uint32_t token) { fota_app_authorize(token); FOTA_APP_PRINT("Install authorization granted"); @@ -93,18 +98,21 @@ FOTA_WEAK int fota_app_on_install_authorization(uint32_t token) Note: the authorization call can be postponed and called later. This doesn't affect the performance of the Cloud Client. */ -FOTA_WEAK int fota_app_on_download_authorization( +int fota_app_on_download_authorization( uint32_t token, const manifest_firmware_info_t *candidate_info, fota_component_version_t curr_fw_version ) { + char curr_semver[FOTA_COMPONENT_MAX_SEMVER_STR_SIZE] = { 0 }; + char new_semver[FOTA_COMPONENT_MAX_SEMVER_STR_SIZE] = { 0 }; + fota_component_version_int_to_semver(curr_fw_version, curr_semver); + fota_component_version_int_to_semver(candidate_info->version, new_semver); FOTA_APP_PRINT("---------------------------------------------------"); FOTA_APP_PRINT( - "Updating component %s from version %" PRIu64 " to %" PRIu64, + "Updating component %s from version %s to %s", candidate_info->component_name, - curr_fw_version, - candidate_info->version + curr_semver, new_semver ); FOTA_APP_PRINT("Update priority %" PRIu32, candidate_info->priority); @@ -130,5 +138,6 @@ FOTA_WEAK int fota_app_on_download_authorization( */ return FOTA_STATUS_SUCCESS; } +#endif // FOTA_DEFAULT_APP_IFS #endif // MBED_CLOUD_CLIENT_FOTA_ENABLE diff --git a/fota/fota_app_ifs.h b/fota/fota_app_ifs.h index 5f1f7d7..c3f029b 100644 --- a/fota/fota_app_ifs.h +++ b/fota/fota_app_ifs.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -50,7 +50,7 @@ typedef enum { * Update will be restarted on next boot. Alternatively update can be restarted by calling fota_app_resume(). * * \note only required if MBED_CLOUD_CLIENT_FOTA_ENABLE build flag is specified - * + * \note the FW versions in this callback are in internal library format and should be converted to string using fota_component_version_int_to_semver() before use. * \param[in] token callback token The token is expected to be passed to fota_app_authorize() or fota_app_reject() * \param[in] candidate_info update candidate descriptor * \param[in] curr_fw_version current component FW version @@ -95,7 +95,7 @@ int fota_app_on_complete(int32_t status); * Resume Pelion FOTA update. * * In case update process was interupted - application can restart it by calling this function. - */ + */ void fota_app_resume(void); /** diff --git a/fota/fota_base.h b/fota/fota_base.h index fe35a7e..691188b 100644 --- a/fota/fota_base.h +++ b/fota/fota_base.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -43,6 +43,13 @@ extern "C" { #define FOTA_WEAK __attribute__((weak)) #endif +#if MBED_CONF_MBED_TRACE_ENABLE +#include "mbed-trace/mbed_trace.h" +#define FOTA_TRACE_DEBUG tr_debug +#define FOTA_TRACE_INFO tr_info +#define FOTA_TRACE_ERROR tr_error +#else + #if FOTA_TRACE_ENABLE #if FOTA_TRACE_DBG #define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__) @@ -54,15 +61,12 @@ extern "C" { #define FOTA_TRACE_INFO(fmt, ...) printf("[FOTA INFO] " fmt "\n", ##__VA_ARGS__) #define FOTA_TRACE_ERROR(fmt, ...) printf("[FOTA ERROR] " fmt "\n", ##__VA_ARGS__) #endif // FOTA_TRACE_DBG -#else // !FOTA_TRACE_ENABLE -#include "mbed-trace/mbed_trace.h" -#ifndef TRACE_GROUP -#define TRACE_GROUP "FOTA" -#endif -#define FOTA_TRACE_DEBUG tr_debug -#define FOTA_TRACE_INFO tr_info -#define FOTA_TRACE_ERROR tr_error -#endif // FOTA_TRACE_ENABLE +#else // FOTA_TRACE_ENABLE +#define FOTA_TRACE_DEBUG(fmt, ...) +#define FOTA_TRACE_INFO(fmt, ...) +#define FOTA_TRACE_ERROR(fmt, ...) +#endif // !FOTA_TRACE_ENABLE +#endif // !MBED_CONF_MBED_TRACE_ENABLE #if FOTA_APP_DEFAULT_CB_NO_PRINT #define FOTA_APP_PRINT FOTA_TRACE_INFO @@ -70,7 +74,6 @@ extern "C" { #define FOTA_APP_PRINT(fmt, ...) printf("[FOTA] " fmt "\n", ##__VA_ARGS__) #endif - #if !defined(FOTA_HALT) #define FOTA_HALT for(;;) #endif diff --git a/fota/fota_block_device.cpp b/fota/fota_block_device.cpp index 998e3c9..c4a0b1d 100644 --- a/fota/fota_block_device.cpp +++ b/fota/fota_block_device.cpp @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -20,16 +20,15 @@ #ifdef MBED_CLOUD_CLIENT_FOTA_ENABLE +#define TRACE_GROUP "FOTA" + #include "fota/fota_block_device.h" +#include "fota/fota_status.h" // External BD should supply all these APIs #if (MBED_CLOUD_CLIENT_FOTA_BLOCK_DEVICE_TYPE != FOTA_EXTERNAL_BD) -#ifndef __MBED__ -#error This type of block device is only supported in mbed-os -#endif - static bool initialized = false; #include "BlockDevice.h" @@ -64,28 +63,20 @@ mbed::BlockDevice *fota_bd_get_custom_bd() extern "C" { #endif -int fota_bd_create(uint32_t size, uint32_t read_size, uint32_t prog_size, - uint32_t erase_size) -{ - return 0; -} - -uint32_t fota_bd_size() +int fota_bd_size(uint32_t *size) { if (!initialized) { - int ret = fota_bd_init(); - if (ret) { - return 0; - } + return FOTA_STATUS_NOT_INITIALIZED; } - return bd->size(); + *size = (uint32_t) bd->size(); + return FOTA_STATUS_SUCCESS; } int fota_bd_init(void) { if (initialized) { - return 0; + return FOTA_STATUS_SUCCESS; } if (!bd) { @@ -96,14 +87,16 @@ int fota_bd_init(void) int ret = bd->init(); if (!ret) { initialized = true; + return FOTA_STATUS_SUCCESS; } - return ret; + FOTA_TRACE_ERROR("Failed to initialize BlockDevice. error %d", ret); + return FOTA_STATUS_NOT_INITIALIZED; } int fota_bd_deinit(void) { if (!initialized) { - return 0; + return FOTA_STATUS_SUCCESS; } int ret = bd->deinit(); @@ -112,91 +105,79 @@ int fota_bd_deinit(void) #endif bd = 0; initialized = false; - return ret; + if (!ret) { + return FOTA_STATUS_SUCCESS; + } + FOTA_TRACE_ERROR("Failed to deinitialize BlockDevice. error %d", ret); + return FOTA_STATUS_INTERNAL_ERROR; } int fota_bd_read(void *buffer, uint32_t addr, uint32_t size) { - if (!initialized) { - int ret = fota_bd_init(); - if (ret) { - return ret; - } - } + int ret; + FOTA_ASSERT(bd); - return bd->read(buffer, addr, size); + ret = bd->read(buffer, addr, size); + if (ret) { + return FOTA_STATUS_STORAGE_READ_FAILED; + } + return FOTA_STATUS_SUCCESS; } int fota_bd_program(const void *buffer, uint32_t addr, uint32_t size) { - if (!initialized) { - int ret = fota_bd_init(); - if (ret) { - return ret; - } - } + int ret; + FOTA_ASSERT(bd); - return bd->program(buffer, addr, size); + ret = bd->program(buffer, addr, size); + if (ret) { + return FOTA_STATUS_STORAGE_WRITE_FAILED; + } + return FOTA_STATUS_SUCCESS; } int fota_bd_erase(uint32_t addr, uint32_t size) { - if (!initialized) { - int ret = fota_bd_init(); - if (ret) { - return ret; - } - } + int ret; + FOTA_ASSERT(bd); - return bd->erase(addr, size); + ret = bd->erase(addr, size); + if (ret) { + return FOTA_STATUS_STORAGE_WRITE_FAILED; + } + return FOTA_STATUS_SUCCESS; } -uint32_t fota_bd_get_read_size(void) +int fota_bd_get_read_size(uint32_t *read_size) { - if (!initialized) { - int ret = fota_bd_init(); - if (ret) { - return 0; - } - } + FOTA_ASSERT(bd); - return bd->get_read_size(); + *read_size = (uint32_t) bd->get_read_size(); + return FOTA_STATUS_SUCCESS; } -uint32_t fota_bd_get_program_size(void) +int fota_bd_get_program_size(uint32_t *prog_size) { - if (!initialized) { - int ret = fota_bd_init(); - if (ret) { - return 0; - } - } + FOTA_ASSERT(bd); - return bd->get_program_size(); + *prog_size = (uint32_t)bd->get_program_size(); + return FOTA_STATUS_SUCCESS; } -uint32_t fota_bd_get_erase_size(uint32_t addr) +int fota_bd_get_erase_size(uint32_t addr, uint32_t *erase_size) { - if (!initialized) { - int ret = fota_bd_init(); - if (ret) { - return 0; - } - } + FOTA_ASSERT(bd); - return bd->get_erase_size(addr); + *erase_size = (uint32_t) bd->get_erase_size(addr); + return FOTA_STATUS_SUCCESS; } -uint8_t fota_bd_get_erase_value(void) +int fota_bd_get_erase_value(int *erase_value) { - if (!initialized) { - int ret = fota_bd_init(); - if (ret) { - return 0; - } - } + FOTA_ASSERT(bd); - return bd->get_erase_value(); + *erase_value = bd->get_erase_value(); + return FOTA_STATUS_SUCCESS; } #ifdef __cplusplus diff --git a/fota/fota_block_device.h b/fota/fota_block_device.h index 7628fad..e90b635 100644 --- a/fota/fota_block_device.h +++ b/fota/fota_block_device.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -25,14 +25,6 @@ extern "C" { #endif -#define FOTA_INTERNAL_FLASH_BD 1 -#define FOTA_CUSTOM_BD 2 -#define FOTA_EXTERNAL_BD 3 - -// For testing purposes -int fota_bd_create(uint32_t size, uint32_t read_size, uint32_t prog_size, - uint32_t erase_size); - /* * Pelion FOTA block device initialize * @@ -51,9 +43,11 @@ int fota_bd_deinit(void); /* * Pelion FOTA block device size getter - * \return block device size. A positive value on success 0 otherwise. + * + * \param[out] size Block device size. + * \return FOTA_STATUS_SUCCESS on success */ -uint32_t fota_bd_size(void); +int fota_bd_size(uint32_t *size); /* * Pelion FOTA block device read. @@ -94,31 +88,36 @@ int fota_bd_erase(uint32_t addr, uint32_t size); /* * Pelion FOTA block device get the size of a readable block. * - * \return The size of a readable block in bytes. + * \param[out] read_size The size of a readable block in bytes. + * \return FOTA_STATUS_SUCCESS on success */ -uint32_t fota_bd_get_read_size(void); +int fota_bd_get_read_size(uint32_t *read_size); /* * Pelion FOTA block device get the size of a programmable block. * - * \return The size of a programmable block in bytes. A positive value on success 0 otherwise. + * \param[out] prog_size The size of a programmable block in bytes. A positive value on success 0 otherwise. + * \return FOTA_STATUS_SUCCESS on success */ -uint32_t fota_bd_get_program_size(void); +int fota_bd_get_program_size(uint32_t *prog_size); /* * Pelion FOTA block device get the size of a erasable block given address. * - * \param[in] addr Address of erasable block. - * \return The size of an erasable block in bytes. A positive value on success 0 otherwise. + * \param[in] addr Address of erasable block. + * \param[out] erase_size The size of an erasable block in bytes. A positive value on success 0 otherwise. + * \return FOTA_STATUS_SUCCESS on success */ -uint32_t fota_bd_get_erase_size(uint32_t addr); +int fota_bd_get_erase_size(uint32_t addr, uint32_t *erase_size); /* * Pelion FOTA block device get the value of storage when erased. * - * \returns erase value. + * \param[out] erase_value erase value if non negative. + * If negative, means that the one can't rely on this value for this block device. + * \return FOTA_STATUS_SUCCESS on success */ -uint8_t fota_bd_get_erase_value(void); +int fota_bd_get_erase_value(int *erase_value); #ifdef __cplusplus } diff --git a/fota/fota_candidate.c b/fota/fota_candidate.c index ea9076f..6960744 100644 --- a/fota/fota_candidate.c +++ b/fota/fota_candidate.c @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -20,6 +20,8 @@ #ifdef MBED_CLOUD_CLIENT_FOTA_ENABLE +#define TRACE_GROUP "FOTA" + #include "fota/fota_candidate.h" #include "fota/fota_status.h" #include "fota/fota_block_device.h" @@ -30,31 +32,27 @@ #include #define MIN_FRAG_SIZE 128 -#define TAGS_BUF_SIZE 128 typedef struct { fota_header_info_t header_info; - uint8_t salt[FOTA_ENCRYPT_METADATA_SALT_LEN]; uint32_t bd_read_size; uint32_t bd_prog_size; uint32_t curr_addr; - uint32_t tags_addr; uint32_t data_start_addr; - uint32_t frag_size; + uint32_t effective_block_size; + uint32_t block_checker_size; + uint32_t frag_extra_bytes; uint32_t bytes_completed; - uint32_t next_pct; - uint32_t tags_buf_size; - uint32_t curr_tag_offs; + uint32_t install_alignment; uint8_t *fragment_buf; - uint8_t *tags_buf; +#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) fota_encrypt_context_t *enc_ctx; - bool is_encrypted; +#endif } candidate_contex_t; static fota_candidate_config_t fota_candidate_config = { .storage_start_addr = 0, .storage_size = 0, - .encrypt_block_size = 0 }; static candidate_contex_t *ctx = NULL; @@ -73,29 +71,31 @@ const fota_candidate_config_t *fota_candidate_get_config(void) fota_candidate_config_t fota_candidate_init_config = { .storage_start_addr = fota_bd_physical_addr_to_logical_addr(MBED_CLOUD_CLIENT_FOTA_STORAGE_START_ADDR), .storage_size = MBED_CLOUD_CLIENT_FOTA_STORAGE_SIZE, - .encrypt_block_size = MBED_CLOUD_CLIENT_FOTA_ENCRYPT_BLOCK_SIZE }; fota_candidate_set_config(&fota_candidate_init_config); } return (const fota_candidate_config_t *) &fota_candidate_config; } -static int bd_has_image(uint32_t *addr, const char *expected_comp_name) +int fota_candidate_read_candidate_ready_header(uint32_t *addr, uint32_t bd_read_size, uint32_t bd_prog_size, + fota_candidate_ready_header_t *header) { int ret = FOTA_STATUS_SUCCESS; // Return success on non BL ready headers (let parse_header deal with it) #if FOTA_HEADER_HAS_CANDIDATE_READY - FOTA_DBG_ASSERT(ctx); uint8_t read_buf[sizeof(fota_candidate_ready_header_t)]; uint8_t *aligned_read_buf = read_buf; - fota_candidate_ready_header_t *header; - uint32_t chunk_size = fota_align_up(sizeof(fota_candidate_ready_header_t), ctx->bd_read_size); + + uint32_t chunk_size = fota_align_up(sizeof(fota_candidate_ready_header_t), bd_read_size); if (chunk_size > sizeof(read_buf)) { // This is very unlikely to happen, as read size is usually 1. // So prefer the buffer to be allocated on stack, which is the likely case. aligned_read_buf = (uint8_t *) malloc(chunk_size); - FOTA_ASSERT(aligned_read_buf); + if (!aligned_read_buf) { + FOTA_TRACE_ERROR("FOTA aligned_read_buf - allocation failed"); + return FOTA_STATUS_OUT_OF_MEMORY; + } } ret = fota_bd_read(aligned_read_buf, *addr, chunk_size); if (ret) { @@ -104,21 +104,15 @@ static int bd_has_image(uint32_t *addr, const char *expected_comp_name) } // Advance read address for next calls - *addr += fota_align_up(chunk_size, ctx->bd_prog_size); + *addr += fota_align_up(chunk_size, bd_prog_size); - header = (fota_candidate_ready_header_t *) aligned_read_buf; + memcpy(header, aligned_read_buf, sizeof(fota_candidate_ready_header_t)); if (header->magic != FOTA_CANDIDATE_READY_MAGIC) { FOTA_TRACE_INFO("No image found on storage"); ret = FOTA_STATUS_NOT_FOUND; goto end; } - if (strncmp(header->comp_name, expected_comp_name, strlen(expected_comp_name))) { - FOTA_TRACE_ERROR("Unexpected component candidate found"); - ret = FOTA_STATUS_UNEXPECTED_COMPONENT; - goto end; - } - end: if (chunk_size > sizeof(read_buf)) { free(aligned_read_buf); @@ -127,207 +121,180 @@ static int bd_has_image(uint32_t *addr, const char *expected_comp_name) return ret; } -static int bd_has_encrypted_image(uint32_t *addr, uint32_t *tags_size) -{ - int ret = FOTA_STATUS_NOT_FOUND; -#if FOTA_HEADER_SUPPORTS_ENCRYPTION - FOTA_DBG_ASSERT(ctx); - uint8_t read_buf[FOTA_ENCRYPT_METADATA_START_SIZE]; - uint8_t *aligned_read_buf = read_buf; - uint32_t chunk_size = fota_align_up(FOTA_ENCRYPT_METADATA_START_SIZE, ctx->bd_read_size); - - if (chunk_size > sizeof(read_buf)) { - // This is very unlikely to happen, as read size is usually 1. - // So prefer the buffer to be allocated on stack, which is the likely case. - aligned_read_buf = (uint8_t *) malloc(chunk_size); - FOTA_ASSERT(aligned_read_buf); - } - ret = fota_bd_read(aligned_read_buf, *addr, chunk_size); - if (ret) { - ret = FOTA_STATUS_STORAGE_READ_FAILED; - goto end; - } - - if (!fota_encryption_metadata_parse(aligned_read_buf, chunk_size, tags_size, ctx->salt, - FOTA_ENCRYPT_METADATA_SALT_LEN)) { - FOTA_TRACE_INFO("Image on storage is not encrypted"); - ret = FOTA_STATUS_NOT_FOUND; - goto end; - } - - // Advance read address for next calls - *addr += fota_align_up(chunk_size, ctx->bd_prog_size); - -end: - if (chunk_size > sizeof(read_buf)) { - free(aligned_read_buf); - } - -#endif - return ret; -} - static void cleanup() { if (!ctx) { return; } +#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) if (ctx->enc_ctx) { fota_encrypt_finalize(&ctx->enc_ctx); } - free(ctx->tags_buf); +#endif free(ctx->fragment_buf); free(ctx); ctx = 0; } -static int parse_header(uint32_t *addr, bool encrypted, fota_header_info_t *header) +int fota_candidate_read_header(uint32_t *addr, uint32_t bd_read_size, uint32_t bd_prog_size, fota_header_info_t *header) { uint32_t header_size = (uint32_t) fota_get_header_size(); - uint32_t read_size = fota_align_up(header_size, ctx->bd_read_size); + uint32_t read_size = fota_align_up(header_size, bd_read_size); - FOTA_DBG_ASSERT(ctx); - int ret = fota_bd_read(ctx->fragment_buf, *addr, read_size); - *addr += fota_align_up(header_size, ctx->bd_prog_size); + uint8_t *header_buf = (uint8_t *) malloc(read_size); + if (!header_buf) { + FOTA_TRACE_ERROR("FOTA header - allocation failed"); + return FOTA_STATUS_OUT_OF_MEMORY; + } + + int ret = fota_bd_read(header_buf, *addr, read_size); + *addr += fota_align_up(header_size, bd_prog_size); if (ret) { goto end; } - if (encrypted) { -#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) - ret = fota_decrypt_data(ctx->enc_ctx, ctx->fragment_buf, header_size, ctx->fragment_buf, - ctx->tags_buf, FOTA_ENCRYPT_METADATA_MAX_SIZE); - if (ret) { - goto end; - } - ctx->curr_tag_offs += FOTA_ENCRYPT_METADATA_MAX_SIZE; -#endif - } - - ret = fota_deserialize_header(ctx->fragment_buf, header_size, header); + ret = fota_deserialize_header(header_buf, header_size, header); if (ret) { goto end; } end: + free(header_buf); return ret; } -static int fota_candidate_extract_start(bool force_encrypt, const char *expected_comp_name) +static int fota_candidate_extract_start(bool force_encrypt, const char *expected_comp_name, + uint32_t install_alignment) { int ret; - uint32_t tags_size; + uint32_t alloc_size, block_size; if (!ctx) { ctx = (candidate_contex_t *) malloc(sizeof(candidate_contex_t)); - FOTA_ASSERT(ctx); + if (!ctx) { + FOTA_TRACE_ERROR("FOTA candidate_contex_t - allocation failed"); + return FOTA_STATUS_OUT_OF_MEMORY; + } memset(ctx, 0, sizeof(candidate_contex_t)); - } - - ctx->bd_read_size = fota_bd_get_read_size(); - if (!ctx->bd_read_size) { - ret = FOTA_STATUS_INTERNAL_ERROR; - goto fail; - } - ctx->bd_prog_size = fota_bd_get_program_size(); - if (!ctx->bd_prog_size) { - ret = FOTA_STATUS_INTERNAL_ERROR; - goto fail; - } - - ctx->curr_addr = fota_candidate_get_config()->storage_start_addr; - ret = bd_has_image(&ctx->curr_addr, expected_comp_name); - if (ret) { - goto fail; - } - - ret = bd_has_encrypted_image(&ctx->curr_addr, &tags_size); - if (!ret) { -#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 0) - FOTA_TRACE_ERROR("Encrypted candidate image - not supported"); - ret = FOTA_STATUS_UNSUPPORTED; - goto fail; -#endif - ctx->is_encrypted = true; - ctx->frag_size = MAX(MIN_FRAG_SIZE, fota_candidate_get_config()->encrypt_block_size); - ctx->frag_size = fota_align_up(ctx->frag_size, ctx->bd_read_size); - FOTA_TRACE_INFO("Found an encrypted image at address 0x%" PRIx32, fota_candidate_get_config()->storage_start_addr); - } else if (ret == FOTA_STATUS_NOT_FOUND) { - if (force_encrypt) { - FOTA_TRACE_ERROR("Non-encrypted image found, but this is not allowed for this candidate type."); - ret = FOTA_STATUS_NOT_ALLOWED; + ret = fota_bd_get_read_size(&ctx->bd_read_size); + if (ret) { + FOTA_TRACE_ERROR("fota_bd_get_read_size error %d", ret); goto fail; } - ctx->is_encrypted = false; - ctx->frag_size = fota_align_up(MIN_FRAG_SIZE, ctx->bd_read_size); - FOTA_TRACE_INFO("Found a non-encrypted image at address 0x%" PRIx32, fota_candidate_get_config()->storage_start_addr); - } else { - goto fail; - } - ctx->fragment_buf = (uint8_t *) malloc(ctx->frag_size); - FOTA_ASSERT(ctx->fragment_buf); + ret = fota_bd_get_program_size(&ctx->bd_prog_size); + if (ret) { + FOTA_TRACE_ERROR("fota_bd_get_program_size error %d", ret); + goto fail; + } -#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) - if (ctx->is_encrypted) { - fota_encrypt_config_t encrypt_config; - uint8_t fw_enc_key[FOTA_ENCRYPT_KEY_SIZE]; - uint8_t derived_key[FOTA_ENCRYPT_KEY_SIZE]; + ctx->curr_addr = fota_candidate_get_config()->storage_start_addr; - ret = fota_nvm_fw_encryption_key_get(fw_enc_key); + fota_candidate_ready_header_t header; + ret = fota_candidate_read_candidate_ready_header(&ctx->curr_addr, ctx->bd_read_size, ctx->bd_prog_size, &header); if (ret) { - FOTA_TRACE_ERROR("FW encryption key get failed. ret %d", ret); goto fail; } - ret = fota_get_derived_key(fw_enc_key, sizeof(fw_enc_key), ctx->salt, - sizeof(ctx->salt), derived_key); - if (ret) { - FOTA_TRACE_ERROR("Derived key get failed. ret %d", ret); +#if FOTA_HEADER_HAS_CANDIDATE_READY + if (strncmp(header.comp_name, expected_comp_name, strlen(expected_comp_name))) { + FOTA_TRACE_ERROR("Unexpected component candidate found"); + ret = FOTA_STATUS_UNEXPECTED_COMPONENT; goto fail; } +#endif - encrypt_config.encrypt_block_size = fota_candidate_get_config()->encrypt_block_size; - ret = fota_encrypt_decrypt_start(&ctx->enc_ctx, &encrypt_config, derived_key, FOTA_ENCRYPT_KEY_SIZE, false); + ret = fota_candidate_read_header(&ctx->curr_addr, ctx->bd_read_size, ctx->bd_prog_size, &ctx->header_info); if (ret) { - FOTA_TRACE_ERROR("Decrypt start failed. ret %d", ret); + FOTA_TRACE_ERROR("Header parsing failed. ret %d", ret); goto fail; } - // Make sure we don't read partial tags - FOTA_DBG_ASSERT(!((ctx->bd_read_size % FOTA_ENCRYPT_METADATA_MAX_SIZE) && - (FOTA_ENCRYPT_METADATA_MAX_SIZE % ctx->bd_read_size))); - - ctx->tags_buf_size = fota_align_up(TAGS_BUF_SIZE, ctx->bd_read_size); - ctx->tags_buf_size = fota_align_up(ctx->tags_buf_size, FOTA_ENCRYPT_METADATA_MAX_SIZE); - - ctx->tags_buf = (uint8_t *) malloc(ctx->tags_buf_size); - if (!ctx->tags_buf) { - FOTA_TRACE_ERROR("Unable to allocate tags buffer"); - ret = FOTA_STATUS_OUT_OF_MEMORY; + if (ctx->header_info.flags & FOTA_HEADER_ENCRYPTED_FLAG) { +#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 0) + FOTA_TRACE_ERROR("Encrypted candidate image - not supported"); + ret = FOTA_STATUS_UNSUPPORTED; goto fail; +#endif + FOTA_TRACE_INFO("Found an encrypted image at address 0x%" PRIx32, fota_candidate_get_config()->storage_start_addr); + } else { + if (force_encrypt) { + FOTA_TRACE_ERROR("Non-encrypted image found, but this is not allowed for this candidate type."); + ret = FOTA_STATUS_NOT_ALLOWED; + goto fail; + } + FOTA_TRACE_INFO("Found a non-encrypted image at address 0x%" PRIx32, fota_candidate_get_config()->storage_start_addr); } - ctx->curr_tag_offs = 0; - ctx->tags_addr = ctx->curr_addr; - ret = fota_bd_read(ctx->tags_buf, ctx->tags_addr, ctx->tags_buf_size); - if (ret) { - FOTA_TRACE_ERROR("Reading tags failed. ret %d", ret); - goto fail; + if (ctx->header_info.flags & (FOTA_HEADER_ENCRYPTED_FLAG | FOTA_HEADER_SUPPORT_RESUME_FLAG)) { + block_size = ctx->header_info.block_size; + } else { + block_size = MIN_FRAG_SIZE; } - ctx->curr_addr = fota_align_up(ctx->curr_addr + tags_size, ctx->bd_prog_size); + block_size = fota_align_up(block_size, ctx->bd_read_size); + + // Block checker can be different here and have different sizes: + // Tag (8 bytes) in encrypted case, checksum (2 bytes) in non-encrypted case (with resume support). + if (ctx->header_info.flags & FOTA_HEADER_ENCRYPTED_FLAG) { + ctx->block_checker_size = FOTA_ENCRYPT_TAG_SIZE; + } else if (ctx->header_info.flags & FOTA_HEADER_SUPPORT_RESUME_FLAG) { + ctx->block_checker_size = sizeof(fota_candidate_block_checksum_t); + } else { + ctx->block_checker_size = 0; + } + ctx->effective_block_size = block_size - ctx->block_checker_size; + +#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) + if (ctx->header_info.flags & FOTA_HEADER_ENCRYPTED_FLAG) { + uint8_t fw_key[FOTA_ENCRYPT_KEY_SIZE]; + + ret = fota_nvm_fw_encryption_key_get(fw_key); + if (ret) { + FOTA_TRACE_ERROR("FW encryption key get failed. ret %d", ret); + goto fail; + } + + ret = fota_encrypt_decrypt_start(&ctx->enc_ctx, fw_key, FOTA_ENCRYPT_KEY_SIZE); + memset(fw_key, 0, sizeof(fw_key)); + if (ret) { + FOTA_TRACE_ERROR("Decrypt start failed. ret %d", ret); + goto fail; + } + + ctx->curr_addr = fota_align_up(ctx->curr_addr, ctx->bd_prog_size); + } +#endif + + ctx->data_start_addr = ctx->curr_addr; + } // !ctx + + ctx->curr_addr = ctx->data_start_addr; + ctx->bytes_completed = 0; +#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) + if (ctx->header_info.flags & FOTA_HEADER_ENCRYPTED_FLAG) { + fota_encryption_stream_reset(ctx->enc_ctx); } #endif - ret = parse_header(&ctx->curr_addr, ctx->is_encrypted, &ctx->header_info); - if (ret) { - FOTA_TRACE_ERROR("Header parsing failed. ret %d", ret); - goto fail; + // Install alignment of zero is just like an alignment of 1 (i.e. no limitation) + ctx->install_alignment = install_alignment ? install_alignment : 1; + free(ctx->fragment_buf); + + alloc_size = ctx->effective_block_size + ctx->block_checker_size; + + // In case we are not aligned to installer requirements, need an extra + if (ctx->effective_block_size % ctx->install_alignment) { + alloc_size += ctx->install_alignment; } - ctx->data_start_addr = ctx->curr_addr; + ctx->fragment_buf = (uint8_t *) malloc(alloc_size); + if (!ctx->fragment_buf) { + FOTA_TRACE_ERROR("FOTA ctx->fragment_buf - allocation failed"); + ret = FOTA_STATUS_OUT_OF_MEMORY; + goto fail; + } return FOTA_STATUS_SUCCESS; @@ -336,76 +303,105 @@ static int fota_candidate_extract_start(bool force_encrypt, const char *expected return ret; } -static int fota_candidate_extract_fragment(uint8_t **buf, uint32_t *actual_size) +static int fota_candidate_extract_fragment(uint8_t **buf, uint32_t *actual_size, bool *ignore) { - uint32_t chunk, read_size; + uint32_t read_size; int ret; FOTA_DBG_ASSERT(ctx); - chunk = MIN(ctx->header_info.fw_size - ctx->bytes_completed, ctx->frag_size); - *actual_size = chunk; - if (!chunk) { + + *ignore = false; + + // Move extra bytes from last time from end to beginning of buffer + memcpy(ctx->fragment_buf, ctx->fragment_buf + *actual_size, ctx->frag_extra_bytes); + *buf = ctx->fragment_buf + ctx->frag_extra_bytes; + + *actual_size = MIN(ctx->header_info.fw_size - ctx->bytes_completed, ctx->effective_block_size); + if (!*actual_size) { return FOTA_STATUS_SUCCESS; } - if (ctx->is_encrypted) { - // encrypted blocks are aligned to program size - read_size = fota_align_up(chunk, ctx->bd_prog_size); - } else { - read_size = fota_align_up(chunk, ctx->bd_read_size); + read_size = fota_align_up(ctx->block_checker_size + *actual_size, ctx->bd_read_size); + + if (ctx->curr_addr + read_size > + fota_candidate_get_config()->storage_start_addr + fota_candidate_get_config()->storage_size) { + FOTA_TRACE_ERROR("Storage end address exceeded"); + return FOTA_STATUS_STORAGE_READ_FAILED; } - ret = fota_bd_read(ctx->fragment_buf, ctx->curr_addr, read_size); + ret = fota_bd_read(*buf, ctx->curr_addr, read_size); if (ret) { FOTA_TRACE_ERROR("storage read failed, ret %d", ret); return ret; } #if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) - if (ctx->is_encrypted) { - // exhausted tag group, read next one - if (!(ctx->curr_tag_offs % ctx->tags_buf_size)) { - ret = fota_bd_read(ctx->tags_buf, ctx->tags_addr + ctx->curr_tag_offs, ctx->tags_buf_size); - if (ret) { - FOTA_TRACE_ERROR("Reading tags failed. ret %d", ret); + if (ctx->header_info.flags & FOTA_HEADER_ENCRYPTED_FLAG) { + uint8_t *tag = *buf; + *buf += FOTA_ENCRYPT_TAG_SIZE; + ret = fota_decrypt_data(ctx->enc_ctx, *buf, *actual_size, *buf, tag); + if (ret) { + if (ctx->header_info.flags & FOTA_HEADER_SUPPORT_RESUME_FLAG) { + FOTA_TRACE_DEBUG("Bad block ignored"); + *ignore = true; + } else { + FOTA_TRACE_ERROR("decrypt data failed, ret %d", ret); return ret; } } + } +#endif - ret = fota_decrypt_data(ctx->enc_ctx, ctx->fragment_buf, read_size, ctx->fragment_buf, - ctx->tags_buf + ctx->curr_tag_offs % ctx->tags_buf_size, FOTA_ENCRYPT_METADATA_MAX_SIZE); - ctx->curr_tag_offs += FOTA_ENCRYPT_METADATA_MAX_SIZE; - if (ret) { - FOTA_TRACE_ERROR("decrypt data failed, ret %d", ret); - return ret; + if (!(ctx->header_info.flags & FOTA_HEADER_ENCRYPTED_FLAG) && + (ctx->header_info.flags & FOTA_HEADER_SUPPORT_RESUME_FLAG)) { + fota_candidate_block_checksum_t read_checksum = *(fota_candidate_block_checksum_t *) *buf; + *buf += sizeof(fota_candidate_block_checksum_t); + fota_candidate_block_checksum_t calc_checksum = 0; + for (uint32_t i = 0; i < *actual_size; i++) { + calc_checksum += (*buf)[i]; + } + if (calc_checksum != read_checksum) { + FOTA_TRACE_DEBUG("Bad block ignored"); + *ignore = true; } } -#endif - ctx->bytes_completed += chunk; - ctx->curr_addr += chunk; - *buf = ctx->fragment_buf; + ctx->curr_addr += read_size; - return FOTA_STATUS_SUCCESS; -} + if (*ignore) { + return FOTA_STATUS_SUCCESS; + } + + ctx->bytes_completed += *actual_size; + + if (*actual_size % ctx->install_alignment || ctx->frag_extra_bytes) { + // Not aligned, need to gather read data (without checker) and extra bytes from previous time + memmove(*buf - ctx->block_checker_size, *buf, *actual_size); + *buf = ctx->fragment_buf; + *actual_size += ctx->frag_extra_bytes; + if (*actual_size >= ctx->effective_block_size) { + ctx->frag_extra_bytes = *actual_size % ctx->install_alignment; + *actual_size -= ctx->frag_extra_bytes; + } + *actual_size = fota_align_up(*actual_size, ctx->install_alignment); + } -int fota_candidate_extract_finish() -{ - cleanup(); return FOTA_STATUS_SUCCESS; } int fota_candidate_iterate_image(bool validate, bool force_encrypt, const char *expected_comp_name, - fota_candidate_iterate_handler_t handler) + uint32_t install_alignment, fota_candidate_iterate_handler_t handler) { int ret; fota_candidate_iterate_callback_info cb_info; - uint32_t actual_size; + uint32_t actual_size = 0; uint8_t *buf; fota_hash_context_t *hash_ctx = NULL; + bool ignore; FOTA_ASSERT(handler); - ret = fota_candidate_extract_start(force_encrypt, expected_comp_name); + + ret = fota_candidate_extract_start(force_encrypt, expected_comp_name, 0); if (ret) { goto fail; } @@ -419,10 +415,14 @@ int fota_candidate_iterate_image(bool validate, bool force_encrypt, const char * goto fail; } do { - ret = fota_candidate_extract_fragment(&buf, &actual_size); + ret = fota_candidate_extract_fragment(&buf, &actual_size, &ignore); if (ret) { goto fail; } + if (ignore) { + continue; + } + ret = fota_hash_update(hash_ctx, buf, actual_size); if (ret) { goto fail; @@ -437,36 +437,35 @@ int fota_candidate_iterate_image(bool validate, bool force_encrypt, const char * fota_hash_finish(&hash_ctx); +#if defined(MBED_CLOUD_CLIENT_FOTA_SIGNED_IMAGE_SUPPORT) + int sig_verify_status = fota_verify_signature_prehashed( + hash_output, + ctx->header_info.signature, FOTA_IMAGE_RAW_SIGNATURE_SIZE + ); + FOTA_FI_SAFE_COND( + (sig_verify_status == FOTA_STATUS_SUCCESS), + (sig_verify_status == FOTA_STATUS_MANIFEST_SIGNATURE_INVALID) ? FOTA_STATUS_MANIFEST_PAYLOAD_CORRUPTED : ret, + "Candidate image is not authentic" + ); +#else FOTA_FI_SAFE_MEMCMP(hash_output, ctx->header_info.digest, FOTA_CRYPTO_HASH_SIZE, FOTA_STATUS_MANIFEST_PAYLOAD_CORRUPTED, "Hash mismatch - corrupted candidate"); - - // No need to call start extract again as it's quite heavy. - // Return to the state at the beginning of the data - ctx->curr_addr = ctx->data_start_addr; - ctx->bytes_completed = 0; -#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) - if (ctx->is_encrypted) { - ret = fota_bd_read(ctx->tags_buf, ctx->tags_addr, ctx->tags_buf_size); - if (ret) { - FOTA_TRACE_ERROR("Reading tags failed. ret %d", ret); - goto fail; - } - // Skip header tag - ctx->curr_tag_offs = FOTA_ENCRYPT_METADATA_MAX_SIZE; - fota_encryption_stream_reset(ctx->enc_ctx); - fota_encryption_iv_increment(ctx->enc_ctx); // compensate for parse_header - } #endif FOTA_TRACE_INFO("Image is valid."); } // Start iteration phase + + ret = fota_candidate_extract_start(force_encrypt, expected_comp_name, install_alignment); + if (ret) { + goto fail; + } + memset(&cb_info, 0, sizeof(cb_info)); cb_info.status = FOTA_CANDIDATE_ITERATE_START; cb_info.header_info = &ctx->header_info; - cb_info.salt = ctx->salt; ret = handler(&cb_info); if (ret) { FOTA_TRACE_ERROR("Candidate user handler failed on start, ret %d", ret); @@ -474,23 +473,26 @@ int fota_candidate_iterate_image(bool validate, bool force_encrypt, const char * } do { - ret = fota_candidate_extract_fragment(&buf, &actual_size); + ret = fota_candidate_extract_fragment(&buf, &actual_size, &ignore); if (ret) { goto fail; } + if (ignore) { + continue; + } cb_info.status = FOTA_CANDIDATE_ITERATE_FRAGMENT; cb_info.frag_size = actual_size; - cb_info.frag_pos = ctx->bytes_completed - actual_size; cb_info.frag_buf = buf; ret = handler(&cb_info); if (ret) { FOTA_TRACE_ERROR("Candidate user handler failed on fragment, ret %d", ret); goto fail; } - } while (actual_size); + cb_info.frag_pos += actual_size; + } while (cb_info.frag_pos < ctx->header_info.fw_size); #if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) - if (ctx->is_encrypted) { + if (ctx->header_info.flags & FOTA_HEADER_ENCRYPTED_FLAG) { fota_encrypt_finalize(&ctx->enc_ctx); } #endif @@ -512,7 +514,12 @@ int fota_candidate_iterate_image(bool validate, bool force_encrypt, const char * int fota_candidate_erase(void) { - int ret = fota_bd_erase(fota_candidate_get_config()->storage_start_addr, fota_bd_get_erase_size(fota_candidate_get_config()->storage_start_addr)); + uint32_t erase_size; + int ret = fota_bd_get_erase_size(fota_candidate_get_config()->storage_start_addr, &erase_size); + if (ret) { + return ret; + } + ret = fota_bd_erase(fota_candidate_get_config()->storage_start_addr, erase_size); return ret; } diff --git a/fota/fota_candidate.h b/fota/fota_candidate.h index a134e16..edce491 100644 --- a/fota/fota_candidate.h +++ b/fota/fota_candidate.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -38,15 +38,17 @@ typedef enum { FOTA_CANDIDATE_ITERATE_FINISH, /**< sent once on candidate iteration finish event */ } fota_candidate_iterate_status; +// Block checksum (in case of resume and non encrypted blocks) +typedef uint16_t fota_candidate_block_checksum_t; + /** * Candidate iterate callback info * - * status iterate status + * status iterate status. * frag_size fragment size. * frag_pos fragment position. * frag_buf fragment buffer. - * salt Salt from candidate header encryption metadata - * header_info candidate header info + * header_info candidate header info. * user_ctx user data, which lives between the calls to the callbacks */ typedef struct { @@ -54,24 +56,19 @@ typedef struct { uint32_t frag_size; uint32_t frag_pos; uint8_t *frag_buf; - uint8_t *salt; fota_header_info_t *header_info; void *user_ctx; } fota_candidate_iterate_callback_info; -typedef int (*fota_candidate_iterate_handler_t)(const fota_candidate_iterate_callback_info *info); - /** * Candidate config info * * storage_size storage size used for candidate. * storage_start_addr storage start address for candidate. - * encrypt_block_size encryption block size for candidate encryption. */ typedef struct { uint32_t storage_size; uint32_t storage_start_addr; - uint32_t encrypt_block_size; } fota_candidate_config_t; /** @@ -95,7 +92,7 @@ const fota_candidate_config_t *fota_candidate_get_config(void); * \param[in] info iterate callback info. * \return FOTA_STATUS_SUCCESS on success. */ -typedef int (*fota_candidate_iterate_handler_t)(const fota_candidate_iterate_callback_info *info); +typedef int (*fota_candidate_iterate_handler_t)(fota_candidate_iterate_callback_info *info); /** * Iterate on candidate image. @@ -103,18 +100,41 @@ typedef int (*fota_candidate_iterate_handler_t)(const fota_candidate_iterate_cal * \param[in] validate optionally validate image on storage, could add significant time to validate candidate. * \param[in] force_encrypt force encryption. * \param[in] expected_comp_name expected component name. + * \param[in] install_alignment installer alignment in bytes. * \param[in] handler callback called on iteration start, each fragment and finish. * \return FOTA_STATUS_SUCCESS on success. */ int fota_candidate_iterate_image(bool validate, bool force_encrypt, const char *expected_comp_name, - fota_candidate_iterate_handler_t handler); + uint32_t install_alignment, fota_candidate_iterate_handler_t handler); + +/** + * Read candidate component ready header. + * + * \param[in,out] addr candidate header address. + * \param[in] bd_read_size bd read size. + * \param[in] bd_prog_size bd program size. + * \param[out] header candidate ready header. + * \return FOTA_STATUS_SUCCESS if found. + */ +int fota_candidate_read_candidate_ready_header(uint32_t *addr, uint32_t bd_read_size, uint32_t bd_prog_size, + fota_candidate_ready_header_t *header); + +/** + * Read candidate image header. + * + * \param[in,out] addr image header address. + * \param[in] bd_read_size bd read size. + * \param[in] bd_prog_size bd program size. + * \param[out] header image header info. + * \return FOTA_STATUS_SUCCESS if found. + */ +int fota_candidate_read_header(uint32_t *addr, uint32_t bd_read_size, uint32_t bd_prog_size, fota_header_info_t *header); /** * Erase current candidate. * * \return FOTA_STATUS_SUCCESS on success. */ - int fota_candidate_erase(void); #ifdef __cplusplus diff --git a/fota/fota_component.c b/fota/fota_component.c index ace904c..a05a029 100644 --- a/fota/fota_component.c +++ b/fota/fota_component.c @@ -20,6 +20,8 @@ #ifdef MBED_CLOUD_CLIENT_FOTA_ENABLE +#define TRACE_GROUP "FOTA" + #include "fota/fota_component.h" #include "fota/fota_component_internal.h" #include "fota/fota_status.h" @@ -27,31 +29,28 @@ #include #include -typedef struct { - fota_component_desc_t desc; - fota_component_version_t version; -} comp_entry_t; - static unsigned int num_components = 0; -static comp_entry_t comp_table[FOTA_NUM_COMPONENTS]; +static fota_component_desc_t comp_table[FOTA_NUM_COMPONENTS]; #define MAJOR_NUM_BITS 24 #define MINOR_NUM_BITS 24 #define SPLIT_NUM_BITS 16 #define MAX_VER 999 -void fota_component_init(void) +void fota_component_clean(void) { num_components = 0; memset(comp_table, 0, sizeof(comp_table)); } -int fota_component_add(const fota_component_desc_t *comp_desc) +int fota_component_add(const fota_component_desc_info_t *comp_desc_info, const char *comp_name, const char *comp_semver) { FOTA_ASSERT(num_components < FOTA_NUM_COMPONENTS); - FOTA_ASSERT(!(comp_desc->support_delta && (!comp_desc->curr_fw_get_digest || !comp_desc->curr_fw_read))); + FOTA_ASSERT(!(comp_desc_info->support_delta && (!comp_desc_info->curr_fw_get_digest || !comp_desc_info->curr_fw_read))); - memcpy(&comp_table[num_components].desc, comp_desc, sizeof(fota_component_desc_t)); + memcpy(&comp_table[num_components].desc_info, comp_desc_info, sizeof(*comp_desc_info)); + strncpy(comp_table[num_components].name, comp_name, FOTA_COMPONENT_MAX_NAME_SIZE); + fota_component_version_semver_to_int(comp_semver, &comp_table[num_components].version); num_components++; return FOTA_STATUS_SUCCESS; @@ -65,7 +64,7 @@ unsigned int fota_component_num_components(void) void fota_component_get_desc(unsigned int comp_id, const fota_component_desc_t * *comp_desc) { FOTA_ASSERT(comp_id < num_components) - *comp_desc = &comp_table[comp_id].desc; + *comp_desc = &comp_table[comp_id]; } void fota_component_get_curr_version(unsigned int comp_id, fota_component_version_t *version) @@ -82,12 +81,16 @@ void fota_component_set_curr_version(unsigned int comp_id, fota_component_versio int fota_component_name_to_id(const char *name, unsigned int *comp_id) { - for (unsigned int i = 0; i < num_components; i++) { - if (!strcmp(name, comp_table[i].desc.name)) { - *comp_id = i; + int i = num_components; + + // One or more components + do { + if (!strncmp(name, comp_table[num_components - i].name, FOTA_COMPONENT_MAX_NAME_SIZE)) { + *comp_id = num_components - i; return FOTA_STATUS_SUCCESS; } - } + } while (--i); + return FOTA_STATUS_NOT_FOUND; } @@ -116,25 +119,33 @@ int fota_component_version_int_to_semver(fota_component_version_t version, char int fota_component_version_semver_to_int(const char *sem_ver, fota_component_version_t *version) { - uint64_t major, minor, split; + // This better use signed strtol() instead of strtoul() as it is already used by other code + // and there is no need to add more dependencies here. That change saves ~120B. + int64_t major, minor, split; char *endptr; int ret = FOTA_STATUS_SUCCESS; - major = strtoul(sem_ver, &endptr, 10); - minor = strtoul(endptr + 1, &endptr, 10); - split = strtoul(endptr + 1, &endptr, 10); - FOTA_DBG_ASSERT((endptr-sem_ver) <= FOTA_COMPONENT_MAX_SEMVER_STR_SIZE); + major = strtol(sem_ver, &endptr, 10); + minor = strtol(endptr + 1, &endptr, 10); + split = strtol(endptr + 1, &endptr, 10); + FOTA_DBG_ASSERT((endptr - sem_ver) <= FOTA_COMPONENT_MAX_SEMVER_STR_SIZE); - if ((major > MAX_VER) || (minor > MAX_VER) || (split > MAX_VER)) { + if ((major < 0) || (major > MAX_VER) || + (minor < 0) || (minor > MAX_VER) || + (split < 0) || (split > MAX_VER)) { ret = FOTA_STATUS_INVALID_ARGUMENT; - } - split = MIN(split, MAX_VER); - minor = MIN(minor, MAX_VER); - major = MIN(major, MAX_VER); + // Unfortunately not all call sites of this handle the error, so this might as well + // give stable output on error path too. + *version = 0; + } else { - *version = split | minor << SPLIT_NUM_BITS | major << (SPLIT_NUM_BITS + MINOR_NUM_BITS); + split = MIN(split, MAX_VER); + minor = MIN(minor, MAX_VER); + major = MIN(major, MAX_VER); + *version = split | minor << SPLIT_NUM_BITS | major << (SPLIT_NUM_BITS + MINOR_NUM_BITS); + } return ret; } diff --git a/fota/fota_component.h b/fota/fota_component.h index bc22880..b04f627 100644 --- a/fota/fota_component.h +++ b/fota/fota_component.h @@ -31,7 +31,7 @@ extern "C" { /** * Callback to read current firmware, required only if delta supported. * - * \param[out] buf buffer with curr fw data + * \param[out] buf buffer with curr fw data. * \param[in] offset offset where to read from. * \param[in] size output buffer size. * \param[in] num_read actual size read. @@ -47,35 +47,52 @@ typedef int (*fota_component_curr_fw_read)(uint8_t *buf, uint32_t offset, uint32 */ typedef int (*fota_component_curr_fw_get_digest)(uint8_t *buf); +/** + * Callback called handle post install. + * + * \return FOTA_STATUS_SUCCESS on success. + */ +typedef int (*fota_component_post_install_handler_t)(const char *new_sem_ver); + /** * Component description info * - * name component name. - * factory_version initial version installed on factory in SemVer format. + * install_alignment If set to non-zero, fragment sizes returned to the user will be aligned to this value. * candidate_iterate_cb callback to candidate iterate firmware function. * support_delta if delta update supported for component. + * component_post_install_cb callback to for post install component check. * curr_fw_read callback to read current firmware. Required only if delta is supported for current component, NULL otherwise. * curr_fw_get_digest callback to get current firmware digest. Required only if delta is supported for current component, NULL otherwise. * need_reboot if reboot required after installation. */ typedef struct { - char name[FOTA_COMPONENT_MAX_NAME_SIZE]; - char factory_version[FOTA_COMPONENT_MAX_SEMVER_STR_SIZE]; + uint32_t install_alignment; fota_candidate_iterate_handler_t candidate_iterate_cb; + fota_component_post_install_handler_t component_post_install_cb; bool support_delta; fota_component_curr_fw_read curr_fw_read; fota_component_curr_fw_get_digest curr_fw_get_digest; bool need_reboot; -} fota_component_desc_t; +} fota_component_desc_info_t; /** * Component registration, adding to component database. * Component description should reside in text section to prevent unnecessary allocations and memory copies. * - * \param[in] comp_desc component description with required information. + * \param[in] comp_desc component description info with required information. + * \param[in] comp_name component name to add. + * \param[in] comp_semver component semver. * \return FOTA_STATUS_SUCCESS on success. */ -int fota_component_add(const fota_component_desc_t *comp_desc); +int fota_component_add(const fota_component_desc_info_t *comp_desc, const char *comp_name, const char *comp_semver); + +/** + * Convert internal FOTA library semantic version representation to human readable string. + * + * The version in internal FOTA library representation passed to fota_app_on_download_authorization() and + * candidate callback APIs. + */ +int fota_component_version_int_to_semver(fota_component_version_t version, char *sem_ver); #ifdef __cplusplus } diff --git a/fota/fota_component_internal.h b/fota/fota_component_internal.h index 5238118..dab0a05 100644 --- a/fota/fota_component_internal.h +++ b/fota/fota_component_internal.h @@ -26,8 +26,14 @@ extern "C" { #endif +typedef struct { + fota_component_desc_info_t desc_info; + fota_component_version_t version; + char name[FOTA_COMPONENT_MAX_NAME_SIZE]; +} fota_component_desc_t; + // Component access APIs -void fota_component_init(void); +void fota_component_clean(void); unsigned int fota_component_num_components(void); void fota_component_get_desc(unsigned int comp_id, const fota_component_desc_t * *comp_desc); void fota_component_get_curr_version(unsigned int comp_id, fota_component_version_t *version); @@ -36,7 +42,6 @@ void fota_component_set_curr_version(unsigned int comp_id, fota_component_versio int fota_component_name_to_id(const char *name, unsigned int *comp_id); // Semantic version translation -int fota_component_version_int_to_semver(fota_component_version_t version, char *sem_ver); int fota_component_version_semver_to_int(const char *sem_ver, fota_component_version_t *version); #ifdef __cplusplus diff --git a/fota/fota_config.h b/fota/fota_config.h index 214c15d..b57cd84 100644 --- a/fota/fota_config.h +++ b/fota/fota_config.h @@ -24,6 +24,18 @@ // skip this include in Bootloader and unittest builds as the configurations are delivered by other means #include "MbedCloudClientConfig.h" +#else // external configuration - unit tests + +#if !defined(MBED_CLOUD_CLIENT_FOTA_STORAGE_START_ADDR) +#define MBED_CLOUD_CLIENT_FOTA_STORAGE_START_ADDR 0 +#endif + +#if !defined(MBED_CLOUD_CLIENT_FOTA_STORAGE_SIZE) +#define MBED_CLOUD_CLIENT_FOTA_STORAGE_SIZE (1) +#endif + +#endif // defined(FOTA_UNIT_TEST) + #ifdef MBED_CLOUD_CLIENT_FOTA_ENABLE #ifndef MBED_CLOUD_CLIENT_FOTA_BLOCK_DEVICE_TYPE @@ -34,19 +46,103 @@ #error Storage size should be defined and have a nonzero value #endif -#endif // MBED_CLOUD_CLIENT_FOTA_ENABLE +#if !defined(FOTA_MANIFEST_SCHEMA_VERSION) +#define FOTA_MANIFEST_SCHEMA_VERSION 3 +#endif + +#if !defined(FOTA_MANIFEST_URI_SIZE) +#define FOTA_MANIFEST_URI_SIZE 256 +#endif -#else // external configuration - unit tests +#if !defined(FOTA_MANIFEST_VENDOR_DATA_SIZE) +#define FOTA_MANIFEST_VENDOR_DATA_SIZE 0 +#endif -#if !defined(MBED_CLOUD_CLIENT_FOTA_STORAGE_START_ADDR) -#define MBED_CLOUD_CLIENT_FOTA_STORAGE_START_ADDR 0 +#if !defined(FOTA_CERT_MAX_SIZE) +#define FOTA_CERT_MAX_SIZE 600 #endif -#if !defined(MBED_CLOUD_CLIENT_FOTA_STORAGE_SIZE) -#define MBED_CLOUD_CLIENT_FOTA_STORAGE_SIZE 0 +#if !defined(MBED_CLOUD_CLIENT_FOTA_CANDIDATE_BLOCK_SIZE) +#define MBED_CLOUD_CLIENT_FOTA_CANDIDATE_BLOCK_SIZE 1024 #endif -#endif // defined(FOTA_UNIT_TEST) +#if !(FOTA_MANIFEST_SCHEMA_VERSION == 1) +// Mainfest schema version #1 requires public key in x509 form +// Other cases require defaults to uncompressed elliptic curve +// point format (X9.62) +#define FOTA_USE_UPDATE_RAW_PUBLIC_KEY +#else +#define FOTA_USE_UPDATE_X509 +#endif + +#if (FOTA_MANIFEST_SCHEMA_VERSION < 3) +#define FOTA_SOURCE_LEGACY_OBJECTS_REPORT 1 + +#if !defined(FOTA_MANIFEST_MAX_SIZE) +#define FOTA_MANIFEST_MAX_SIZE 650 +#endif + +#else // (FOTA_MANIFEST_SCHEMA_VERSION < 3) +#define FOTA_SOURCE_LEGACY_OBJECTS_REPORT 0 +#endif // (FOTA_MANIFEST_SCHEMA_VERSION < 3) + +#if !defined(FOTA_MANIFEST_MAX_SIZE) +#define FOTA_MANIFEST_MAX_SIZE 580 +#endif + +#define FOTA_RESUME_UNSUPPORTED 0 +#define FOTA_RESUME_SUPPORT_RESTART 1 +#define FOTA_RESUME_SUPPORT_RESUME 2 + +#define FOTA_INTERNAL_FLASH_BD 1 +#define FOTA_CUSTOM_BD 2 +#define FOTA_EXTERNAL_BD 3 + +#ifndef MBED_CLOUD_CLIENT_FOTA_RESUME_SUPPORT +#define MBED_CLOUD_CLIENT_FOTA_RESUME_SUPPORT FOTA_RESUME_SUPPORT_RESUME +#endif + +#if !defined(MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION) +#define MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION 3 +#endif + +#if (MBED_CLOUD_CLIENT_FOTA_BLOCK_DEVICE_TYPE != FOTA_EXTERNAL_BD) +#ifndef __MBED__ +#error This type of block device is only supported in mbed-os +#endif +#endif + +#if (MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION >= 3) + +#define FOTA_HEADER_HAS_CANDIDATE_READY 1 + +#if !defined(MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT) +// set candidate encryption flag to false by default for internal flash +#if (MBED_CLOUD_CLIENT_FOTA_BLOCK_DEVICE_TYPE == FOTA_INTERNAL_FLASH_BD) +#define MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT 0 +#else +#define MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT 1 +#endif +#endif + +#else // LEGACY profile (MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION == 2) + +#define FOTA_HEADER_HAS_CANDIDATE_READY 0 + +#if !defined(MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT) +#define MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT 0 +#elif (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) +#error MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT enabled only for header version >= 3 +#endif // !defined(MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT) + +#if (MBED_CLOUD_CLIENT_FOTA_RESUME_SUPPORT == FOTA_RESUME_SUPPORT_RESUME) +// force resume restart for legacy profile +#undef MBED_CLOUD_CLIENT_FOTA_RESUME_SUPPORT +#define MBED_CLOUD_CLIENT_FOTA_RESUME_SUPPORT FOTA_RESUME_SUPPORT_RESTART +#endif + +#endif // (MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION >= 3) +#endif // MBED_CLOUD_CLIENT_FOTA_ENABLE #endif // __FOTA_CONFIG_H_ diff --git a/fota/fota_crypto.c b/fota/fota_crypto.c index 1522d1b..24a166b 100644 --- a/fota/fota_crypto.c +++ b/fota/fota_crypto.c @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -20,18 +20,37 @@ #ifdef MBED_CLOUD_CLIENT_FOTA_ENABLE +#define TRACE_GROUP "FOTA" + #include "fota/fota_crypto.h" #include "fota/fota_status.h" #include "fota/fota_crypto_defs.h" +#include "fota/fota_nvm.h" #include "mbedtls/sha256.h" #include "mbedtls/entropy.h" #include "mbedtls/ccm.h" #include "mbedtls/aes.h" -#include "mbedtls/asn1.h" +#include "mbedtls/platform_util.h" + +#if defined(FOTA_USE_UPDATE_RAW_PUBLIC_KEY) && defined(MBEDTLS_USE_TINYCRYPT) +#include "tinycrypt/ecc.h" +#include "tinycrypt/ecc_dsa.h" +#include "fota/fota_nvm.h" +#endif + +#if defined(FOTA_USE_UPDATE_RAW_PUBLIC_KEY) && defined(MBEDTLS_ECDSA_C) +#include "mbedtls/ecdsa.h" +#include "mbedtls/ecp.h" +#include "mbedtls/bignum.h" +#endif + +#if defined(FOTA_USE_UPDATE_X509) #include "mbedtls/x509_crt.h" +#include "mbedtls/x509.h" +#endif #include "mbedtls/pk.h" -#if defined(REMOVE_MBEDTLS_SSL_CONF_RNG) || (defined(FOTA_SIMULATE_RANDOM) && FOTA_SIMULATE_RANDOM) +#if defined(REMOVE_MBEDTLS_SSL_CONF_RNG) #undef MBEDTLS_SSL_CONF_RNG #endif @@ -42,17 +61,10 @@ #include #define HASH_KEY ((uint8_t *) "FotaHashMainKey.") -#define TAG_SIZE 8 #if !defined(MBEDTLS_SSL_CONF_RNG) static bool random_initialized = false; -#if defined(FOTA_SIMULATE_RANDOM) && FOTA_SIMULATE_RANDOM -static uint32_t random_seed_pos = 0; -static uint32_t random_seed_size = 0; -static uint8_t *random_seed = NULL; -#else static mbedtls_entropy_context entropy_ctx; -#endif #endif // !defined(MBEDTLS_SSL_CONF_RNG) typedef struct fota_hash_context_s { @@ -61,17 +73,12 @@ typedef struct fota_hash_context_s { typedef struct fota_encrypt_context_s { mbedtls_ccm_context ccm_ctx; - fota_encrypt_config_t config; - bool encrypt; - bool got_partial_block; - bool effective_block_size; uint64_t iv; } fota_encrypt_context_t; #define FOTA_TRACE_TLS_ERR(err) FOTA_TRACE_DEBUG("mbedTLS error %d", err) -int fota_encrypt_decrypt_start(fota_encrypt_context_t **ctx, const fota_encrypt_config_t *encrypt_config, - const uint8_t *key, uint32_t key_size, bool encrypt) +int fota_encrypt_decrypt_start(fota_encrypt_context_t **ctx, const uint8_t *key, uint32_t key_size) { FOTA_DBG_ASSERT(ctx); int ret; @@ -83,12 +90,8 @@ int fota_encrypt_decrypt_start(fota_encrypt_context_t **ctx, const fota_encrypt_ return FOTA_STATUS_OUT_OF_MEMORY; } - memcpy(&enc_ctx->config, encrypt_config, sizeof(fota_encrypt_config_t)); mbedtls_ccm_init(&enc_ctx->ccm_ctx); enc_ctx->iv = 0; - enc_ctx->encrypt = encrypt; - enc_ctx->got_partial_block = false; - enc_ctx->effective_block_size = 0; ret = mbedtls_ccm_setkey(&enc_ctx->ccm_ctx, MBEDTLS_CIPHER_ID_AES, key, key_size * 8); if (ret) { @@ -106,8 +109,6 @@ void fota_encryption_stream_reset(fota_encrypt_context_t *ctx) { FOTA_DBG_ASSERT(ctx); ctx->iv = 0; - ctx->got_partial_block = false; - ctx->effective_block_size = 0; } @@ -117,97 +118,24 @@ void fota_encryption_iv_increment(fota_encrypt_context_t *ctx) ctx->iv++; } -int fota_encryption_metadata_start(fota_encrypt_context_t *ctx, uint8_t *salt, uint32_t salt_len, - uint32_t fw_size, uint8_t *metadata, uint32_t metdata_buffer_size, - uint32_t *metadata_start_size, uint32_t *metadata_tags_size) -{ - FOTA_DBG_ASSERT(ctx); - FOTA_DBG_ASSERT(salt); - FOTA_DBG_ASSERT(salt_len == FOTA_ENCRYPT_METADATA_SALT_LEN); - FOTA_DBG_ASSERT(metdata_buffer_size >= FOTA_ENCRYPT_METADATA_START_SIZE); - FOTA_DBG_ASSERT(metadata); - FOTA_DBG_ASSERT(metadata_start_size); - FOTA_DBG_ASSERT(metadata_tags_size); - - uint32_t magic = FOTA_ENCRYPT_METADATA_MAGIC; - - uint32_t tags_size = (fw_size / ctx->config.encrypt_block_size); - tags_size *= TAG_SIZE; - if (fw_size % ctx->config.encrypt_block_size) { - tags_size += TAG_SIZE; - } - - // We need one additional tag for the fw header - tags_size += TAG_SIZE; - - memcpy(metadata, &magic, sizeof(magic)); - metadata += sizeof(magic); - - memcpy(metadata, &tags_size, sizeof(tags_size)); - metadata += sizeof(tags_size); - memcpy(metadata, salt, FOTA_ENCRYPT_METADATA_SALT_LEN); - - *metadata_start_size = FOTA_ENCRYPT_METADATA_START_SIZE; - *metadata_tags_size = tags_size; - - return FOTA_STATUS_SUCCESS; -} - -bool fota_encryption_metadata_parse(uint8_t *buffer, uint32_t buffer_len, - uint32_t *tags_size, uint8_t *salt, uint32_t salt_len) -{ - - if ((buffer_len < FOTA_ENCRYPT_METADATA_START_SIZE) || - (salt_len < FOTA_ENCRYPT_METADATA_SALT_LEN) || - (buffer == NULL) || (tags_size == NULL) || (salt == NULL)) { - return false; - } - - uint32_t magic; - - memcpy(&magic, buffer, sizeof(magic)); - if (magic != FOTA_ENCRYPT_METADATA_MAGIC) { - return false; - } - - buffer += sizeof(magic); - memcpy(tags_size, buffer, sizeof(*tags_size)); - buffer += sizeof(*tags_size); - memcpy(salt, buffer, FOTA_ENCRYPT_METADATA_SALT_LEN); - - return true; -} - int fota_encrypt_data( fota_encrypt_context_t *ctx, const uint8_t *in_buf, uint32_t buf_size, uint8_t *out_buf, - uint8_t *metadata_buf, uint32_t metadata_buf_size, uint32_t *metadata_actual_size) + uint8_t *tag) { FOTA_DBG_ASSERT(ctx); FOTA_DBG_ASSERT(in_buf); FOTA_DBG_ASSERT(out_buf); - FOTA_DBG_ASSERT(metadata_buf); - FOTA_DBG_ASSERT(metadata_actual_size); - FOTA_DBG_ASSERT(ctx->encrypt); - FOTA_DBG_ASSERT(metadata_buf_size >= TAG_SIZE); - FOTA_DBG_ASSERT(buf_size <= ctx->config.encrypt_block_size); + FOTA_DBG_ASSERT(tag); int ret; - // Make sure partial blocks are only received once at the end - FOTA_DBG_ASSERT(!ctx->got_partial_block); - if (!ctx->effective_block_size) { - ctx->effective_block_size = buf_size; - } else if (buf_size < ctx->effective_block_size) { - ctx->got_partial_block = true; - } - ret = mbedtls_ccm_encrypt_and_tag( &ctx->ccm_ctx, buf_size, (const unsigned char *) &ctx->iv, sizeof(ctx->iv), NULL, 0, in_buf, out_buf, - metadata_buf, TAG_SIZE); + tag, FOTA_ENCRYPT_TAG_SIZE); if (ret) { FOTA_TRACE_TLS_ERR(ret); @@ -215,7 +143,6 @@ int fota_encrypt_data( } fota_encryption_iv_increment(ctx); - *metadata_actual_size = TAG_SIZE; return FOTA_STATUS_SUCCESS; } @@ -223,14 +150,12 @@ int fota_encrypt_data( int fota_decrypt_data( fota_encrypt_context_t *ctx, const uint8_t *in_buf, uint32_t buf_size, uint8_t *out_buf, - uint8_t *metadata_buf, uint32_t metadata_buf_size) + uint8_t *tag) { FOTA_DBG_ASSERT(ctx); FOTA_DBG_ASSERT(in_buf); FOTA_DBG_ASSERT(out_buf); - FOTA_DBG_ASSERT(metadata_buf); - FOTA_DBG_ASSERT(!(ctx->encrypt)); - FOTA_DBG_ASSERT(metadata_buf_size >= TAG_SIZE); + FOTA_DBG_ASSERT(tag); int ret; ret = mbedtls_ccm_auth_decrypt( @@ -238,7 +163,7 @@ int fota_decrypt_data( (const unsigned char *) &ctx->iv, sizeof(ctx->iv), NULL, 0, in_buf, out_buf, - metadata_buf, TAG_SIZE); + tag, FOTA_ENCRYPT_TAG_SIZE); if (ret) { FOTA_TRACE_TLS_ERR(ret); @@ -308,7 +233,7 @@ int fota_hash_result(fota_hash_context_t *ctx, uint8_t *hash_buf) return FOTA_STATUS_SUCCESS; } -int fota_hash_finish(fota_hash_context_t **ctx) +void fota_hash_finish(fota_hash_context_t **ctx) { FOTA_DBG_ASSERT(ctx); if (*ctx) { @@ -316,27 +241,13 @@ int fota_hash_finish(fota_hash_context_t **ctx) free(*ctx); *ctx = NULL; } - - return FOTA_STATUS_SUCCESS; } int fota_random_init(const uint8_t *seed, uint32_t seed_size) { #if !defined(MBEDTLS_SSL_CONF_RNG) if (!random_initialized) { -#if defined(FOTA_SIMULATE_RANDOM) && FOTA_SIMULATE_RANDOM - FOTA_DBG_ASSERT(seed); - FOTA_DBG_ASSERT(seed_size); - random_seed_pos = 0; - random_seed_size = seed_size; - random_seed = (uint8_t *) malloc(random_seed_size); - if (!random_seed) { - return FOTA_STATUS_OUT_OF_MEMORY; - } - memcpy(random_seed, seed, random_seed_size); -#else mbedtls_entropy_init(&entropy_ctx); -#endif random_initialized = true; } #endif // !defined(MBEDTLS_SSL_CONF_RNG) @@ -348,18 +259,11 @@ int fota_gen_random(uint8_t *buf, uint32_t buf_size) { FOTA_DBG_ASSERT(random_initialized); -#if defined(FOTA_SIMULATE_RANDOM) && FOTA_SIMULATE_RANDOM - for (uint32_t i = 0; i < buf_size; i++) { - buf[i] = random_seed[random_seed_pos] + (uint8_t) i; - random_seed_pos = (random_seed_pos + 1) % random_seed_size; - } -#else int ret = mbedtls_entropy_func(&entropy_ctx, buf, buf_size); if (ret) { FOTA_TRACE_TLS_ERR(ret); return FOTA_STATUS_INTERNAL_CRYPTO_ERROR; } -#endif return FOTA_STATUS_SUCCESS; } #else @@ -378,61 +282,19 @@ int fota_random_deinit(void) { #if !defined(MBEDTLS_SSL_CONF_RNG) if (random_initialized) { -#if defined(FOTA_SIMULATE_RANDOM) && FOTA_SIMULATE_RANDOM - free(random_seed); -#else mbedtls_entropy_free(&entropy_ctx); -#endif random_initialized = false; } #endif // !defined(MBEDTLS_SSL_CONF_RNG) return FOTA_STATUS_SUCCESS; } -int fota_get_derived_key(const uint8_t *key, size_t key_size, const uint8_t *input, size_t input_size, - uint8_t *derived_key) -{ - uint8_t sha256_buf[FOTA_CRYPTO_HASH_SIZE]; - int ret; - - /* We will only be using 128 bits secret key for key derivation. - * Larger input keys will be truncated to 128 bit length */ - FOTA_DBG_ASSERT(key_size >= FOTA_ENCRYPT_KEY_SIZE); - - ret = mbedtls_sha256_ret(input, input_size, sha256_buf, 0); - if (ret) { - FOTA_TRACE_TLS_ERR(ret); - return FOTA_STATUS_INTERNAL_CRYPTO_ERROR; - } - - mbedtls_aes_context ctx = {0}; - mbedtls_aes_init(&ctx); - - ret = mbedtls_aes_setkey_enc(&ctx, key, key_size * 8); - if (ret) { - FOTA_TRACE_TLS_ERR(ret); - return FOTA_STATUS_INTERNAL_CRYPTO_ERROR; - } - - /* Encrypting only first 128 bits, the reset is discarded */ - ret = mbedtls_aes_crypt_ecb(&ctx, MBEDTLS_AES_ENCRYPT, sha256_buf, derived_key); - if (ret) { - FOTA_TRACE_TLS_ERR(ret); - return FOTA_STATUS_INTERNAL_CRYPTO_ERROR; - } - - mbedtls_aes_free(&ctx); - - return FOTA_STATUS_SUCCESS; -} - +#if FOTA_FI_MITIGATION_ENABLE int fota_fi_memcmp(const uint8_t *ptr1, const uint8_t *ptr2, size_t num, volatile size_t *loop_check) { volatile int is_diff = 0; - uint16_t start_pos = 0; volatile size_t pos; - fota_gen_random((uint8_t *)&start_pos, sizeof(start_pos)); - start_pos %= num; + uint32_t start_pos = mbedtls_platform_random_in_range(num); for (*loop_check = 0; *loop_check < num; (*loop_check)++) { pos = (*loop_check + start_pos) % num; @@ -440,173 +302,269 @@ int fota_fi_memcmp(const uint8_t *ptr1, const uint8_t *ptr2, size_t num, volatil } return is_diff; } +#endif // #if FOTA_FI_MITIGATION_ENABLE -int fota_random_delay(void) +#if defined(FOTA_USE_UPDATE_RAW_PUBLIC_KEY) && defined(MBEDTLS_USE_TINYCRYPT) +int fota_verify_signature_prehashed( + const uint8_t *data_digest, + const uint8_t *sig, size_t sig_len +) { - uint8_t spin_count; - volatile int i = 0; - // generate a random delay - int ret = fota_gen_random((uint8_t *)&spin_count, sizeof(spin_count)); + uint8_t public_key[FOTA_UPDATE_RAW_PUBLIC_KEY_SIZE]; + int ret = fota_nvm_get_update_public_key(public_key); if (ret) { + FOTA_TRACE_ERROR("Failed to get public key"); return ret; } - spin_count = spin_count % 100; -start: - for (i = 0; i < spin_count; ++i) { } // spin delay + ret = uECC_verify( + public_key + 1, // +1 for dropping the compression byte + data_digest, FOTA_CRYPTO_HASH_SIZE, + sig + ); - // FI mitigation - if (i < spin_count) { - goto start; - } + FOTA_FI_SAFE_COND(!ret, FOTA_STATUS_MANIFEST_SIGNATURE_INVALID, "Failed to uECC_verify"); + + FOTA_TRACE_DEBUG("uECC_verify passed"); return FOTA_STATUS_SUCCESS; + +fail: + + return ret; } +#endif -int fota_verify_signature( - const uint8_t *signed_data, size_t signed_data_size, - const uint8_t *sig, size_t sig_len, - mbedtls_x509_crt *cert +#if defined(FOTA_USE_UPDATE_RAW_PUBLIC_KEY) && defined(MBEDTLS_ECDSA_C) +int fota_verify_signature_prehashed( + const uint8_t *data_digest, + const uint8_t *sig, size_t sig_len ) { - uint8_t digest[FOTA_CRYPTO_HASH_SIZE] = {0}; - mbedtls_sha256_context sha256_ctx = {0}; - mbedtls_sha256_init(&sha256_ctx); + uint8_t public_key[FOTA_UPDATE_RAW_PUBLIC_KEY_SIZE]; + int ret = FOTA_STATUS_INTERNAL_ERROR; + int tmp_ret = fota_nvm_get_update_public_key(public_key); + if (tmp_ret) { + FOTA_TRACE_ERROR("Failed to get public key %d", tmp_ret); + return tmp_ret; + } + + mbedtls_ecp_group ecp_group; + mbedtls_ecp_point Q; + size_t curve_bytes; + mbedtls_mpi r, s; + + mbedtls_mpi_init(&r); + mbedtls_mpi_init(&s); + mbedtls_ecp_point_init(&Q); + mbedtls_ecp_group_init(&ecp_group); + + tmp_ret = mbedtls_ecp_group_load( + &ecp_group, + MBEDTLS_ECP_DP_SECP256R1); + FOTA_TRACE_DEBUG("mbedtls_ecp_group_load returned %d", tmp_ret); + + if (tmp_ret) { + FOTA_TRACE_ERROR("Failed to load ecp group"); + ret = FOTA_STATUS_INTERNAL_CRYPTO_ERROR; + goto fail; + } - mbedtls_pk_context *pk_ctx_ptr = NULL; + curve_bytes = FOTA_IMAGE_RAW_SIGNATURE_SIZE / 2; - int fota_status = FOTA_STATUS_INTERNAL_ERROR; - volatile int tls_status; - int tmp_status; + FOTA_DBG_ASSERT(sig_len == 2 * curve_bytes); -// supporting both cripto lib api -#ifdef MBEDTLS_X509_ON_DEMAND_PARSING - mbedtls_pk_context pk_ctx; - pk_ctx_ptr = &pk_ctx; - mbedtls_pk_init(pk_ctx_ptr); - tls_status = mbedtls_x509_crt_get_pk(cert, pk_ctx_ptr); - if (tls_status) { + tmp_ret = mbedtls_mpi_read_binary(&r, + sig, + curve_bytes); + FOTA_TRACE_DEBUG("mbedtls_mpi_read_binary r returned %d", tmp_ret); + + if (tmp_ret) { + FOTA_TRACE_ERROR("mbedtls_mpi_read_binary"); + ret = FOTA_STATUS_INTERNAL_CRYPTO_ERROR; goto fail; } -#else - pk_ctx_ptr = &cert->pk; -#endif - tls_status = mbedtls_sha256_starts_ret(&sha256_ctx, 0); + tmp_ret = mbedtls_mpi_read_binary(&s, + sig + curve_bytes, + curve_bytes); + FOTA_TRACE_DEBUG("mbedtls_mpi_read_binary s returned %d", tmp_ret); - if (tls_status) { - goto fail; - } - tls_status = mbedtls_sha256_update_ret(&sha256_ctx, signed_data, signed_data_size); - if (tls_status) { + if (tmp_ret) { + FOTA_TRACE_ERROR("mbedtls_mpi_read_binary"); + ret = FOTA_STATUS_INTERNAL_CRYPTO_ERROR; goto fail; } - tls_status = mbedtls_sha256_finish_ret(&sha256_ctx, digest); - if (tls_status) { + tmp_ret = mbedtls_ecp_point_read_binary(&ecp_group, + &Q, + public_key, + FOTA_UPDATE_RAW_PUBLIC_KEY_SIZE); + + FOTA_TRACE_DEBUG("mbedtls_ecp_point_read_binary returned %d", tmp_ret); + + if (tmp_ret) { + FOTA_TRACE_ERROR("Failed to mbedtls_ecp_point_read_binary public key"); + ret = FOTA_STATUS_INTERNAL_CRYPTO_ERROR; goto fail; } - tls_status = mbedtls_pk_verify( - pk_ctx_ptr, MBEDTLS_MD_SHA256, - digest, sizeof(digest), - sig, sig_len); + tmp_ret = mbedtls_ecdsa_verify( + &ecp_group, + data_digest, FOTA_CRYPTO_HASH_SIZE, + &Q, + &r, &s + ); - if (tls_status) { - FOTA_TRACE_ERROR("Manifest signature verification failed (%d)", tls_status); - fota_status = FOTA_STATUS_MANIFEST_SIGNATURE_INVALID; + FOTA_FI_SAFE_COND(!tmp_ret, FOTA_STATUS_MANIFEST_SIGNATURE_INVALID, "Failed to verify signature"); + + FOTA_TRACE_DEBUG("mbedtls_ecdsa_verify passed"); + + ret = FOTA_STATUS_SUCCESS; + +fail: + + mbedtls_ecp_group_free(&ecp_group); + mbedtls_ecp_point_free(&Q); + mbedtls_mpi_free(&s); + mbedtls_mpi_free(&r); + + return ret; + +} +#endif + +#if defined(FOTA_USE_UPDATE_X509) +int fota_verify_signature_prehashed( + const uint8_t *data_digest, + const uint8_t *sig, size_t sig_len +) +{ + int ret; + int fota_status = FOTA_STATUS_INTERNAL_ERROR; + uint8_t *update_crt_data; + mbedtls_pk_context *pk_ctx_ptr; + size_t update_crt_size; + mbedtls_x509_crt crt; +#if defined(MBEDTLS_X509_ON_DEMAND_PARSING) + mbedtls_pk_context pk_ctx; +#endif + update_crt_data = (uint8_t *)malloc(FOTA_CERT_MAX_SIZE); + if (!update_crt_data) { + FOTA_TRACE_ERROR("Failed to allocate storage for update certificate"); + fota_status = FOTA_STATUS_OUT_OF_MEMORY; goto fail; } - // FI mitigation - re-evaluating if to make sure FI are harder to implement - tmp_status = fota_random_delay(); - if (tmp_status) { - fota_status = tmp_status; + ret = fota_nvm_get_update_certificate( + update_crt_data, FOTA_CERT_MAX_SIZE, + &update_crt_size + ); + if (ret) { + fota_status = ret; + FOTA_TRACE_ERROR("Failed to get update certificate %d", ret); goto fail; } - if (tls_status) { - FOTA_TRACE_ERROR("Manifest signature verification failed (%d)", tls_status); - fota_status = FOTA_STATUS_MANIFEST_SIGNATURE_INVALID; + mbedtls_x509_crt_init(&crt); + + ret = mbedtls_x509_crt_parse_der_nocopy( + &crt, + update_crt_data, update_crt_size + ); + if (ret) { + FOTA_TRACE_ERROR("Failed to parse update certificate %d", ret); + if (ret == MBEDTLS_ERR_X509_ALLOC_FAILED) { + fota_status = FOTA_STATUS_OUT_OF_MEMORY; + } else { + fota_status = FOTA_STATUS_INTERNAL_CRYPTO_ERROR; + } goto fail; } - // FI mitigation - re-evaluating if to make sure FI are harder to implement - tmp_status = fota_random_delay(); - if (tmp_status) { - fota_status = tmp_status; + // supporting both crypto lib api +#if defined(MBEDTLS_X509_ON_DEMAND_PARSING) + pk_ctx_ptr = &pk_ctx; + mbedtls_pk_init(pk_ctx_ptr); + ret = mbedtls_x509_crt_get_pk(&crt, pk_ctx_ptr); + if (ret) { + FOTA_TRACE_ERROR("Failed to extract public key from certificate %d", ret); + fota_status = FOTA_STATUS_INTERNAL_CRYPTO_ERROR; goto fail; } +#else + pk_ctx_ptr = &crt.pk; +#endif - // re-evaluating if to make sure FI are harder to implement - if (tls_status) { + ret = mbedtls_pk_verify( + pk_ctx_ptr, MBEDTLS_MD_SHA256, + data_digest, FOTA_CRYPTO_HASH_SIZE, + sig, sig_len + ); + // todo FI check + if (ret) { + FOTA_TRACE_ERROR("Manifest signature verification failed (%d)", ret); fota_status = FOTA_STATUS_MANIFEST_SIGNATURE_INVALID; goto fail; } fota_status = FOTA_STATUS_SUCCESS; fail: - if (tls_status) { - FOTA_TRACE_ERROR("mbedtls failure %d", tls_status); - } #ifdef MBEDTLS_X509_ON_DEMAND_PARSING mbedtls_pk_free(pk_ctx_ptr); #endif - mbedtls_sha256_free(&sha256_ctx); + mbedtls_x509_crt_free(&crt); + free(update_crt_data); return fota_status; } +#endif // defined(FOTA_USE_UPDATE_X509) -/*----------------------------mbedtls patch-----------------------------------*/ -int mbedtls_asn1_get_enumerated_value(unsigned char **p, - const unsigned char *end, - int *val) +int fota_verify_signature( + const uint8_t *signed_data, size_t signed_data_size, + const uint8_t *sig, size_t sig_len +) { - int ret; - size_t len; + uint8_t digest[FOTA_CRYPTO_HASH_SIZE] = {0}; + mbedtls_sha256_context sha256_ctx = {0}; + mbedtls_sha256_init(&sha256_ctx); - if ((ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_ENUMERATED)) != 0) { - return (ret); - } + int ret = FOTA_STATUS_INTERNAL_ERROR; + int status; - if (len == 0 || len > sizeof(int) || (**p & 0x80) != 0) { - return (MBEDTLS_ERR_ASN1_INVALID_LENGTH); + status = mbedtls_sha256_starts_ret(&sha256_ctx, 0); + if (status) { + goto fail; } - *val = 0; - - while (len-- > 0) { - *val = (*val << 8) | **p; - (*p)++; + status = mbedtls_sha256_update_ret(&sha256_ctx, signed_data, signed_data_size); + if (status) { + mbedtls_sha256_free(&sha256_ctx); + goto fail; } - return (0); -} - -int mbedtls_asn1_get_int64(unsigned char **p, - const unsigned char *end, - int64_t *val) -{ - int ret; - size_t len; - - if ((ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_INTEGER)) != 0) { - return (ret); + status = mbedtls_sha256_finish_ret(&sha256_ctx, digest); + mbedtls_sha256_free(&sha256_ctx); + if (status) { + goto fail; } - if (len == 0 || len > sizeof(int64_t) || (**p & 0x80) != 0) { - return (MBEDTLS_ERR_ASN1_INVALID_LENGTH); - } + ret = fota_verify_signature_prehashed( + digest, + sig, sig_len + ); - *val = 0; + FOTA_FI_SAFE_COND( + ret == FOTA_STATUS_SUCCESS, + ret, + "Manifest signature verification failed" + ); - while (len-- > 0) { - *val = (*val << 8) | **p; - (*p)++; - } + ret = FOTA_STATUS_SUCCESS; - return (0); +fail: + return ret; } #endif // MBED_CLOUD_CLIENT_FOTA_ENABLE diff --git a/fota/fota_crypto.h b/fota/fota_crypto.h index b1ea676..4d076cb 100644 --- a/fota/fota_crypto.h +++ b/fota/fota_crypto.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -26,30 +26,9 @@ extern "C" { #endif -#define MBEDTLS_ASN1_ENUMERATED 0x0A - -/* - Encryption Metadata structure - +++++++++++++++++++++++++++++++++++++++ - + ENCRYPTION_METADATA_MAGIC (4 bytes) + - +++++++++++++++++++++++++++++++++++++++ - + Tags area length (4 bytes) + - +++++++++++++++++++++++++++++++++++++++ - + Salt (16 Bytes) + - +++++++++++++++++++++++++++++++++++++++ - + Tags + - + Tags + - + Tags + - + Tags + - +++++++++++++++++++++++++++++++++++++++ -*/ - - - typedef struct fota_encrypt_context_s fota_encrypt_context_t; -int fota_encrypt_decrypt_start(fota_encrypt_context_t **ctx, const fota_encrypt_config_t *encrypt_config, - const uint8_t *key, uint32_t key_size, bool encrypt); +int fota_encrypt_decrypt_start(fota_encrypt_context_t **ctx, const uint8_t *key, uint32_t key_size); // reset stream // reset iv and buffering states @@ -57,21 +36,14 @@ void fota_encryption_stream_reset(fota_encrypt_context_t *ctx); void fota_encryption_iv_increment(fota_encrypt_context_t *ctx); -int fota_encryption_metadata_start(fota_encrypt_context_t *ctx, uint8_t *salt, uint32_t salt_len, - uint32_t fw_size, uint8_t *metadata, uint32_t metdata_buffer_size, - uint32_t *metadata_start_size, uint32_t *metadata_tags_size); -// used in bootloader and tests -bool fota_encryption_metadata_parse(uint8_t *buffer, uint32_t buffer_len, - uint32_t *tags_size, uint8_t *salt, uint32_t salt_len); - int fota_encrypt_data( fota_encrypt_context_t *ctx, const uint8_t *in_buf, uint32_t buf_size, uint8_t *out_buf, - uint8_t *metadata_buf, uint32_t metadata_buf_size, uint32_t *metadata_actual_size); + uint8_t *tag); int fota_decrypt_data( fota_encrypt_context_t *ctx, const uint8_t *in_buf, uint32_t buf_size, uint8_t *out_buf, - uint8_t *metadata_buf, uint32_t metadata_buf_size); + uint8_t *tag); int fota_encrypt_finalize(fota_encrypt_context_t **ctx); typedef struct fota_hash_context_s fota_hash_context_t; @@ -79,93 +51,80 @@ typedef struct fota_hash_context_s fota_hash_context_t; int fota_hash_start(fota_hash_context_t **ctx); int fota_hash_update(fota_hash_context_t *ctx, const uint8_t *buf, uint32_t buf_size); int fota_hash_result(fota_hash_context_t *ctx, uint8_t *hash_buf); -int fota_hash_finish(fota_hash_context_t **ctx); +void fota_hash_finish(fota_hash_context_t **ctx); int fota_random_init(const uint8_t *seed, uint32_t seed_size); int fota_gen_random(uint8_t *buf, uint32_t buf_size); int fota_random_deinit(void); -int fota_get_derived_key(const uint8_t *key, size_t key_size, const uint8_t *input, size_t input_size, - uint8_t *derived_key); -// FI mitigation APIs -int fota_random_delay(void); +#if FOTA_FI_MITIGATION_ENABLE + // TODO: check if should return volatile int fota_fi_memcmp(const uint8_t *ptr1, const uint8_t *ptr2, size_t num, volatile size_t *loop_check); -#if defined(FOTA_FI_MITIGATION_ENABLE) && FOTA_FI_MITIGATION_ENABLE +#include "mbedtls/platform_util.h" // This handles a a fault injection safe condition - desired condition tested 3 times with random delay between checks // (to prevent power glitch attacks). // In case of a bad case scenario, error message is displayed (if not null), variable ret (must exist) is filled with RET // and we jump to label "fail", which must exist. -#define FOTA_FI_SAFE_COND(DESIRED_COND, RET, MSG) \ +#define FOTA_FI_SAFE_COND(DESIRED_COND, RET, MSG, ...) \ do { \ if (!(DESIRED_COND)) { \ - if (MSG) { \ - FOTA_TRACE_ERROR(MSG); \ - } \ - ret = RET; \ - goto fail; \ - } \ - fota_random_delay(); \ - if (!(DESIRED_COND)) { \ - if (MSG) { \ - FOTA_TRACE_ERROR(MSG); \ - } \ + FOTA_TRACE_ERROR(MSG, ##__VA_ARGS__); \ ret = RET; \ goto fail; \ } \ - fota_random_delay(); \ + mbedtls_platform_random_delay(); \ if (!(DESIRED_COND)) { \ - if (MSG) { \ - FOTA_TRACE_ERROR(MSG); \ - } \ + FOTA_TRACE_ERROR(MSG, ##__VA_ARGS__); \ ret = RET; \ goto fail; \ } \ } while (0) // specific case, safe memcmp (desired condition is equal strings) -#define FOTA_FI_SAFE_MEMCMP(PTR1, PTR2, NUM, RET, MSG) \ +#define FOTA_FI_SAFE_MEMCMP(PTR1, PTR2, NUM, RET, MSG, ...) \ do { \ size_t volatile loop_check; \ - FOTA_FI_SAFE_COND((!fota_fi_memcmp((PTR1), (PTR2), (NUM), &loop_check) && (loop_check == (NUM))), RET, MSG); \ + FOTA_FI_SAFE_COND((!fota_fi_memcmp((PTR1), (PTR2), (NUM), &loop_check) && (loop_check == (NUM))), RET, MSG, ##__VA_ARGS__); \ } while (0) #else // no FI support // No FI mitigation, simple handling -#define FOTA_FI_SAFE_COND(DESIRED_COND, RET, MSG) \ +#define FOTA_FI_SAFE_COND(DESIRED_COND, RET, MSG, ...) \ do { \ if (!(DESIRED_COND)) { \ - if (MSG) { \ - FOTA_TRACE_ERROR(MSG); \ - } \ + FOTA_TRACE_ERROR(MSG, ##__VA_ARGS__); \ ret = RET; \ goto fail; \ } \ } while (0) // specific case, regular memcmp (desired condition is equal strings) -#define FOTA_FI_SAFE_MEMCMP(PTR1, PTR2, NUM, RET, MSG) \ - FOTA_FI_SAFE_COND(!memcmp((PTR1), (PTR2), (NUM)), RET, MSG) +#define FOTA_FI_SAFE_MEMCMP(PTR1, PTR2, NUM, RET, MSG, ...) \ + FOTA_FI_SAFE_COND(!memcmp((PTR1), (PTR2), (NUM)), RET, MSG, ##__VA_ARGS__) -#endif // FI +static inline int fota_fi_memcmp(const uint8_t *ptr1, const uint8_t *ptr2, size_t num, volatile size_t *loop_check) +{ + *loop_check = num; + return memcmp(ptr1, ptr2, num); +} +#endif // #if FOTA_FI_MITIGATION_ENABLE -int mbedtls_asn1_get_enumerated_value(unsigned char **p, - const unsigned char *end, - int *val); -int mbedtls_asn1_get_int64(unsigned char **p, - const unsigned char *end, - int64_t *val); -typedef struct mbedtls_x509_crt mbedtls_x509_crt; int fota_verify_signature( const uint8_t *signed_data, size_t signed_data_size, - const uint8_t *sig, size_t sig_len, - mbedtls_x509_crt *cert + const uint8_t *sig, size_t sig_len ); +int fota_verify_signature_prehashed( + const uint8_t *data_digest, + const uint8_t *sig, size_t sig_len +); + + #ifdef __cplusplus } #endif diff --git a/fota/fota_crypto_asn_extra.c b/fota/fota_crypto_asn_extra.c new file mode 100644 index 0000000..92696eb --- /dev/null +++ b/fota/fota_crypto_asn_extra.c @@ -0,0 +1,70 @@ +// ---------------------------------------------------------------------------- +// Copyright 2018-2020 ARM Ltd. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------- +#include "fota/fota_crypto_asn_extra.h" +#include "mbedtls/asn1.h" +#include + +int mbedtls_asn1_get_enumerated_value(unsigned char **p, + const unsigned char *end, + int *val) +{ + int ret; + size_t len; + + if ((ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_ENUMERATED)) != 0) { + return (ret); + } + + if (len == 0 || len > sizeof(int) || (**p & 0x80) != 0) { + return (MBEDTLS_ERR_ASN1_INVALID_LENGTH); + } + + *val = 0; + + while (len-- > 0) { + *val = (*val << 8) | **p; + (*p)++; + } + + return (0); +} + +int mbedtls_asn1_get_int64(unsigned char **p, + const unsigned char *end, + int64_t *val) +{ + int ret; + size_t len; + + if ((ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_INTEGER)) != 0) { + return (ret); + } + + if (len == 0 || len > sizeof(int64_t) || (**p & 0x80) != 0) { + return (MBEDTLS_ERR_ASN1_INVALID_LENGTH); + } + + *val = 0; + + while (len-- > 0) { + *val = (*val << 8) | **p; + (*p)++; + } + + return (0); +} diff --git a/fota/fota_crypto_asn_extra.h b/fota/fota_crypto_asn_extra.h new file mode 100644 index 0000000..39e1752 --- /dev/null +++ b/fota/fota_crypto_asn_extra.h @@ -0,0 +1,33 @@ +// ---------------------------------------------------------------------------- +// Copyright 2018-2020 ARM Ltd. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------- + +#ifndef __FOTA_CRYPTO_ASN_EXTRA_H_ +#define __FOTA_CRYPTO_ASN_EXTRA_H_ + +#include + +#define MBEDTLS_ASN1_ENUMERATED 0x0A + +int mbedtls_asn1_get_enumerated_value(unsigned char **p, + const unsigned char *end, + int *val); +int mbedtls_asn1_get_int64(unsigned char **p, + const unsigned char *end, + int64_t *val); + +#endif // __FOTA_CRYPTO_ASN_EXTRA_H_ diff --git a/fota/fota_crypto_defs.h b/fota/fota_crypto_defs.h index 4953557..78f4b9d 100644 --- a/fota/fota_crypto_defs.h +++ b/fota/fota_crypto_defs.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -28,22 +28,12 @@ extern "C" { #define FOTA_ENCRYPT_KEY_SIZE 16 /*< AES-128 key size in bytes */ -#define FOTA_ENCRYPT_METADATA_MAX_SIZE 8 /*< AES-CCM tag size in bytes */ - -#define FOTA_ENCRYPT_METADATA_START_SIZE 24 -#define FOTA_ENCRYPT_METADATA_MAGIC ((uint32_t)(0x4a6ba649)) -#define FOTA_ENCRYPT_METADATA_SALT_LEN FOTA_ENCRYPT_KEY_SIZE +#define FOTA_ENCRYPT_TAG_SIZE 8 /*< AES-CCM tag size in bytes */ #define FOTA_CRYPTO_HASH_SIZE 32 /*< SHA256 digest size in bytes*/ -#if !defined(MBED_CLOUD_CLIENT_FOTA_ENCRYPT_BLOCK_SIZE) -/* Encryption block size used for encrypting FW candidate */ -#define MBED_CLOUD_CLIENT_FOTA_ENCRYPT_BLOCK_SIZE 1024 -#endif - -typedef struct { - uint32_t encrypt_block_size; -} fota_encrypt_config_t; +#define FOTA_UPDATE_RAW_PUBLIC_KEY_SIZE 65 // compression byte | r | s +#define FOTA_IMAGE_RAW_SIGNATURE_SIZE 64 // raw signature #ifdef __cplusplus } diff --git a/fota/fota_curr_fw.c b/fota/fota_curr_fw.c index f637958..3aace81 100644 --- a/fota/fota_curr_fw.c +++ b/fota/fota_curr_fw.c @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -20,14 +20,15 @@ #ifdef MBED_CLOUD_CLIENT_FOTA_ENABLE +#define TRACE_GROUP "FOTA" + #include "fota/fota_curr_fw.h" #include "fota/fota_status.h" #include -// Bootloader and application have different defines - +#if !defined(FOTA_CUSTOM_CURR_FW_STRUCTURE) || (!FOTA_CUSTOM_CURR_FW_STRUCTURE) #if defined(__MBED__) - +// Bootloader and application have different defines #if !defined(APPLICATION_ADDR) #if defined(MBED_CONF_MBED_BOOTLOADER_APPLICATION_START_ADDRESS) #define APPLICATION_ADDR MBED_CONF_MBED_BOOTLOADER_APPLICATION_START_ADDRESS @@ -36,7 +37,7 @@ #else #error Application start address not defined #endif -#endif +#endif // !defined(APPLICATION_ADDR) #if !defined(HEADER_ADDR) #if defined(MBED_CONF_MBED_BOOTLOADER_APPLICATION_HEADER_ADDRESS) @@ -46,14 +47,8 @@ #else #error Header start address not defined #endif -#endif - -#endif // defined(__MBED__) - - -#if !defined(FOTA_CUSTOM_CURR_FW_STRUCTURE) || (!FOTA_CUSTOM_CURR_FW_STRUCTURE) +#endif // !defined(HEADER_ADDR) -#if defined(__MBED__) // The following two functions should be overridden in the non mbed-os cases. uint8_t *fota_curr_fw_get_app_start_addr(void) @@ -80,12 +75,6 @@ uint8_t *fota_curr_fw_get_app_header_addr(void) #endif // defined(__MBED__) -int fota_curr_fw_read_header(fota_header_info_t *header_info) -{ - uint8_t *header_in_curr_fw = (uint8_t *) fota_curr_fw_get_app_header_addr(); - return fota_deserialize_header(header_in_curr_fw, fota_get_header_size(), header_info); -} - int fota_curr_fw_read(uint8_t *buf, uint32_t offset, uint32_t size, uint32_t *num_read) { fota_header_info_t header_info; @@ -110,6 +99,18 @@ int fota_curr_fw_read(uint8_t *buf, uint32_t offset, uint32_t size, uint32_t *nu } +int fota_curr_fw_get_digest(uint8_t *buf) +{ + fota_header_info_t curr_fw_info; + int ret = fota_curr_fw_read_header(&curr_fw_info); + if (ret) { + FOTA_TRACE_ERROR("Failed to read current header"); + return ret; + } + memcpy(buf, curr_fw_info.digest, FOTA_CRYPTO_HASH_SIZE); + return FOTA_STATUS_SUCCESS; +} + #endif // !defined(FOTA_CUSTOM_CURR_FW_STRUCTURE) || (!FOTA_CUSTOM_CURR_FW_STRUCTURE) #endif // MBED_CLOUD_CLIENT_FOTA_ENABLE diff --git a/fota/fota_curr_fw.h b/fota/fota_curr_fw.h index 189118b..a8d45bb 100644 --- a/fota/fota_curr_fw.h +++ b/fota/fota_curr_fw.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -26,14 +26,57 @@ extern "C" { #endif +/** + * Return a pointer to application start. + * + * \return Pointer to application start. + */ uint8_t *fota_curr_fw_get_app_start_addr(void); +/** + * Return a pointer to header start. + * + * \return Pointer to header start. + */ uint8_t *fota_curr_fw_get_app_header_addr(void); +#if defined(FOTA_CUSTOM_CURR_FW_STRUCTURE) && (FOTA_CUSTOM_CURR_FW_STRUCTURE) +/** + * Read header of current firmware. + * + * \param[in] header_info Header info structure. + * \return FOTA_STATUS_SUCCESS on success. + */ int fota_curr_fw_read_header(fota_header_info_t *header_info); +#else +// Default read header implementation +static inline int fota_curr_fw_read_header(fota_header_info_t *header_info) +{ + uint8_t *header_in_curr_fw = (uint8_t *)fota_curr_fw_get_app_header_addr(); + return fota_deserialize_header(header_in_curr_fw, fota_get_header_size(), header_info); +} +#endif + +/** + * Read from current firmware. + * + * \param[out] buf Buffer to read into. + * \param[in] offset Offset in firmware. + * \param[in] size Size to read (bytes). + * \param[out] num_read Number of read bytes. + * \return FOTA_STATUS_SUCCESS on success. + */ int fota_curr_fw_read(uint8_t *buf, uint32_t offset, uint32_t size, uint32_t *num_read); +/** + * Read digest from current firmware. + * + * \param[out] buf Buffer to read into. + * \return FOTA_STATUS_SUCCESS on success. + */ +int fota_curr_fw_get_digest(uint8_t *buf); + #ifdef __cplusplus } #endif diff --git a/fota/fota_delta.c b/fota/fota_delta.c index 5001382..084ba4e 100644 --- a/fota/fota_delta.c +++ b/fota/fota_delta.c @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2016-2019 ARM Ltd. +// Copyright 2016-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -19,6 +19,8 @@ #ifdef MBED_CLOUD_CLIENT_FOTA_ENABLE +#define TRACE_GROUP "FOTA" + #if !defined(FOTA_DISABLE_DELTA) #include "fota/fota_delta.h" @@ -37,6 +39,7 @@ #define DBG(fmt, ...) #endif + typedef struct fota_delta_ctx_s { struct bspatch_stream bs_patch_stream; // To keep internal state of which bspatch event is currently going to be completed @@ -46,9 +49,9 @@ typedef struct fota_delta_ctx_s { // to keep pointer to buffer bspatch gives us to read_patch function void *bspatch_read_patch_buffer_ptr; // to keep length what size buffer bspatch gave into read_patch function - uint64_t bspatch_read_patch_buffer_length; + uint32_t bspatch_read_patch_buffer_length; // to keep size how much we have remaining to be consumed from buffer bspatch gave into read_patch function - uint64_t bspatch_read_patch_buffer_remaining; + uint32_t bspatch_read_patch_buffer_remaining; // Pointer to data waiting for BS patch const uint8_t *incoming_frag_ptr; // Size of data waiting for BS patch @@ -85,7 +88,7 @@ bs_patch_api_return_code_t original_read(const struct bspatch_stream *stream, vo * * \return bs_patch_api_return_code_t EBSAPI_OPERATION_DONE_IMMEDIATELY or error code */ -bs_patch_api_return_code_t patch_read(const struct bspatch_stream *stream, void *buffer, uint64_t length); +bs_patch_api_return_code_t read_patch(const struct bspatch_stream *stream, void *buffer, uint32_t length); /* * BsPatch callback function to Seek the original file/image @@ -131,7 +134,7 @@ int fota_delta_start(fota_delta_ctx_t **ctx, fota_component_curr_fw_read curr_fw delta_ctx->incoming_frag_ptr = 0; delta_ctx->curr_fw_read = curr_fw_read; ARM_BS_Init(&delta_ctx->bs_patch_stream, (void *)delta_ctx, - patch_read, + read_patch, original_read, original_seek, new_write); @@ -154,16 +157,20 @@ int fota_delta_new_payload_frag( // Copy what we can fit into bspatch read_patch buffer if (ctx->next_event_to_post == EBSAPI_READ_PATCH_DONE && ctx->bspatch_read_patch_buffer_remaining > 0 && - ctx->bspatch_read_patch_buffer_remaining <= payload_frag_size) { + ctx->bspatch_read_patch_buffer_remaining <= ctx->bspatch_read_patch_buffer_length) { + uint32_t incoming_bytes_copy = payload_frag_size < ctx->bspatch_read_patch_buffer_remaining ? payload_frag_size : ctx->bspatch_read_patch_buffer_remaining; uint32_t patch_buf_offset = ctx->bspatch_read_patch_buffer_length - ctx->bspatch_read_patch_buffer_remaining; memcpy((uint8_t *)(ctx->bspatch_read_patch_buffer_ptr) + (patch_buf_offset), payload_frag, - ctx->bspatch_read_patch_buffer_remaining); - ctx->incoming_frag_ptr_offset += (uint32_t)ctx->bspatch_read_patch_buffer_remaining; - ctx->bspatch_read_patch_buffer_remaining = 0; + incoming_bytes_copy); + ctx->incoming_frag_ptr_offset += incoming_bytes_copy; + ctx->bspatch_read_patch_buffer_remaining -= incoming_bytes_copy; + } + if (ctx->bspatch_read_patch_buffer_remaining == 0) { + return do_patching(ctx); + } else { + return FOTA_STATUS_FW_DELTA_REQUIRED_MORE_DATA; } - int status = do_patching(ctx); - return status; } int fota_delta_get_next_fw_frag( @@ -218,7 +225,7 @@ int fota_delta_finalize(fota_delta_ctx_t **ctx) // bspatch read is still waiting for data if ((*ctx)->bspatch_read_patch_buffer_remaining > 0) { - FOTA_TRACE_ERROR("[DELTA] fota_delta_finalize bspatch read is still waiting for data %" PRIu64 " bytes.", (*ctx)->bspatch_read_patch_buffer_remaining); + FOTA_TRACE_ERROR("[DELTA] fota_delta_finalize bspatch read is still waiting for data %" PRIu32 " bytes.", (*ctx)->bspatch_read_patch_buffer_remaining); status = FOTA_STATUS_INTERNAL_DELTA_ERROR; } @@ -234,11 +241,9 @@ int do_patching(fota_delta_ctx_t *delta_ctx) bs_patch_api_return_code_t bs_result = EBSAPI_ERR_INVALID_STATE; do { bs_result = ARM_BS_ProcessPatchEvent(&delta_ctx->bs_patch_stream, delta_ctx->next_event_to_post); - if (bs_result == EBSAPI_PATCH_DONE) { - delta_ctx->next_event_to_post = EBSAPI_PATCH_DONE; - break; - } else if ((bs_result == EBSAPI_OPERATION_NEW_FILE_WRITE_WILL_COMPLETE_LATER) || - (bs_result == EBSAPI_OPERATION_PATCH_READ_WILL_COMPLETE_LATER)) { + if (bs_result == EBSAPI_PATCH_DONE || + bs_result == EBSAPI_OPERATION_NEW_FILE_WRITE_WILL_COMPLETE_LATER || + bs_result == EBSAPI_OPERATION_PATCH_READ_WILL_COMPLETE_LATER) { break; } else if (bs_result < EBSAPI_OPERATION_DONE_IMMEDIATELY) { // for all the failure error codes DBG("[DELTA] ARM_BS_ProcessPatchEvent() = %d.", bs_result); @@ -253,13 +258,13 @@ int do_patching(fota_delta_ctx_t *delta_ctx) return FOTA_STATUS_SUCCESS; } -bs_patch_api_return_code_t patch_read( +bs_patch_api_return_code_t read_patch( const struct bspatch_stream *stream, void *buffer, - uint64_t length) + uint32_t length) { bs_patch_api_return_code_t return_code = EBSAPI_ERR_UNEXPECTED_EVENT; - uint64_t copy_amount = 0; + uint32_t copy_amount = 0; fota_delta_ctx_t *delta_ctx = (fota_delta_ctx_t *)stream->opaque; FOTA_DBG_ASSERT(delta_ctx); delta_ctx->bspatch_read_patch_buffer_ptr = buffer; @@ -270,12 +275,12 @@ bs_patch_api_return_code_t patch_read( if (length > (delta_ctx->incoming_frag_size - delta_ctx->incoming_frag_ptr_offset)) { // We need to signal main bspatch-loop we have (in Write?) // to break so that we can get more patch data in. - DBG("[DELTA] patch_read(length=%" PRIu64 ")=EBSAPI_OPERATION_PATCH_READ_WILL_COMPLETE_LATER", length); + DBG("[DELTA] read_patch(length=%" PRIu32 ") EBSAPI_OPERATION_PATCH_READ_WILL_COMPLETE_LATER", length); copy_amount = (uint64_t)(delta_ctx->incoming_frag_size - delta_ctx->incoming_frag_ptr_offset); return_code = EBSAPI_OPERATION_PATCH_READ_WILL_COMPLETE_LATER; } else { - DBG("[DELTA] patch_read(length=%" PRIu64 ")=EBSAPI_OPERATION_DONE_IMMEDIATELY", length); + DBG("[DELTA] read_patch(length=%" PRIu32 ") EBSAPI_OPERATION_DONE_IMMEDIATELY", length); copy_amount = length; return_code = EBSAPI_OPERATION_DONE_IMMEDIATELY; } diff --git a/fota/fota_delta.h b/fota/fota_delta.h index 36c287f..f081a39 100644 --- a/fota/fota_delta.h +++ b/fota/fota_delta.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // diff --git a/fota/fota_event_handler.c b/fota/fota_event_handler.c index abe4f7c..39fe402 100644 --- a/fota/fota_event_handler.c +++ b/fota/fota_event_handler.c @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -20,6 +20,8 @@ #ifdef MBED_CLOUD_CLIENT_FOTA_ENABLE +#define TRACE_GROUP "FOTA" + #include #include "mbed-client-libservice/ns_types.h" #include "nanostack-event-loop/eventOS_event.h" @@ -59,44 +61,45 @@ static fota_event_handler_ctx_t g_ctx = { 0 }; static void event_handler(arm_event_t *event) { FOTA_TRACE_DEBUG("FOTA event-handler got event [type= %d]", event->event_type); - switch (event->event_type) { - case FOTA_EVENT_EXECUTE_WITH_BUFFER: { - fota_event_handler_ctx_t *ctx = (fota_event_handler_ctx_t *)event->data_ptr; - FOTA_DBG_ASSERT(ctx == &g_ctx); - FOTA_DBG_ASSERT(ctx->is_pending_event); - - fota_deferred_data_callabck_t cb = (fota_deferred_data_callabck_t)ctx->cb; - // backup the pointer as we need it after the callback. - // since we are setting ctx->is_pending_event = false - it may be overwritten - uint8_t *cb_data = ctx->args.buffer.data; - ctx->is_pending_event = false; + switch (event->event_type) { + case FOTA_EVENT_EXECUTE_WITH_BUFFER: + case FOTA_EVENT_EXECUTE_WITH_RESULT: + break; - cb(ctx->args.buffer.data, ctx->args.buffer.size); - free((void *)cb_data); - return; - } - case FOTA_EVENT_EXECUTE_WITH_RESULT: { - fota_event_handler_ctx_t *ctx = (fota_event_handler_ctx_t *)event->data_ptr; - FOTA_DBG_ASSERT(ctx == &g_ctx); - FOTA_DBG_ASSERT(ctx->is_pending_event); - - ctx->is_pending_event = false; - fota_deferred_result_callabck_t cb = (fota_deferred_result_callabck_t)ctx->cb; - cb(ctx->args.result.token, ctx->args.result.status); - return; - } case FOTA_EVENT_INIT: return; // ignore event - nothing to be done default: FOTA_DBG_ASSERT(!"Unknown event"); } + fota_event_handler_ctx_t *ctx = (fota_event_handler_ctx_t *)event->data_ptr; + FOTA_DBG_ASSERT(ctx == &g_ctx); + FOTA_DBG_ASSERT(ctx->is_pending_event); + + ctx->is_pending_event = false; + + if (event->event_type == FOTA_EVENT_EXECUTE_WITH_BUFFER) { + + fota_deferred_data_callabck_t cb = (fota_deferred_data_callabck_t)ctx->cb; + + // backup the pointer as we need it after the callback. + // since we are setting ctx->is_pending_event = false - it may be overwritten + uint8_t *cb_data = ctx->args.buffer.data; + + cb(ctx->args.buffer.data, ctx->args.buffer.size); + free((void *)cb_data); + + } else { // FOTA_EVENT_EXECUTE_WITH_RESULT + + fota_deferred_result_callabck_t cb = (fota_deferred_result_callabck_t)ctx->cb; + cb(ctx->args.result.token, ctx->args.result.status); + } } int fota_event_handler_init(void) { - FOTA_DBG_ASSERT(!g_ctx.is_pending_event); + FOTA_ASSERT(!g_ctx.is_pending_event); memset(&g_ctx, 0, sizeof(g_ctx)); @@ -113,7 +116,7 @@ void fota_event_handler_deinit(void) //nothing to de-register - eventOS does not have a method for destroying handlers } -void fota_event_handler_defer_with_data( +int fota_event_handler_defer_with_data( fota_deferred_data_callabck_t cb, uint8_t *data, size_t size) { FOTA_ASSERT(!g_ctx.is_pending_event); @@ -122,6 +125,10 @@ void fota_event_handler_defer_with_data( g_ctx.args.buffer.size = size; if (size) { uint8_t *tmp_data_ptr = (uint8_t *) malloc(size); + if (!tmp_data_ptr) { + FOTA_TRACE_ERROR("FOTA tmp_data_ptr - allocation failed"); + return FOTA_STATUS_OUT_OF_MEMORY; + } memcpy(tmp_data_ptr, data, size); g_ctx.args.buffer.data = tmp_data_ptr; } else { @@ -135,6 +142,7 @@ void fota_event_handler_defer_with_data( eventOS_event_send_user_allocated(&g_ctx.event_storage); + return FOTA_STATUS_SUCCESS; } void fota_event_handler_defer_with_result( diff --git a/fota/fota_event_handler.h b/fota/fota_event_handler.h index 178ff0e..b27667d 100644 --- a/fota/fota_event_handler.h +++ b/fota/fota_event_handler.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -46,9 +46,9 @@ void fota_event_handler_deinit(void); * /param cb[in] callback function pointer to be deferred * /param data[in] deferred callback input data pointer * /param size[in] deferred callback input data size - * + * \return FOTA_STATUS_SUCCESS on success. */ -void fota_event_handler_defer_with_data( +int fota_event_handler_defer_with_data( fota_deferred_data_callabck_t cb, uint8_t *data, size_t size); /* diff --git a/fota/fota_header_info.h b/fota/fota_header_info.h index 770a331..18e10f6 100644 --- a/fota/fota_header_info.h +++ b/fota/fota_header_info.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -19,51 +19,46 @@ #ifndef __FOTA_HEADER_INFO_H_ #define __FOTA_HEADER_INFO_H_ -#include #include "fota/fota_base.h" #include "fota/fota_crypto_defs.h" #include "fota/fota_component_defs.h" +#include "fota/fota_status.h" #ifdef __cplusplus extern "C" { #endif #if !defined(MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION) -#define MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION 3 +#error MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION expected to be set in fota_config.h #endif -#if (MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION >= 3) -#define FOTA_HEADER_HAS_CANDIDATE_READY 1 -#else -#define FOTA_HEADER_HAS_CANDIDATE_READY 0 +#if !defined(FOTA_HEADER_HAS_CANDIDATE_READY) +#error FOTA_HEADER_HAS_CANDIDATE_READY expected to be set in fota_config.h #endif -#if (MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION >= 3) -#define FOTA_HEADER_SUPPORTS_ENCRYPTION 1 -#else -#define FOTA_HEADER_SUPPORTS_ENCRYPTION 0 -#endif #define FOTA_FW_HEADER_MAGIC ((uint32_t)(0x5c0253a3)) #define FOTA_CANDIDATE_READY_MAGIC ((uint32_t)(0xfed54e01)) -#if (MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION == 3) -#if !defined(MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT) -#define MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT 1 -#endif -#else -#if (MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT == 1) -#error MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT enabled only for header version 3 -#endif +#if (MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION == 2) +#define ARM_UC_HEADER_SIZE_V2_EXTERNAL (296) +#define ARM_UC_HEADER_SIZE_V2_INTERNAL (112) + +#define ARM_UC_HEADER_MAGIC_V2_EXTERNAL (0x5a51b3d4UL) +#define ARM_UC_HEADER_MAGIC_V2_INTERNAL (0x5a51b3d4UL) #endif // Tells that we have a candidate ready typedef struct { uint32_t magic; char comp_name[FOTA_COMPONENT_MAX_NAME_SIZE]; + uint32_t footer; } fota_candidate_ready_header_t; +#define FOTA_HEADER_ENCRYPTED_FLAG 0x01 +#define FOTA_HEADER_SUPPORT_RESUME_FLAG 0x02 + /* * FW header as found in flash. * @@ -75,12 +70,48 @@ typedef struct { uint32_t magic; /*< Magic value */ uint32_t fw_size; /*< FW size in bytes */ uint64_t version; /*< FW version - timestamp */ +#if defined(MBED_CLOUD_CLIENT_FOTA_SIGNED_IMAGE_SUPPORT) + uint8_t signature[FOTA_IMAGE_RAW_SIGNATURE_SIZE]; /*< RAW ECDSA signature */ +#endif // defined(MBED_CLOUD_CLIENT_FOTA_SIGNED_IMAGE_SUPPORT) uint8_t digest[FOTA_CRYPTO_HASH_SIZE]; /*< FW image SHA256 digest */ - uint8_t precursor[FOTA_CRYPTO_HASH_SIZE]; /*< Only relevant for update candidate - contains previously installed FW SHA256 digest */ + + // From this point on, all fields are relevant to candidate only and + // can be skipped by bootloader if it wishes not to save them internally + uint8_t internal_header_barrier; + uint8_t flags; /*< Flags */ + uint16_t block_size; /*< Block size. Encryption block size if encrypted, + validated block size if unencrypted and block validation turned on */ + uint8_t precursor[FOTA_CRYPTO_HASH_SIZE]; /*< contains previously installed FW SHA256 digest */ + uint32_t footer; } fota_header_info_t; -size_t fota_get_header_size(void); -void fota_set_header_info_magic(fota_header_info_t *header_info); +static inline size_t fota_get_header_size(void) +{ +#if (MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION == 2) +#if (MBED_CLOUD_CLIENT_FOTA_FW_HEADER_EXTERNAL == 1) + return ARM_UC_HEADER_SIZE_V2_EXTERNAL; +#else + return ARM_UC_HEADER_SIZE_V2_INTERNAL; +#endif +#elif (MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION == 3) + return sizeof(fota_header_info_t); +#endif +} + +static inline void fota_set_header_info_magic(fota_header_info_t *header_info) +{ +#if (MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION == 2) +#if (MBED_CLOUD_CLIENT_FOTA_FW_HEADER_EXTERNAL == 1) + header_info->magic = ARM_UC_HEADER_MAGIC_V2_EXTERNAL; +#else + header_info->magic = ARM_UC_HEADER_MAGIC_V2_INTERNAL; +#endif +#elif (MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION == 3) + header_info->magic = FOTA_FW_HEADER_MAGIC; + header_info->footer = FOTA_FW_HEADER_MAGIC; +#endif +} + int fota_deserialize_header(const uint8_t *buffer, size_t buffer_size, fota_header_info_t *header_info); int fota_serialize_header(const fota_header_info_t *header_info, uint8_t *header_buf, size_t header_buf_size, size_t *header_buf_actual_size); diff --git a/fota/fota_header_info_v2.c b/fota/fota_header_info_v2.c index 2efe725..aeee320 100644 --- a/fota/fota_header_info_v2.c +++ b/fota/fota_header_info_v2.c @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -19,6 +19,8 @@ #ifdef MBED_CLOUD_CLIENT_FOTA_ENABLE +#define TRACE_GROUP "FOTA" + #include #include #include @@ -38,14 +40,12 @@ #define ARM_UC_FIRMWARE_SIZE_OFFSET_V2 (16) #define ARM_UC_FIRMWARE_HASH_OFFSET_V2 (24) -#define ARM_UC_HEADER_MAGIC_V2_EXTERNAL (0x5a51b3d4UL) #define ARM_UC_PAYLOAD_SIZE_OFFSET_V2_EXTERNAL (88) #define ARM_UC_PAYLOAD_HASH_OFFSET_V2_EXTERNAL (96) #define ARM_UC_CAMPAIGN_OFFSET_V2_EXTERNAL (160) #define ARM_UC_HMAC_OFFSET_V2_EXTERNAL (232) #define ARM_UC_HEADER_SIZE_V2_EXTERNAL (296) -#define ARM_UC_HEADER_MAGIC_V2_INTERNAL (0x5a51b3d4UL) #define ARM_UC_CAMPAIGN_OFFSET_V2_INTERNAL (88) #define ARM_UC_SIGNATURE_SIZE_OFFSET_V2_INTERNAL (104) #define ARM_UC_HEADER_CRC_OFFSET_V2_INTERNAL (108) @@ -360,26 +360,6 @@ int fota_deserialize_header(const uint8_t *buffer, size_t buffer_size, fota_head } -size_t fota_get_header_size() -{ -#if (MBED_CLOUD_CLIENT_FOTA_FW_HEADER_EXTERNAL == 1) - return ARM_UC_HEADER_SIZE_V2_EXTERNAL; -#else - return ARM_UC_HEADER_SIZE_V2_INTERNAL; -#endif -} - -void fota_set_header_info_magic(fota_header_info_t *header_info) -{ - FOTA_DBG_ASSERT(header_info); -#if (MBED_CLOUD_CLIENT_FOTA_FW_HEADER_EXTERNAL == 1) - header_info->magic = ARM_UC_HEADER_MAGIC_V2_EXTERNAL; -#else - header_info->magic = ARM_UC_HEADER_MAGIC_V2_INTERNAL; -#endif -} - - #endif #endif // MBED_CLOUD_CLIENT_FOTA_ENABLE diff --git a/fota/fota_header_info_v3.c b/fota/fota_header_info_v3.c index 47ec89b..fe895ce 100644 --- a/fota/fota_header_info_v3.c +++ b/fota/fota_header_info_v3.c @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -19,20 +19,17 @@ #ifdef MBED_CLOUD_CLIENT_FOTA_ENABLE -#include -#include -#include -#include -#include "fota/fota_header_info.h" -#include "fota/fota_status.h" +#define TRACE_GROUP "FOTA" +#include "fota/fota_header_info.h" +#include #if (MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION == 3) int fota_deserialize_header(const uint8_t *buffer, size_t buffer_size, fota_header_info_t *header_info) { FOTA_DBG_ASSERT(sizeof(*header_info) <= buffer_size); - memcpy(header_info, buffer, buffer_size); + memcpy(header_info, buffer, sizeof(*header_info)); if (header_info->magic != FOTA_FW_HEADER_MAGIC) { FOTA_TRACE_ERROR("Invalid header in current installed firmware"); return FOTA_STATUS_INTERNAL_ERROR; @@ -41,7 +38,10 @@ int fota_deserialize_header(const uint8_t *buffer, size_t buffer_size, fota_head return FOTA_STATUS_SUCCESS; } -int fota_serialize_header(const fota_header_info_t *header_info, uint8_t *header_buf, size_t header_buf_size, size_t *header_buf_actual_size) +int fota_serialize_header(const fota_header_info_t *header_info, + uint8_t *header_buf, + size_t header_buf_size, + size_t *header_buf_actual_size) { FOTA_DBG_ASSERT(sizeof(*header_info) <= header_buf_size); memcpy(header_buf, header_info, sizeof(*header_info)); @@ -50,17 +50,5 @@ int fota_serialize_header(const fota_header_info_t *header_info, uint8_t *header return FOTA_STATUS_SUCCESS; } -size_t fota_get_header_size(void) -{ - return sizeof(fota_header_info_t); -} - -void fota_set_header_info_magic(fota_header_info_t *header_info) -{ - FOTA_DBG_ASSERT(header_info); - header_info->magic = FOTA_FW_HEADER_MAGIC; -} - -#endif - -#endif // MBED_CLOUD_CLIENT_FOTA_ENABLE +#endif // MBED_CLOUD_CLIENT_FOTA_FW_HEADER_VERSION == 3 +#endif // MBED_CLOUD_CLIENT_FOTA_ENABLE diff --git a/fota/fota_internal.h b/fota/fota_internal.h index 35b5424..7f9666d 100644 --- a/fota/fota_internal.h +++ b/fota/fota_internal.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -39,6 +39,12 @@ typedef enum { FOTA_STATE_INVALID = 255, } fota_state_e; +typedef enum { + FOTA_RESUME_STATE_INACTIVE = 0, // must be zero as it is set by zeroing entire FOTA context at init + FOTA_RESUME_STATE_STARTED, + FOTA_RESUME_STATE_ONGOING, +} fota_resume_state_e; + typedef struct { manifest_firmware_info_t *fw_info; uint32_t payload_offset; @@ -46,11 +52,6 @@ typedef struct { uint32_t auth_token; unsigned int comp_id; fota_state_e state; - - // All fields up until now are persistent - // and should be kept in NVM for restore functionality. - // Those this line are not. - uint32_t frag_size; #if !defined(FOTA_DISABLE_DELTA) uint8_t *delta_buf; @@ -61,22 +62,19 @@ typedef struct { uint8_t *page_buf; uint32_t page_buf_offset; uint32_t page_buf_size; - uint32_t fw_offset_in_storage; - uint32_t storage_end_addr; - uint8_t *metadata_start_buf; - uint8_t *metadata_buf; - uint32_t metadata_buf_size; - uint32_t metadata_buf_offset; - uint32_t metadata_start_size; - uint32_t metadata_tags_size; - uint32_t metadata_curr_addr; + uint8_t *effective_page_buf; + uint32_t effective_page_buf_size; + uint32_t storage_addr; uint32_t fw_header_bd_size; uint32_t fw_header_offset; uint32_t candidate_header_size; + fota_resume_state_e resume_state; } fota_context_t; +fota_context_t *fota_get_context(void); + bool fota_is_active_update(void); -fota_state_e fota_is_ready(uint8_t *data, size_t size); +int fota_is_ready(uint8_t *data, size_t size, fota_state_e *fota_state); void fota_on_manifest(uint8_t *data, size_t size); void fota_on_reject(uint32_t token, int32_t status); @@ -84,7 +82,7 @@ void fota_on_defer(uint32_t token, int32_t status); void fota_on_authorize(uint32_t token, int32_t status); void fota_on_fragment(uint8_t *buf, size_t size); void fota_on_fragment_failure(uint32_t token, int32_t status); -void fota_on_resume(uint8_t *data, size_t size); +void fota_on_resume(uint32_t token, int32_t status); #ifdef __cplusplus } #endif diff --git a/fota/fota_manifest.h b/fota/fota_manifest.h index 87a99b2..3ee3de6 100644 --- a/fota/fota_manifest.h +++ b/fota/fota_manifest.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -21,7 +21,6 @@ #include "fota/fota_base.h" #include "fota/fota_crypto_defs.h" -#include "fota/fota_manifest_defs.h" #include "fota/fota_component.h" #ifdef __cplusplus @@ -34,6 +33,9 @@ extern "C" { #define FOTA_MANIFEST_TRACE_DEBUG(fmt, ...) #endif +#define FOTA_MANIFEST_PAYLOAD_FORMAT_RAW 1 +#define FOTA_MANIFEST_PAYLOAD_FORMAT_DELTA 5 + /* * Update details as extracted from the Pelion FOTA manifest */ @@ -42,16 +44,19 @@ typedef struct { uint32_t priority; /*< Update priority. */ uint32_t payload_format; /*< Payload format. */ uint32_t payload_size; /*< Payload size to be downloaded. */ + uint32_t installed_size; /*< Installed FW size. In case payload_format equals FOTA_MANIFEST_PAYLOAD_FORMAT_RAW the value is equal to payload_size. */ uint8_t payload_digest[FOTA_CRYPTO_HASH_SIZE]; /*< Payload SHA226 digest - for verifying downloaded payload integrity. */ char uri[FOTA_MANIFEST_URI_SIZE]; /*< Payload URI for downloading the payload. */ - uint32_t installed_size; /*< Installed FW size. In case payload_format equals FOTA_MANIFEST_PAYLOAD_FORMAT_RAW the value is equal to payload_size. */ uint8_t installed_digest[FOTA_CRYPTO_HASH_SIZE]; /*< Installed FW SHA256 digest. In case payload_format equals FOTA_MANIFEST_PAYLOAD_FORMAT_RAW the value is equal to payload_digest. */ uint8_t precursor_digest[FOTA_CRYPTO_HASH_SIZE]; /*< Currently installed (before update) FW SHA256 digest.*/ char component_name[FOTA_COMPONENT_MAX_NAME_SIZE]; /*< Component name */ uint8_t vendor_data[FOTA_MANIFEST_VENDOR_DATA_SIZE]; /*< Vendor custom data as received in Pelion FOTA manifest. */ +#if defined(MBED_CLOUD_CLIENT_FOTA_SIGNED_IMAGE_SUPPORT) + uint8_t installed_signature[FOTA_IMAGE_RAW_SIGNATURE_SIZE]; /** Raw encoded signature over installed image */ +#endif // defined(MBED_CLOUD_CLIENT_FOTA_SIGNED_IMAGE_SUPPORT) + } manifest_firmware_info_t; -typedef struct mbedtls_x509_crt mbedtls_x509_crt; /* * Parse and validate Pelion FOTA manifest. * @@ -60,15 +65,13 @@ typedef struct mbedtls_x509_crt mbedtls_x509_crt; * \param[in] manifest_buf Pionter to a buffer holding Pelion FOTA manifest to be parsed * \param[in] manifest_size Input manifest size * \param[out] fw_info Pointer to a struct holding update details - * \param[in] cert X.509 certificate for verifying FOTA Manifest authenticity * \param[in] current_fw_digest Currently installed FW SHA256 digest - required for asserting precursor digest * \return FOTA_STATUS_SUCCESS on success */ int fota_manifest_parse( const uint8_t *manifest_buf, size_t manifest_size, - manifest_firmware_info_t *fw_info, - mbedtls_x509_crt *cert); + manifest_firmware_info_t *fw_info); #ifdef __cplusplus } diff --git a/fota/fota_manifest_v1.c b/fota/fota_manifest_v1.c index 2a6c737..2ed546f 100644 --- a/fota/fota_manifest_v1.c +++ b/fota/fota_manifest_v1.c @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -19,6 +19,8 @@ #ifdef MBED_CLOUD_CLIENT_FOTA_ENABLE +#define TRACE_GROUP "FOTA" + #include #include #include @@ -27,6 +29,7 @@ #include "fota/fota_status.h" #include "fota/fota_manifest.h" #include "fota/fota_crypto.h" +#include "fota/fota_crypto_asn_extra.h" #include "fota/fota_nvm.h" #include "mbedtls/asn1.h" #include "mbedtls/sha256.h" @@ -64,7 +67,7 @@ * installedDigest OCTET STRING OPTIONAL, * version UTF8String OPTIONAL * } - * + * */ int parse_delta_metadata( const uint8_t *metadata, size_t metadata_size, @@ -126,7 +129,7 @@ int parse_delta_metadata( * installedDigest OCTET STRING OPTIONAL, * version UTF8String OPTIONAL * } - * + * */ int parse_payload_description( const uint8_t *desc_data, size_t desc_size, @@ -147,7 +150,7 @@ int parse_payload_description( FOTA_TRACE_ERROR("Error reading PayloadDescription:format %d", tls_status); return FOTA_STATUS_MANIFEST_MALFORMED; } - + FOTA_MANIFEST_TRACE_DEBUG("PayloadDescription:format %d", payload_format_value); fw_info->payload_format = payload_format_value; if (payload_format_value == FOTA_MANIFEST_PAYLOAD_FORMAT_DELTA) { @@ -313,6 +316,7 @@ int parse_manifest_internal( return FOTA_STATUS_MANIFEST_MALFORMED; } +#if !defined(FOTA_TEST_MANIFEST_BYPASS_VALIDATION) uint8_t fota_id[FOTA_GUID_SIZE] = {0}; fota_status = fota_nvm_get_vendor_id(fota_id); if (fota_status != FOTA_STATUS_SUCCESS) { @@ -323,7 +327,8 @@ int parse_manifest_internal( FOTA_TRACE_ERROR("vendor_id mismatch"); return FOTA_STATUS_MANIFEST_WRONG_VENDOR_ID; } - +#endif // !defined(FOTA_TEST_MANIFEST_BYPASS_VALIDATION) + p += len; FOTA_MANIFEST_TRACE_DEBUG("Reading Manifest:classId @%d", p - input_data); @@ -335,6 +340,7 @@ int parse_manifest_internal( return FOTA_STATUS_MANIFEST_MALFORMED; } +#if !defined(FOTA_TEST_MANIFEST_BYPASS_VALIDATION) memset(fota_id, 0, FOTA_GUID_SIZE); fota_status = fota_nvm_get_class_id(fota_id); if (fota_status != FOTA_STATUS_SUCCESS) { @@ -346,6 +352,7 @@ int parse_manifest_internal( FOTA_TRACE_ERROR("class_id mismatch"); return FOTA_STATUS_MANIFEST_WRONG_CLASS_ID; } +#endif // !defined(FOTA_TEST_MANIFEST_BYPASS_VALIDATION) p += len; FOTA_MANIFEST_TRACE_DEBUG("Reading Manifest:deviceId @%d", p - input_data); @@ -489,8 +496,7 @@ int parse_manifest_internal( */ int fota_manifest_parse( const uint8_t *input_data, size_t input_size, - manifest_firmware_info_t *fw_info, - mbedtls_x509_crt *cert + manifest_firmware_info_t *fw_info ) { FOTA_DBG_ASSERT(input_data); @@ -498,9 +504,9 @@ int fota_manifest_parse( FOTA_DBG_ASSERT(fw_info); memset(fw_info, 0, sizeof(*fw_info)); - - int fota_status = FOTA_STATUS_MANIFEST_MALFORMED; - int tls_status; + int ret = FOTA_STATUS_MANIFEST_MALFORMED; // used by FOTA_FI_SAFE_COND + int fota_sig_status = FOTA_STATUS_MANIFEST_MALFORMED; // must be set to error + int tmp_status; // reusable status size_t len = input_size; unsigned char *signed_data_ptr = 0; @@ -515,11 +521,11 @@ int fota_manifest_parse( int resource_type = -1; FOTA_MANIFEST_TRACE_DEBUG("SignedResource @%d", (p - input_data)); - tls_status = mbedtls_asn1_get_tag( + tmp_status = mbedtls_asn1_get_tag( &p, resource_end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); - if (tls_status != 0) { - FOTA_TRACE_ERROR("Error reading SignedResource tag %d", tls_status); + if (tmp_status != 0) { + FOTA_TRACE_ERROR("Error reading SignedResource tag %d", tmp_status); return FOTA_STATUS_MANIFEST_MALFORMED; } if (p + len > resource_end) { @@ -533,11 +539,11 @@ int fota_manifest_parse( signed_data_ptr = p; FOTA_MANIFEST_TRACE_DEBUG("Reading Resource @%d", (p - input_data)); - tls_status = mbedtls_asn1_get_tag( + tmp_status = mbedtls_asn1_get_tag( &p, resource_end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); - if (tls_status != 0) { - FOTA_TRACE_ERROR("Error reading Resource %d", tls_status); + if (tmp_status != 0) { + FOTA_TRACE_ERROR("Error reading Resource %d", tmp_status); return FOTA_STATUS_MANIFEST_MALFORMED; } @@ -550,55 +556,57 @@ int fota_manifest_parse( p += len; // jump over resource element FOTA_MANIFEST_TRACE_DEBUG("Reading ResourceSignature @%d", (p - input_data)); - tls_status = mbedtls_asn1_get_tag( + tmp_status = mbedtls_asn1_get_tag( &p, resource_end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); - if (tls_status != 0) { - FOTA_TRACE_ERROR("Error reading ResourceSignature %d", tls_status); + if (tmp_status != 0) { + FOTA_TRACE_ERROR("Error reading ResourceSignature %d", tmp_status); return FOTA_STATUS_MANIFEST_MALFORMED; } FOTA_DBG_ASSERT(resource_end >= p + len); FOTA_MANIFEST_TRACE_DEBUG("Reading ResourceSignature:hash @%d", (p - input_data)); - tls_status = mbedtls_asn1_get_tag( + tmp_status = mbedtls_asn1_get_tag( &p, resource_end, &len, MBEDTLS_ASN1_OCTET_STRING); - if (tls_status != 0) { - FOTA_TRACE_ERROR("Error reading hash %d", tls_status); + if (tmp_status != 0) { + FOTA_TRACE_ERROR("Error reading hash %d", tmp_status); return FOTA_STATUS_MANIFEST_MALFORMED; } p += len; // jump over hash element FOTA_MANIFEST_TRACE_DEBUG("Reading ResourceSignature:signatures @%d", (p - input_data)); - tls_status = mbedtls_asn1_get_sequence_of( + tmp_status = mbedtls_asn1_get_sequence_of( &p, resource_end, cur_ptr, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); - if (tls_status != 0) { - FOTA_TRACE_ERROR("Error reading ResourceSignature:signatures %d", tls_status); + if (tmp_status != 0) { + FOTA_TRACE_ERROR("Error reading ResourceSignature:signatures %d", tmp_status); return FOTA_STATUS_MANIFEST_MALFORMED; } - + FOTA_MANIFEST_TRACE_DEBUG("Reading ResourceSignature:signatures[0] @%d", (p - input_data)); - tls_status = mbedtls_asn1_get_tag( + tmp_status = mbedtls_asn1_get_tag( &(cur_ptr->buf.p), resource_end, &len, MBEDTLS_ASN1_OCTET_STRING); - if (tls_status != 0) { - FOTA_TRACE_ERROR("Error reading ResourceSignature:signatures[0] %d", tls_status); + if (tmp_status != 0) { + FOTA_TRACE_ERROR("Error reading ResourceSignature:signatures[0] %d", tmp_status); return FOTA_STATUS_MANIFEST_MALFORMED; } FOTA_DBG_ASSERT(resource_end >= cur_ptr->buf.p + len); - - fota_status = fota_verify_signature( - signed_data_ptr, signed_data_size, - cur_ptr->buf.p, len, - cert); - if (fota_status != 0) { - FOTA_TRACE_ERROR("fota_verify_signature failed %d", fota_status); - return fota_status; - } +#if !defined(FOTA_TEST_MANIFEST_BYPASS_VALIDATION) + // Make sure fota_status has erroneous value before the call + fota_sig_status = fota_verify_signature( + signed_data_ptr, signed_data_size, + cur_ptr->buf.p, len); + FOTA_FI_SAFE_COND( + fota_sig_status == FOTA_STATUS_SUCCESS, + fota_sig_status, + "fota_verify_signature failed %d", fota_sig_status + ); +#endif // !defined(FOTA_TEST_MANIFEST_BYPASS_VALIDATION) if (cur_ptr->next != NULL) { FOTA_MANIFEST_TRACE_DEBUG("Could be only one sequence"); @@ -606,18 +614,18 @@ int fota_manifest_parse( } p = resource; FOTA_MANIFEST_TRACE_DEBUG("Reading Resource:uri OPTIONAL @%d", (p - input_data)); - tls_status = mbedtls_asn1_get_tag( + tmp_status = mbedtls_asn1_get_tag( &p, resource_end, &len, MBEDTLS_ASN1_UTF8_STRING); - if (tls_status == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) { + if (tmp_status == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) { FOTA_MANIFEST_TRACE_DEBUG("Resource:uri OPTIONAL is missing"); } else { p += len; } FOTA_MANIFEST_TRACE_DEBUG("Reading Resource:resourceType @%d", (p - input_data)); - tls_status = mbedtls_asn1_get_enumerated_value(&p, resource_end, &resource_type); - if (tls_status != 0) { - FOTA_TRACE_ERROR("Error reading Resource:resourceType %d", tls_status); + tmp_status = mbedtls_asn1_get_enumerated_value(&p, resource_end, &resource_type); + if (tmp_status != 0) { + FOTA_TRACE_ERROR("Error reading Resource:resourceType %d", tmp_status); return FOTA_STATUS_MANIFEST_MALFORMED; } FOTA_MANIFEST_TRACE_DEBUG("Resource:resourceType=%d", resource_type); @@ -627,27 +635,30 @@ int fota_manifest_parse( return FOTA_STATUS_MANIFEST_MALFORMED; } FOTA_MANIFEST_TRACE_DEBUG("Resource:Manifest @%d", (p - input_data)); - tls_status = mbedtls_asn1_get_tag( + tmp_status = mbedtls_asn1_get_tag( &p, resource_end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); - if (tls_status != 0) { - FOTA_TRACE_ERROR("Error reading Resource:Manifest %d", tls_status); + if (tmp_status != 0) { + FOTA_TRACE_ERROR("Error reading Resource:Manifest %d", tmp_status); return FOTA_STATUS_MANIFEST_MALFORMED; } FOTA_DBG_ASSERT(resource_end >= p + len); - fota_status = parse_manifest_internal( - p, len, - fw_info, - input_data); - if (fota_status != 0) { - FOTA_TRACE_ERROR("parse_manifest_internal failed %d", fota_status); - return fota_status; + tmp_status = parse_manifest_internal( + p, len, + fw_info, + input_data); + if (tmp_status != 0) { + FOTA_TRACE_ERROR("parse_manifest_internal failed %d", tmp_status); + return tmp_status; } FOTA_MANIFEST_TRACE_DEBUG("status = %d", FOTA_STATUS_SUCCESS); return FOTA_STATUS_SUCCESS; +fail: + return ret; + } #endif diff --git a/fota/fota_manifest_v3.c b/fota/fota_manifest_v3.c index 4a880d0..0d33471 100644 --- a/fota/fota_manifest_v3.c +++ b/fota/fota_manifest_v3.c @@ -1,6 +1,5 @@ - // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -20,14 +19,22 @@ #ifdef MBED_CLOUD_CLIENT_FOTA_ENABLE +#define TRACE_GROUP "FOTA" + +#if (FOTA_MANIFEST_SCHEMA_VERSION == 3) + #include #include #include +#include #include #include "fota/fota_manifest.h" +#include "fota/fota_component.h" +#include "fota/fota_component_internal.h" #include "fota/fota_status.h" #include "fota/fota_crypto.h" +#include "fota/fota_crypto_asn_extra.h" #include "fota/fota_base.h" #include "fota/fota_nvm.h" #include "fota/fota_crypto.h" @@ -36,8 +43,6 @@ #include "mbedtls/x509_crt.h" #include "mbedtls/pk.h" -#if (FOTA_MANIFEST_SCHEMA_VERSION == 3) - /* * DeltaMetadata ::= SEQUENCE { * installed-size INTEGER, @@ -99,12 +104,14 @@ int parse_delta_metadata( } + /* * Manifest ::= SEQUENCE { * vendor-id OCTET STRING, * class-id OCTET STRING, * update-priority INTEGER, - * payload-version INTEGER, + * component-name UTF8String, + * payload-version UTF8String, * payload-digest OCTET STRING, * payload-size INTEGER, * payload-uri UTF8String, @@ -112,6 +119,7 @@ int parse_delta_metadata( * raw-binary(1), * arm-patch-stream(5) * }, + * installed-signature OCTET STRING, * delta-metadata DeltaMetadata OPTIONAL, * vendor-data OCTET STRING OPTIONAL * } @@ -135,6 +143,7 @@ int parse_manifest_internal( return FOTA_STATUS_MANIFEST_MALFORMED; } +#if !defined(FOTA_TEST_MANIFEST_BYPASS_VALIDATION) uint8_t fota_id[FOTA_GUID_SIZE] = {0}; fota_status = fota_nvm_get_vendor_id(fota_id); if (fota_status != FOTA_STATUS_SUCCESS) { @@ -145,6 +154,8 @@ int parse_manifest_internal( FOTA_TRACE_ERROR("vendor_id mismatch"); return FOTA_STATUS_MANIFEST_WRONG_VENDOR_ID; } +#endif // !defined(FOTA_TEST_MANIFEST_BYPASS_VALIDATION) + p += len; FOTA_MANIFEST_TRACE_DEBUG("Parse Manifest:class-id @%d", p - input_data); @@ -156,6 +167,7 @@ int parse_manifest_internal( return FOTA_STATUS_MANIFEST_MALFORMED; } +#if !defined(FOTA_TEST_MANIFEST_BYPASS_VALIDATION) memset(fota_id, 0, FOTA_GUID_SIZE); fota_status = fota_nvm_get_class_id(fota_id); if (fota_status != FOTA_STATUS_SUCCESS) { @@ -166,6 +178,7 @@ int parse_manifest_internal( FOTA_TRACE_ERROR("class_id mismatch"); return FOTA_STATUS_MANIFEST_WRONG_CLASS_ID; } +#endif // !defined(FOTA_TEST_MANIFEST_BYPASS_VALIDATION) p += len; FOTA_MANIFEST_TRACE_DEBUG("Parse Manifest:update-priority @%d", p - input_data); @@ -177,14 +190,41 @@ int parse_manifest_internal( FOTA_MANIFEST_TRACE_DEBUG("Manifest:update-priority %" PRIu32, fw_info->priority); + FOTA_MANIFEST_TRACE_DEBUG("Parse Manifest:component-name @%d", p - input_data); + tls_status = mbedtls_asn1_get_tag( + &p, manifest_end, &len, MBEDTLS_ASN1_UTF8_STRING); + if (tls_status != 0) { + FOTA_TRACE_ERROR("Error reading Manifest:component-name %d", tls_status); + return FOTA_STATUS_MANIFEST_MALFORMED; + } + + if (len >= FOTA_COMPONENT_MAX_NAME_SIZE) { + FOTA_TRACE_ERROR("component-name too long %zu", len); + return FOTA_STATUS_MANIFEST_SEMVER_ERROR; + } + memcpy(fw_info->component_name, p, len); + FOTA_MANIFEST_TRACE_DEBUG("component-name %s", fw_info->component_name); + p += len; + FOTA_MANIFEST_TRACE_DEBUG("Parse Manifest:payload-version @%d", p - input_data); - tls_status = mbedtls_asn1_get_int64(&p, manifest_end, (int64_t *) &fw_info->version); + tls_status = mbedtls_asn1_get_tag( + &p, manifest_end, &len, MBEDTLS_ASN1_UTF8_STRING); if (tls_status != 0) { FOTA_TRACE_ERROR("Error reading Manifest:payload-version %d", tls_status); return FOTA_STATUS_MANIFEST_MALFORMED; } - - FOTA_MANIFEST_TRACE_DEBUG("Manifest:payload-version %" PRIu64, fw_info->version); + if (len >= FOTA_COMPONENT_MAX_SEMVER_STR_SIZE) { + FOTA_TRACE_ERROR("Manifest:payload-version too long %zu", len); + return FOTA_STATUS_MANIFEST_PAYLOAD_CORRUPTED; + } + char sem_ver[FOTA_COMPONENT_MAX_SEMVER_STR_SIZE] = { 0 }; + memcpy(sem_ver, p, len); + fota_status = fota_component_version_semver_to_int(sem_ver, &fw_info->version); + if (fota_status != FOTA_STATUS_SUCCESS) { + return fota_status; + } + FOTA_MANIFEST_TRACE_DEBUG("Manifest:payload-version %d", sem_ver); + p += len; FOTA_MANIFEST_TRACE_DEBUG("Parse Manifest:payload-digest @%d", p - input_data); tls_status = mbedtls_asn1_get_tag( @@ -243,6 +283,23 @@ int parse_manifest_internal( return FOTA_STATUS_MANIFEST_PAYLOAD_UNSUPPORTED; } + FOTA_MANIFEST_TRACE_DEBUG("Parse Manifest:installed-signature @%d", p - input_data); + tls_status = mbedtls_asn1_get_tag( + &p, manifest_end, &len, + MBEDTLS_ASN1_OCTET_STRING); + if (tls_status == 0) { +#if defined(MBED_CLOUD_CLIENT_FOTA_SIGNED_IMAGE_SUPPORT) + if (FOTA_IMAGE_RAW_SIGNATURE_SIZE != len) { + FOTA_TRACE_ERROR("installed-signature len is invalid %d (expected %d)", len, FOTA_IMAGE_RAW_SIGNATURE_SIZE); + return FOTA_STATUS_MANIFEST_MALFORMED; + } + memcpy(fw_info->installed_signature, p, len); +#endif // defined(MBED_CLOUD_CLIENT_FOTA_SIGNED_IMAGE_SUPPORT) + p += len; + } else { + FOTA_MANIFEST_TRACE_DEBUG("installed-signature not found ptr=%p", p); + } + if (is_delta) { FOTA_MANIFEST_TRACE_DEBUG("Parse Manifest:delta-metadata @%d", p - input_data); tls_status = mbedtls_asn1_get_tag( @@ -300,8 +357,7 @@ int parse_manifest_internal( */ int fota_manifest_parse( const uint8_t *input_data, size_t input_size, - manifest_firmware_info_t *fw_info, - mbedtls_x509_crt *cert + manifest_firmware_info_t *fw_info ) { FOTA_DBG_ASSERT(input_data); @@ -310,8 +366,9 @@ int fota_manifest_parse( memset(fw_info, 0, sizeof(*fw_info)); - int fota_status = FOTA_STATUS_MANIFEST_MALFORMED; - int tls_status; + int ret = FOTA_STATUS_MANIFEST_MALFORMED; // used by FOTA_FI_SAFE_COND + int fota_sig_status = FOTA_STATUS_MANIFEST_MALFORMED; // must be set to error + int tmp_status; // reusable status size_t len = input_size; unsigned char *p = (unsigned char *)input_data; unsigned char *signed_resource_end = p + len; @@ -320,11 +377,11 @@ int fota_manifest_parse( size_t int_manifest_size = 0; FOTA_MANIFEST_TRACE_DEBUG("Parse SignedResource @%d", p - input_data); - tls_status = mbedtls_asn1_get_tag( + tmp_status = mbedtls_asn1_get_tag( &p, signed_resource_end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); - if (tls_status != 0) { - FOTA_TRACE_ERROR("Error SignedResource tag %d", tls_status); + if (tmp_status != 0) { + FOTA_TRACE_ERROR("Error SignedResource tag %d", tmp_status); return FOTA_STATUS_MANIFEST_MALFORMED; } @@ -339,9 +396,9 @@ int fota_manifest_parse( int manifest_format_version = 0; FOTA_MANIFEST_TRACE_DEBUG("Parse SignedResource:version @%d", p - input_data); - tls_status = mbedtls_asn1_get_enumerated_value(&p, signed_resource_end, &manifest_format_version); - if (tls_status != 0) { - FOTA_TRACE_ERROR("Error reading SignedResource:version %d", tls_status); + tmp_status = mbedtls_asn1_get_enumerated_value(&p, signed_resource_end, &manifest_format_version); + if (tmp_status != 0) { + FOTA_TRACE_ERROR("Error reading SignedResource:version %d", tmp_status); return FOTA_STATUS_MANIFEST_MALFORMED; } @@ -356,11 +413,11 @@ int fota_manifest_parse( size_t signed_data_size; FOTA_MANIFEST_TRACE_DEBUG("Parse SignedResource:manifest @%d", p - input_data); - tls_status = mbedtls_asn1_get_tag( + tmp_status = mbedtls_asn1_get_tag( &p, signed_resource_end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); - if (tls_status != 0) { - FOTA_TRACE_ERROR("Error reading SignedResource:manifest %d", tls_status); + if (tmp_status != 0) { + FOTA_TRACE_ERROR("Error reading SignedResource:manifest %d", tmp_status); return FOTA_STATUS_MANIFEST_MALFORMED; } @@ -371,35 +428,40 @@ int fota_manifest_parse( p += len; FOTA_MANIFEST_TRACE_DEBUG("Parse SignedResource:signature @%d", p - input_data); - tls_status = mbedtls_asn1_get_tag( + tmp_status = mbedtls_asn1_get_tag( &p, signed_resource_end, &len, MBEDTLS_ASN1_OCTET_STRING); - if (tls_status != 0) { - FOTA_TRACE_ERROR("Error reading SignedResource:signature %d", tls_status); + if (tmp_status != 0) { + FOTA_TRACE_ERROR("Error reading SignedResource:signature %d", tmp_status); return FOTA_STATUS_MANIFEST_MALFORMED; } - fota_status = fota_verify_signature( - signed_data_ptr, signed_data_size, - p, len, - cert); - if (fota_status != 0) { - FOTA_TRACE_ERROR("fota_verify_signature failed %d", fota_status); - return fota_status; - } +#if !defined(FOTA_TEST_MANIFEST_BYPASS_VALIDATION) + + fota_sig_status = fota_verify_signature( + signed_data_ptr, signed_data_size, + p, len); + FOTA_FI_SAFE_COND( + fota_sig_status == FOTA_STATUS_SUCCESS, + fota_sig_status, + "fota_verify_signature failed %d", fota_sig_status + ); +#endif // !defined(FOTA_TEST_MANIFEST_BYPASS_VALIDATION) p += len; - fota_status = parse_manifest_internal( - int_manifest, int_manifest_size, - fw_info, input_data); - if (fota_status != 0) { - FOTA_TRACE_ERROR("parse_manifest_internal failed %d", fota_status); - return fota_status; + tmp_status = parse_manifest_internal( + int_manifest, int_manifest_size, + fw_info, input_data); + if (tmp_status != 0) { + FOTA_TRACE_ERROR("parse_manifest_internal failed %d", tmp_status); + return tmp_status; } FOTA_MANIFEST_TRACE_DEBUG("status = %d", FOTA_STATUS_SUCCESS); return FOTA_STATUS_SUCCESS; +fail: + return ret; } #endif diff --git a/fota/fota_nvm.c b/fota/fota_nvm.c index 02697b1..d9fb541 100644 --- a/fota/fota_nvm.c +++ b/fota/fota_nvm.c @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -20,15 +20,16 @@ #ifdef MBED_CLOUD_CLIENT_FOTA_ENABLE +#define TRACE_GROUP "FOTA" + #include "fota/fota_status.h" #include "fota/fota_nvm.h" -#include "fota/fota_manifest_defs.h" -#include "fota/fota_crypto_defs.h" +#include "fota/fota_nvm_int.h" #include "fota/fota_crypto.h" #include "fota/fota_component.h" +#include "fota/fota_crypto_defs.h" #include "mbed_error.h" #include "mbed-trace/mbed_trace.h" -#include "CloudClientStorage.h" #include static fota_status_e map_store_result(int result) @@ -53,31 +54,48 @@ static fota_status_e map_store_result(int result) return res; } -static int get(cloud_client_param key, uint8_t *buffer, size_t buffer_size, size_t *bytes_read) +int fota_nvm_get(cloud_client_param key, uint8_t *buffer, size_t buffer_size, size_t *bytes_read) { ccs_status_e result = get_config_parameter(key, buffer, buffer_size, bytes_read); return map_store_result(result); } -static int set(cloud_client_param key, const uint8_t *buffer, size_t buffer_size) +int fota_nvm_set(cloud_client_param key, const uint8_t *buffer, size_t buffer_size) { ccs_status_e result = set_config_parameter(key, buffer, buffer_size); return map_store_result(result); } +int fota_nvm_remove(cloud_client_param key) +{ + ccs_status_e status = remove_config_parameter(key); + return map_store_result(status); +} + +#if !defined(FOTA_USE_EXTERNAL_FW_KEY) int fota_nvm_fw_encryption_key_get(uint8_t buffer[FOTA_ENCRYPT_KEY_SIZE]) { size_t bytes_read; - int ret = get(FOTA_ENCRYPT_KEY, buffer, FOTA_ENCRYPT_KEY_SIZE, &bytes_read); + int ret = fota_nvm_get(FOTA_ENCRYPT_KEY, buffer, FOTA_ENCRYPT_KEY_SIZE, &bytes_read); FOTA_DBG_ASSERT(ret || (FOTA_ENCRYPT_KEY_SIZE == bytes_read)); return ret; } int fota_nvm_fw_encryption_key_set(const uint8_t buffer[FOTA_ENCRYPT_KEY_SIZE]) { - return set(FOTA_ENCRYPT_KEY, buffer, FOTA_ENCRYPT_KEY_SIZE); + return fota_nvm_set(FOTA_ENCRYPT_KEY, buffer, FOTA_ENCRYPT_KEY_SIZE); } +int fota_nvm_fw_encryption_key_delete(void) +{ + return fota_nvm_remove(FOTA_ENCRYPT_KEY); +} +#endif // !defined(FOTA_USE_EXTERNAL_FW_KEY) +/******************************************************************************************************/ +/* Update x509 Certificate */ +/******************************************************************************************************/ +#if defined(FOTA_USE_UPDATE_X509) + #if defined(MBED_CLOUD_DEV_UPDATE_CERT) extern const uint8_t arm_uc_default_certificate[]; @@ -106,6 +124,11 @@ int fota_nvm_get_update_certificate(uint8_t *buffer, size_t size, size_t *bytes_ int fota_nvm_update_cert_set(void) { uint8_t *buffer_fota_certificate = malloc(FOTA_CERT_MAX_SIZE); + if (!buffer_fota_certificate) { + FOTA_TRACE_ERROR("FOTA buffer_fota_certificate - allocation failed"); + return FOTA_STATUS_OUT_OF_MEMORY; + } + memset(buffer_fota_certificate, 0, FOTA_CERT_MAX_SIZE); size_t bytes_read; @@ -113,15 +136,9 @@ int fota_nvm_update_cert_set(void) int ret = fota_nvm_get_update_certificate(buffer_fota_certificate, FOTA_CERT_MAX_SIZE, &bytes_read); - if (ret == FOTA_STATUS_NOT_FOUND) { - ret = set(UPDATE_CERTIFICATE, buffer_fota_certificate, FOTA_CERT_MAX_SIZE); - free(buffer_fota_certificate); - return ret; - } else if (ret == FOTA_STATUS_SUCCESS && 0 != memcmp(buffer_fota_certificate, arm_uc_default_certificate, arm_uc_default_certificate_size)) { - - ret = set(UPDATE_CERTIFICATE, buffer_fota_certificate, FOTA_CERT_MAX_SIZE); - free(buffer_fota_certificate); - return ret; + if ((ret == FOTA_STATUS_NOT_FOUND) || + (ret == FOTA_STATUS_SUCCESS && 0 != memcmp(buffer_fota_certificate, arm_uc_default_certificate, arm_uc_default_certificate_size))) { + ret = fota_nvm_set(UPDATE_CERTIFICATE, buffer_fota_certificate, FOTA_CERT_MAX_SIZE); } free(buffer_fota_certificate); @@ -129,19 +146,75 @@ int fota_nvm_update_cert_set(void) } #endif // defined(FOTA_USE_EXTERNAL_CERT) - #endif // defined(MBED_CLOUD_DEV_UPDATE_CERT) #if !defined(FOTA_USE_EXTERNAL_CERT) int fota_nvm_get_update_certificate(uint8_t *buffer, size_t size, size_t *bytes_read) { - return get(UPDATE_CERTIFICATE, buffer, size, bytes_read); + return fota_nvm_get(UPDATE_CERTIFICATE, buffer, size, bytes_read); } #endif // !defined(FOTA_USE_EXTERNAL_CERT) +#endif // defined(FOTA_USE_UPDATE_X509) + +/******************************************************************************************************/ +/* Update public key */ +/******************************************************************************************************/ +#if defined(FOTA_USE_UPDATE_RAW_PUBLIC_KEY) +#if defined(MBED_CLOUD_DEV_UPDATE_RAW_PUBLIC_KEY) + +extern const uint8_t arm_uc_update_public_key[]; + +#if defined(FOTA_USE_EXTERNAL_UPDATE_RAW_PUBLIC_KEY) +// in this case we are simulating an externally provided update public key +// getter function based on FOTA developer certificate (auto-generated) +int fota_nvm_get_update_public_key(uint8_t buffer[FOTA_UPDATE_RAW_PUBLIC_KEY_SIZE]) +{ + memcpy(buffer, arm_uc_update_public_key, FOTA_UPDATE_RAW_PUBLIC_KEY_SIZE); + return FOTA_STATUS_SUCCESS; +} +#else +// implement setter functions that will be called from fota_dev_init() +int fota_nvm_set_update_public_key(void) +{ + uint8_t *buffer_raw_key = malloc(FOTA_UPDATE_RAW_PUBLIC_KEY_SIZE); + if (!buffer_raw_key) { + FOTA_TRACE_ERROR("FOTA buffer_raw_key - allocation failed"); + return FOTA_STATUS_OUT_OF_MEMORY; + } + + memcpy(buffer_raw_key, arm_uc_update_public_key, FOTA_UPDATE_RAW_PUBLIC_KEY_SIZE); + + int ret = fota_nvm_get_update_public_key(buffer_raw_key); + + if ((ret == FOTA_STATUS_NOT_FOUND) || + (ret == FOTA_STATUS_SUCCESS && 0 != memcmp(buffer_raw_key, arm_uc_update_public_key, FOTA_UPDATE_RAW_PUBLIC_KEY_SIZE))) { + ret = fota_nvm_set(UPDATE_PUBKEY, buffer_raw_key, FOTA_UPDATE_RAW_PUBLIC_KEY_SIZE); + } + free(buffer_raw_key); + return ret; +} +#endif // defined(FOTA_USE_EXTERNAL_UPDATE_RAW_PUBLIC_KEY) +#endif // defined(MBED_CLOUD_DEV_UPDATE_RAW_PUBLIC_KEY) + +#if !defined(FOTA_USE_EXTERNAL_UPDATE_RAW_PUBLIC_KEY) +int fota_nvm_get_update_public_key(uint8_t buffer[FOTA_UPDATE_RAW_PUBLIC_KEY_SIZE]) +{ + size_t bytes_read; + int ret = fota_nvm_get(UPDATE_PUBKEY, buffer, FOTA_UPDATE_RAW_PUBLIC_KEY_SIZE, &bytes_read); + FOTA_DBG_ASSERT(ret || (FOTA_UPDATE_RAW_PUBLIC_KEY_SIZE == bytes_read)); + return ret; +} +#endif // !defined(FOTA_USE_EXTERNAL_UPDATE_RAW_PUBLIC_KEY) + +#endif // defined(FOTA_USE_UPDATE_RAW_PUBLIC_KEY)§ + +/******************************************************************************************************/ +/* VENDOR and CLASS IDs */ +/******************************************************************************************************/ #if defined(MBED_CLOUD_DEV_UPDATE_ID) extern const uint8_t arm_uc_class_id[]; @@ -174,7 +247,7 @@ int fota_nvm_update_class_id_set(void) if (ret == FOTA_STATUS_NOT_FOUND || (ret == FOTA_STATUS_SUCCESS && 0 != memcmp(buffer, arm_uc_class_id, FOTA_GUID_SIZE))) { - ret = set(UPDATE_CLASS_ID, arm_uc_class_id, FOTA_GUID_SIZE); + ret = fota_nvm_set(UPDATE_CLASS_ID, arm_uc_class_id, FOTA_GUID_SIZE); } return ret; @@ -189,7 +262,7 @@ int fota_nvm_update_vendor_id_set(void) if (ret == FOTA_STATUS_NOT_FOUND || (ret == FOTA_STATUS_SUCCESS && 0 != memcmp(buffer, arm_uc_vendor_id, FOTA_GUID_SIZE))) { - ret = set(UPDATE_VENDOR_ID, arm_uc_vendor_id, FOTA_GUID_SIZE); + ret = fota_nvm_set(UPDATE_VENDOR_ID, arm_uc_vendor_id, FOTA_GUID_SIZE); } return ret; @@ -204,7 +277,7 @@ int fota_nvm_update_vendor_id_set(void) int fota_nvm_get_class_id(uint8_t buffer[FOTA_GUID_SIZE]) { size_t bytes_read; - int ret = get(UPDATE_CLASS_ID, buffer, FOTA_GUID_SIZE, &bytes_read); + int ret = fota_nvm_get(UPDATE_CLASS_ID, buffer, FOTA_GUID_SIZE, &bytes_read); FOTA_DBG_ASSERT(ret || (FOTA_GUID_SIZE == bytes_read)); return ret; @@ -213,7 +286,7 @@ int fota_nvm_get_class_id(uint8_t buffer[FOTA_GUID_SIZE]) int fota_nvm_get_vendor_id(uint8_t buffer[FOTA_GUID_SIZE]) { size_t bytes_read; - int ret = get(UPDATE_VENDOR_ID, buffer, FOTA_GUID_SIZE, &bytes_read); + int ret = fota_nvm_get(UPDATE_VENDOR_ID, buffer, FOTA_GUID_SIZE, &bytes_read); FOTA_DBG_ASSERT(ret || (FOTA_GUID_SIZE == bytes_read)); return ret; @@ -221,26 +294,6 @@ int fota_nvm_get_vendor_id(uint8_t buffer[FOTA_GUID_SIZE]) #endif // !defined(FOTA_USE_EXTERNAL_IDS) -int fota_nvm_salt_get(uint8_t buffer[FOTA_ENCRYPT_METADATA_SALT_LEN]) -{ - size_t bytes_read; - int ret = get(FOTA_SALT_KEY, buffer, FOTA_ENCRYPT_METADATA_SALT_LEN, &bytes_read); - FOTA_DBG_ASSERT(ret || (FOTA_ENCRYPT_METADATA_SALT_LEN == bytes_read)); - return ret; -} - -int fota_nvm_salt_set(const uint8_t buffer[FOTA_ENCRYPT_METADATA_SALT_LEN]) -{ - return set(FOTA_SALT_KEY, buffer, FOTA_ENCRYPT_METADATA_SALT_LEN); - -} - -int fota_nvm_salt_delete(void) -{ - ccs_status_e status = remove_config_parameter(FOTA_SALT_KEY); - return map_store_result(status); -} - /** We always saving manifest buffer max size, because storage backbends may have a requirement for * fixed size values when overwriting - the keys. * The assumption here is that the value of the manifest is ASN.1 encoded thus the parser will discard the trailing bytes. @@ -250,12 +303,22 @@ int fota_nvm_salt_delete(void) int fota_nvm_manifest_set(const uint8_t *buffer, size_t buffer_size) { int ret = FOTA_STATUS_INTERNAL_ERROR; + + if (FOTA_MANIFEST_MAX_SIZE < buffer_size) { + FOTA_TRACE_ERROR("Manifest size is too big for persisting %zu", buffer_size); + return FOTA_STATUS_INSUFFICIENT_STORAGE; + } + uint8_t *manifest = malloc(FOTA_MANIFEST_MAX_SIZE); - FOTA_ASSERT(manifest); + + if (!manifest) { + FOTA_TRACE_ERROR("FOTA manifest - allocation failed"); + return FOTA_STATUS_OUT_OF_MEMORY; + } memset(manifest, 0, FOTA_MANIFEST_MAX_SIZE); memcpy(manifest, buffer, buffer_size); - ret = set(FOTA_MANIFEST_KEY, manifest, FOTA_MANIFEST_MAX_SIZE); + ret = fota_nvm_set(FOTA_MANIFEST_KEY, manifest, FOTA_MANIFEST_MAX_SIZE); free(manifest); return ret; @@ -263,12 +326,12 @@ int fota_nvm_manifest_set(const uint8_t *buffer, size_t buffer_size) int fota_nvm_manifest_get(uint8_t *buffer, size_t buffer_size, size_t *bytes_read) { - return get(FOTA_MANIFEST_KEY, buffer, buffer_size, bytes_read); + return fota_nvm_get(FOTA_MANIFEST_KEY, buffer, buffer_size, bytes_read); } int fota_nvm_manifest_delete(void) { - remove_config_parameter(FOTA_MANIFEST_KEY); + fota_nvm_remove(FOTA_MANIFEST_KEY); return FOTA_STATUS_SUCCESS; } @@ -280,7 +343,7 @@ int fota_nvm_comp_version_set(const char *comp_name, fota_component_version_t ve FOTA_DBG_ASSERT(strlen(FOTA_COMP_VER_BASE) <= COMP_VER_BASE_KEY_SIZE); char key[COMP_VER_BASE_KEY_SIZE + FOTA_COMPONENT_MAX_NAME_SIZE]; sprintf(key, "%s%s", FOTA_COMP_VER_BASE, comp_name); - return set(key, (uint8_t *)&version, sizeof(version)); + return fota_nvm_set(key, (uint8_t *)&version, sizeof(version)); } int fota_nvm_comp_version_get(const char *comp_name, fota_component_version_t *version) @@ -289,7 +352,7 @@ int fota_nvm_comp_version_get(const char *comp_name, fota_component_version_t *v char key[COMP_VER_BASE_KEY_SIZE + FOTA_COMPONENT_MAX_NAME_SIZE]; size_t bytes_read; sprintf(key, "%s%s", FOTA_COMP_VER_BASE, comp_name); - return get(key, (uint8_t *)&version, sizeof(version), &bytes_read); + return fota_nvm_get(key, (uint8_t *)version, sizeof(*version), &bytes_read); } #endif // MBED_CLOUD_CLIENT_FOTA_ENABLE diff --git a/fota/fota_nvm.h b/fota/fota_nvm.h index c27e7db..c722372 100644 --- a/fota/fota_nvm.h +++ b/fota/fota_nvm.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -52,6 +52,7 @@ int fota_nvm_get_class_id(uint8_t buffer[FOTA_GUID_SIZE]); */ int fota_nvm_get_vendor_id(uint8_t buffer[FOTA_GUID_SIZE]); +#if defined(FOTA_USE_UPDATE_X509) /* * Get FOTA certificate from storage. * @@ -62,6 +63,11 @@ int fota_nvm_get_vendor_id(uint8_t buffer[FOTA_GUID_SIZE]); * \return FOTA_STATUS_SUCCESS on success. */ int fota_nvm_get_update_certificate(uint8_t *buffer, size_t size, size_t *bytes_read); +#endif // defined(FOTA_USE_UPDATE_X509) + +#if defined(FOTA_USE_UPDATE_RAW_PUBLIC_KEY) +int fota_nvm_get_update_public_key(uint8_t buffer[FOTA_UPDATE_RAW_PUBLIC_KEY_SIZE]); +#endif // defined(FOTA_USE_UPDATE_RAW_PUBLIC_KEY) /* * Get firmware encryption key from storage. @@ -80,32 +86,11 @@ int fota_nvm_fw_encryption_key_get(uint8_t buffer[FOTA_ENCRYPT_KEY_SIZE]); int fota_nvm_fw_encryption_key_set(const uint8_t buffer[FOTA_ENCRYPT_KEY_SIZE]); /* - * Get salt used for generating FW candidate encryption key. - * - * \param[out] buffer buffer for returning salt. - - * \return FOTA_STATUS_SUCCESS on success. - * \note buffer size expected to of the following size: FOTA_ENCRYPT_METADATA_SALT_LEN - */ -int fota_nvm_salt_get(uint8_t buffer[FOTA_ENCRYPT_METADATA_SALT_LEN]); - -/* - * Save salt used for generating FW candidate encryption key. + * Delete firmware encryption key in storage. * - * \param[in] buffer buffer with salt. - * \return FOTA_STATUS_SUCCESS on success - * \note buffer size expected to of the following size: FOTA_ENCRYPT_METADATA_SALT_LEN */ -int fota_nvm_salt_set(const uint8_t buffer[FOTA_ENCRYPT_METADATA_SALT_LEN]); - -/* - * Delete salt used for generating FW candidate encryption key. - * - * \return FOTA_STATUS_SUCCESS on success. - */ -int fota_nvm_salt_delete(void); - +int fota_nvm_fw_encryption_key_delete(void); /** * Get saved Pelion FOTA manifest. @@ -137,14 +122,14 @@ int fota_nvm_manifest_set(const uint8_t *buffer, size_t size); int fota_nvm_manifest_delete(void); -#ifdef MBED_CLOUD_DEV_UPDATE_ID +#if defined(MBED_CLOUD_DEV_UPDATE_ID) int fota_nvm_update_class_id_set(void); int fota_nvm_update_vendor_id_set(void); #endif -#ifdef MBED_CLOUD_DEV_UPDATE_CERT +#if defined(MBED_CLOUD_DEV_UPDATE_CERT) int fota_nvm_update_cert_set(void); @@ -170,6 +155,9 @@ int fota_nvm_comp_version_set(const char *comp_name, fota_component_version_t ve */ int fota_nvm_comp_version_get(const char *comp_name, fota_component_version_t *version); +#if defined(MBED_CLOUD_DEV_UPDATE_RAW_PUBLIC_KEY) +int fota_nvm_set_update_public_key(void); +#endif #ifdef __cplusplus } diff --git a/fota/fota_manifest_defs.h b/fota/fota_nvm_int.h similarity index 56% rename from fota/fota_manifest_defs.h rename to fota/fota_nvm_int.h index ff5848b..f5229fd 100644 --- a/fota/fota_manifest_defs.h +++ b/fota/fota_nvm_int.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -16,32 +16,24 @@ // limitations under the License. // ---------------------------------------------------------------------------- -#ifndef __FOTA_MANIFEST_DEFS_H_ -#define __FOTA_MANIFEST_DEFS_H_ +#ifndef __FOTA_NVM_INT_H_ +#define __FOTA_NVM_INT_H_ -#include "fota/fota_base.h" - -#ifndef FOTA_MANIFEST_SCHEMA_VERSION -#define FOTA_MANIFEST_SCHEMA_VERSION 3 +#ifdef __cplusplus +extern "C" { #endif -#ifndef FOTA_MANIFEST_URI_SIZE -#define FOTA_MANIFEST_URI_SIZE 256 -#endif +#include "fota/fota_base.h" +#include "CloudClientStorage.h" -#ifndef FOTA_MANIFEST_VENDOR_DATA_SIZE -#define FOTA_MANIFEST_VENDOR_DATA_SIZE 128 -#endif +int fota_nvm_get(cloud_client_param key, uint8_t *buffer, size_t buffer_size, size_t *bytes_read); -#define FOTA_MANIFEST_PAYLOAD_FORMAT_RAW 1 -#define FOTA_MANIFEST_PAYLOAD_FORMAT_DELTA 5 +int fota_nvm_set(cloud_client_param key, const uint8_t *buffer, size_t buffer_size); -#ifndef FOTA_MANIFEST_MAX_SIZE -#define FOTA_MANIFEST_MAX_SIZE 512 -#endif +int fota_nvm_remove(cloud_client_param key); -#ifndef FOTA_CERT_MAX_SIZE -#define FOTA_CERT_MAX_SIZE 600 +#ifdef __cplusplus +} #endif -#endif // __FOTA_MANIFEST_DEFS_H_ +#endif //__FOTA_NVM_INT_H_ diff --git a/fota/fota_platform.c b/fota/fota_platform.c deleted file mode 100644 index 05be972..0000000 --- a/fota/fota_platform.c +++ /dev/null @@ -1,58 +0,0 @@ -// ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. -// -// SPDX-License-Identifier: Apache-2.0 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ---------------------------------------------------------------------------- - -#include "fota/fota_base.h" - -#ifdef MBED_CLOUD_CLIENT_FOTA_ENABLE - -#include "fota/fota_platform.h" -#include "fota/fota_block_device.h" -#include "fota/fota_status.h" -#include "fota/fota_candidate.h" - -#if !defined(FOTA_CUSTOM_PLATFORM) || (!FOTA_CUSTOM_PLATFORM) - -int fota_platform_init_hook(bool after_upgrade) -{ - if (after_upgrade) { - int ret = fota_bd_init(); - if (!ret) { // Don't assert here as failure is not harsh and bd init is also done later - fota_candidate_erase(); - } - } - return FOTA_STATUS_SUCCESS; -} - -int fota_platform_start_update_hook(const char *comp_name) -{ - return FOTA_STATUS_SUCCESS; -} - -int fota_platform_finish_update_hook(const char *comp_name) -{ - return FOTA_STATUS_SUCCESS; -} - -int fota_platform_abort_update_hook(const char *comp_name) -{ - return FOTA_STATUS_SUCCESS; -} - -#endif // !defined(FOTA_CUSTOM_PLATFORM) || (!FOTA_CUSTOM_PLATFORM) - -#endif // MBED_CLOUD_CLIENT_FOTA_ENABLE diff --git a/fota/fota_platform.h b/fota/fota_platform.h index 2d8400b..f0ac3f2 100644 --- a/fota/fota_platform.h +++ b/fota/fota_platform.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -20,19 +20,78 @@ #define __FOTA_PLATFORM_H_ #include "fota/fota_base.h" +#include "fota/fota_status.h" +#include "fota/fota_block_device.h" +#include "fota/fota_candidate.h" #ifdef __cplusplus extern "C" { #endif + +#if defined(FOTA_CUSTOM_PLATFORM) && (FOTA_CUSTOM_PLATFORM) + +// Hooks that need to be supplied by platform specific code + +/** + * Platform init hook, called at FOTA module initialization. + * + * \param[in] after_upgrade Indicates that hook was called after an upgrade. + * \return FOTA_STATUS_SUCCESS on success. + */ int fota_platform_init_hook(bool after_upgrade); +/** + * Platform start update hook, called when update is started. + * + * \param[in] comp_name Component name. + * \return FOTA_STATUS_SUCCESS on success. + */ int fota_platform_start_update_hook(const char *comp_name); +/** + * Platform finish update hook, called when update is finished. + * + * \param[in] comp_name Component name. + * \return FOTA_STATUS_SUCCESS on success. + */ int fota_platform_finish_update_hook(const char *comp_name); +/** + * Platform start update hook, called when update is aborted. + * + * \param[in] comp_name Component name. + * \return FOTA_STATUS_SUCCESS on success. + */ int fota_platform_abort_update_hook(const char *comp_name); +#else + +#ifdef __MBED__ +// Default platform hooks +static inline int fota_platform_init_hook(bool after_upgrade) +{ + return FOTA_STATUS_SUCCESS; +} +#endif + +static inline int fota_platform_start_update_hook(const char *comp_name) +{ + return FOTA_STATUS_SUCCESS; +} + +static inline int fota_platform_finish_update_hook(const char *comp_name) +{ + return FOTA_STATUS_SUCCESS; +} + +static inline int fota_platform_abort_update_hook(const char *comp_name) +{ + return FOTA_STATUS_SUCCESS; +} + +#endif // !defined(FOTA_CUSTOM_PLATFORM) || (!FOTA_CUSTOM_PLATFORM) + #ifdef __cplusplus } #endif diff --git a/fota/fota_source.c b/fota/fota_source.c index 271f7e5..41093dc 100644 --- a/fota/fota_source.c +++ b/fota/fota_source.c @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -20,52 +20,119 @@ #ifdef MBED_CLOUD_CLIENT_FOTA_ENABLE +#define TRACE_GROUP "FOTA" + #include "fota/fota_source.h" #include "fota/fota_source_defs.h" #include "fota/fota_crypto_defs.h" #include "fota/fota_status.h" #include "fota/fota_internal.h" #include "fota/fota_event_handler.h" +#include "fota/fota_component_defs.h" +#include "fota/fota_component_internal.h" +#ifdef MBED_CLOUD_CLIENT_DISABLE_REGISTRY +#include "fota/fota_nvm.h" +#endif #include "mbed-client/lwm2m_endpoint.h" -#include "mbed-client/lwm2m_get_req_handler.h" +#include "mbed-client/lwm2m_req_handler.h" #include "device-management-client/lwm2m_registry_handler.h" #include +#if (FOTA_SOURCE_LEGACY_OBJECTS_REPORT == 1) +#define PROTOCOL_VERSION 3 +#else +// TODO: Move to 4 when issues with service are resolved #define PROTOCOL_VERSION 3 +#endif static endpoint_t *endpoint = 0; +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY static registry_t *registry; const int64_t default_int_val = -1; +#endif + static bool initialized = false; +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY static report_sent_callback_t g_on_sent_callback = NULL; static report_sent_callback_t g_on_failure_callback = NULL; +#else +static const char *manifest_res_id = "/10252/0/1"; +static const char *state_res_id = "/10252/0/2"; +static const char *protocol_version_res_id = "/10255/0/0"; +static const char *vendor_id_res_id = "/10255/0/3"; +static const char *class_id_res_id = "/10255/0/4"; +static const char *main_comp_name_res_id = "/14/0/0"; +static const char *main_comp_sem_ver_res_id = "/14/0/2"; + +static uint8_t fota_vendor_id[FOTA_GUID_SIZE]; +static uint32_t fota_vendor_id_size; +static uint8_t fota_class_id[FOTA_GUID_SIZE]; +static uint32_t fota_class_id_size; +static char main_comp_name[FOTA_COMPONENT_MAX_NAME_SIZE]; +static char main_comp_sem_ver[FOTA_COMPONENT_MAX_SEMVER_STR_SIZE]; +static int fota_state; +#endif static registry_path_t execute_path = { 0 }; static registry_callback_token_t execute_token = { 0 }; +typedef struct { + size_t max_frag_size; + bool allow_unaligned_fragments; +} fota_source_config_t; + +fota_source_config_t fota_source_config = { +#ifdef SN_COAP_MAX_BLOCKWISE_PAYLOAD_SIZE + .max_frag_size = SN_COAP_MAX_BLOCKWISE_PAYLOAD_SIZE, + // COAP doesn't allow non aligned fragments. + // TODO: Make sure it's true in all cases + .allow_unaligned_fragments = false, +#else + // This is true in tests only currently, so values will be set by test code. + .max_frag_size = 0, + .allow_unaligned_fragments = false, +#endif +}; + static void cleanup(void) { - +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY + g_on_sent_callback = NULL; + g_on_failure_callback = NULL; +#endif } - static registry_status_t got_manifest_callback(registry_callback_type_t type, const registry_path_t *path, const registry_callback_token_t *token, const registry_object_value_t *value, const registry_notification_status_t status, - registry_t *registry) +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY + registry_t *registry +#else + void *endpoint +#endif + ) { registry_status_t callback_status = REGISTRY_STATUS_OK; sn_coap_msg_code_e response = COAP_MSG_CODE_RESPONSE_CHANGED; - fota_state_e fota_state = fota_is_ready(value->generic_value.data.opaque_data->data, - value->generic_value.data.opaque_data->size); + fota_state_e fota_state; + + int ret = fota_is_ready(value->generic_value.data.opaque_data->data, + value->generic_value.data.opaque_data->size, &fota_state); + + if (ret == FOTA_STATUS_OUT_OF_MEMORY) { + callback_status = REGISTRY_STATUS_NO_MEMORY; + goto fail; + } + switch (fota_state) { case FOTA_STATE_IDLE: { +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY registry_path_t res_path; registry_set_path(&res_path, FOTA_SOURCE_PACKAGE_OBJECT_ID, 0, FOTA_SOURCE_STATE_RESOURCE_ID, @@ -79,30 +146,42 @@ static registry_status_t got_manifest_callback(registry_callback_type_t type, if (REGISTRY_STATUS_OK != registry_set_value_empty(registry, &res_path, true)) { FOTA_DBG_ASSERT(!"registry_set_value_empty failed"); } +#endif memcpy(&execute_token, token, sizeof(execute_token)); memcpy(&execute_path, path, sizeof(execute_path)); +#if 0 fota_event_handler_defer_with_data( fota_on_manifest, value->generic_value.data.opaque_data->data, value->generic_value.data.opaque_data->size ); +#endif + // Call directly instead of deferring (like the commented out code above), + // as manifest handling is short now + fota_on_manifest(value->generic_value.data.opaque_data->data, + value->generic_value.data.opaque_data->size); break; } case FOTA_STATE_INVALID: FOTA_TRACE_ERROR("FOTA cannot handle manifest - rejecting"); - response = COAP_MSG_CODE_RESPONSE_SERVICE_UNAVAILABLE; - callback_status = REGISTRY_STATUS_ALREADY_EXISTS; + response = COAP_MSG_CODE_RESPONSE_PRECONDITION_FAILED; // fallthrough default: send_final_response( - path, registry->notifier->endpoint, + path, +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY + registry->notifier->endpoint, +#else + (endpoint_t *)endpoint, +#endif token->token, token->token_size, response, false ); } +fail: // Reset tainted buffer memset(value->generic_value.data.opaque_data->data, 0, value->generic_value.data.opaque_data->size); @@ -123,7 +202,7 @@ void fota_source_send_manifest_received_ack(void) memset(&execute_path, 0, sizeof(execute_path)); } - +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY static registry_status_t notification_status(registry_callback_type_t type, const registry_path_t *path, const registry_callback_token_t *token, @@ -179,8 +258,98 @@ static registry_status_t notification_status(registry_callback_type_t type, } return REGISTRY_STATUS_OK; } +#endif + +#ifdef MBED_CLOUD_CLIENT_DISABLE_REGISTRY -#if FOTA_SOURCE_COMPONENT_BACKWARD_COMPATIBILITY_MODE +#if (FOTA_SOURCE_LEGACY_OBJECTS_REPORT == 1) +#error MBED_CLOUD_CLIENT_DISABLE_REGISTRY only supported for MCCP=4 +#endif + +static int get_fota_resources(endpoint_t *endpoint, register_resource_t **res) +{ + register_resource_t *curr; + + curr = endpoint_create_register_resource(endpoint, manifest_res_id, false); + *res = curr; + if (!curr) { + return -1; + } + + curr->next = endpoint_create_register_resource_int(endpoint, state_res_id, true, fota_state); + curr = curr->next; + if (!curr) { + return -1; + } + + curr->next = endpoint_create_register_resource_int(endpoint, protocol_version_res_id, true, PROTOCOL_VERSION); + curr = curr->next; + if (!curr) { + return -1; + } + + curr->next = endpoint_create_register_resource_opaque(endpoint, vendor_id_res_id, true, fota_vendor_id, fota_vendor_id_size); + curr = curr->next; + if (!curr) { + return -1; + } + + curr->next = endpoint_create_register_resource_opaque(endpoint, class_id_res_id, true, fota_class_id, fota_class_id_size); + curr = curr->next; + if (!curr) { + return -1; + } + + curr->next = endpoint_create_register_resource_str(endpoint, main_comp_name_res_id, true, (uint8_t *)main_comp_name, strlen(main_comp_name)); + curr = curr->next; + if (!curr) { + return -1; + } + + curr->next = endpoint_create_register_resource_str(endpoint, main_comp_sem_ver_res_id, true, (uint8_t *)main_comp_sem_ver, strlen(main_comp_sem_ver)); + curr = curr->next; + if (!curr) { + return -1; + } + + return 0; +} + + +static sn_coap_hdr_s *on_coap_request(const registry_path_t *path, + endpoint_t *endpoint, + const sn_coap_hdr_s *request, + sn_nsdl_addr_s *address, + sn_coap_hdr_s *response, + int *acked) +{ + FOTA_TRACE_DEBUG("on_coap_request()"); + + if (0 != memcmp("10252/0/1", (char *)request->uri_path_ptr, request->uri_path_len)) { + response->msg_code = COAP_MSG_CODE_RESPONSE_NOT_FOUND; + } else { + FOTA_TRACE_DEBUG("on_coap_request() - response code: %d", response->msg_code); + response->msg_code = COAP_MSG_CODE_EMPTY; + registry_callback_t callback = endpoint_get_object_callback(endpoint, FOTA_SOURCE_PACKAGE_OBJECT_ID); + if (callback) { + if (send_callback_data(path, request, REGISTRY_CALLBACK_EXECUTE)) { + endpoint->confirmable_response.pending = true; + response->msg_code = COAP_MSG_CODE_EMPTY; + endpoint_send_coap_message(endpoint, address, response); + *acked = 1; + } else { + response->msg_code = COAP_MSG_CODE_RESPONSE_INTERNAL_SERVER_ERROR; + } + } else { + response->msg_code = COAP_MSG_CODE_RESPONSE_NOT_FOUND; + } + } + + return response; +} +#endif + +#if (FOTA_SOURCE_LEGACY_OBJECTS_REPORT == 1) /* * Converting binary array to hex string * @@ -209,26 +378,36 @@ static void bin_to_hex_string(const uint8_t *in, size_t input_size, uint8_t *out } #endif +void fota_source_set_config(size_t max_frag_size, bool allow_unaligned_fragments) +{ + fota_source_config.allow_unaligned_fragments = allow_unaligned_fragments; + fota_source_config.max_frag_size = max_frag_size; +} + int fota_source_init( endpoint_t *in_endpoint, const uint8_t *vendor_id, uint32_t vendor_id_size, const uint8_t *class_id, uint32_t class_id_size, -#if FOTA_SOURCE_COMPONENT_BACKWARD_COMPATIBILITY_MODE const uint8_t *curr_fw_digest, uint32_t curr_fw_digest_size, uint64_t curr_fw_version, -#endif fota_source_state_e source_state) { -#if FOTA_SOURCE_COMPONENT_BACKWARD_COMPATIBILITY_MODE +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY +#if (FOTA_SOURCE_LEGACY_OBJECTS_REPORT == 1) uint8_t str_digest[FOTA_CRYPTO_HASH_SIZE * 2 + 1]; +#endif #endif if (initialized) { return FOTA_STATUS_SUCCESS; } + FOTA_DBG_ASSERT(fota_source_config.max_frag_size); + endpoint = in_endpoint; + +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY registry = &endpoint->registry; registry_path_t path; @@ -241,6 +420,7 @@ int fota_source_init( } // Create state resource /10252/0/2 + FOTA_TRACE_DEBUG("Announcing FOTA state is %d", source_state); registry_set_path(&path, FOTA_SOURCE_PACKAGE_OBJECT_ID, 0, FOTA_SOURCE_STATE_RESOURCE_ID, 0, REGISTRY_PATH_RESOURCE); if (REGISTRY_STATUS_OK != registry_set_value_int(registry, &path, source_state) || @@ -254,12 +434,12 @@ int fota_source_init( registry_set_path(&path, FOTA_SOURCE_PACKAGE_OBJECT_ID, 0, FOTA_SOURCE_UPDATE_RESULT_RESOURCE_ID, 0, REGISTRY_PATH_RESOURCE); if (REGISTRY_STATUS_OK != registry_set_value_int(registry, &path, default_int_val) || - REGISTRY_STATUS_OK != registry_set_auto_observable_parameter(registry, &path, true) || - REGISTRY_STATUS_OK != registry_set_resource_value_to_reg_msg(registry, &path, true)) { + REGISTRY_STATUS_OK != registry_set_auto_observable_parameter(registry, &path, true)) { goto fail; } // Create protocol supported resource /10255/0/0 + FOTA_TRACE_DEBUG("Announcing MCCP is %d", PROTOCOL_VERSION); registry_set_path(&path, FOTA_SOURCE_UPDATE_OBJECT_ID, 0, FOTA_SOURCE_PROTOCOL_SUPP_RESOURCE_ID, 0, REGISTRY_PATH_RESOURCE); if (REGISTRY_STATUS_OK != registry_set_value_int(registry, &path, PROTOCOL_VERSION) || @@ -288,7 +468,7 @@ int fota_source_init( goto fail; } -#if FOTA_SOURCE_COMPONENT_BACKWARD_COMPATIBILITY_MODE +#if (FOTA_SOURCE_LEGACY_OBJECTS_REPORT == 1) // Create package name resource /10252/0/5 FOTA_DBG_ASSERT(curr_fw_digest_size == FOTA_CRYPTO_HASH_SIZE); @@ -303,6 +483,7 @@ int fota_source_init( } // Create package version resource /10252/0/6 + FOTA_TRACE_DEBUG("Announcing version is %" PRIu64, curr_fw_version); registry_set_path(&path, FOTA_SOURCE_PACKAGE_OBJECT_ID, 0, FOTA_SOURCE_PKG_VERSION_RESOURCE_ID, 0, REGISTRY_PATH_RESOURCE); @@ -312,7 +493,25 @@ int fota_source_init( goto fail; } #endif +#else // MBED_CLOUD_CLIENT_DISABLE_REGISTRY + memcpy(fota_vendor_id, vendor_id, vendor_id_size); + fota_vendor_id_size = vendor_id_size; + memcpy(fota_class_id, class_id, class_id_size); + fota_class_id_size = class_id_size; + fota_state = (int) source_state; + strcpy(main_comp_name, FOTA_COMPONENT_MAIN_COMPONENT_NAME); + fota_component_version_int_to_semver(curr_fw_version, main_comp_sem_ver); + + // Register the fota package object because it needs to be able to handle coap requests + // The resource callback registered here is used to add all resources in this module, even those technically for a different object + object_handler_t *handler = endpoint_allocate_object_handler(FOTA_SOURCE_PACKAGE_OBJECT_ID, get_fota_resources, on_coap_request, got_manifest_callback); + if (!handler) { + FOTA_ASSERT(!"Failed to allocate object handler"); // if this happens it's a fatal error + goto fail; + } + endpoint_register_object_handler(endpoint, handler); +#endif initialized = true; return FOTA_STATUS_SUCCESS; @@ -323,7 +522,8 @@ int fota_source_init( int fota_source_add_component(unsigned int comp_id, const char *name, const char *sem_ver) { -#if !FOTA_SOURCE_COMPONENT_BACKWARD_COMPATIBILITY_MODE +#if (FOTA_SOURCE_LEGACY_OBJECTS_REPORT == 0) +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY registry_path_t path; // Create Component Identity resource /14//0 @@ -344,6 +544,8 @@ int fota_source_add_component(unsigned int comp_id, const char *name, const char return FOTA_STATUS_INTERNAL_ERROR; } #endif +#endif + return FOTA_STATUS_SUCCESS; } @@ -357,6 +559,7 @@ int fota_source_deinit(void) initialized = false; +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY registry_path_t path; registry_set_path(&path, FOTA_SOURCE_PACKAGE_OBJECT_ID, 0, 0, 0, REGISTRY_PATH_OBJECT); registry_remove_object(registry, &path, REGISTRY_REMOVE); @@ -364,11 +567,15 @@ int fota_source_deinit(void) registry_remove_object(registry, &path, REGISTRY_REMOVE); registry_set_path(&path, FOTA_SOURCE_SW_COMPONENT_OBJECT_ID, 0, 0, 0, REGISTRY_PATH_OBJECT); registry_remove_object(registry, &path, REGISTRY_REMOVE); +#else + endpoint_remove_object_handler(endpoint, FOTA_SOURCE_PACKAGE_OBJECT_ID); +#endif return FOTA_STATUS_SUCCESS; } -static int report_int(int vlaue, int16_t resource_id, report_sent_callback_t on_sent, report_sent_callback_t on_failure) +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY +static int report_int(int value, int16_t resource_id, report_sent_callback_t on_sent, report_sent_callback_t on_failure) { FOTA_DBG_ASSERT(!g_on_sent_callback); FOTA_DBG_ASSERT(!g_on_failure_callback); @@ -380,25 +587,39 @@ static int report_int(int vlaue, int16_t resource_id, report_sent_callback_t on_ registry_path_t path; registry_set_path(&path, FOTA_SOURCE_PACKAGE_OBJECT_ID, 0, resource_id, 0, REGISTRY_PATH_RESOURCE); - FOTA_TRACE_DEBUG("Reporting resource: /%d/%d/%d: value: %d", path.object_id, path.object_instance_id, path.resource_id, vlaue); - if (REGISTRY_STATUS_OK != registry_set_value_int(registry, &path, vlaue)) { + FOTA_TRACE_DEBUG("Reporting resource: /%d/%d/%d: value: %d", path.object_id, path.object_instance_id, path.resource_id, value); + if (REGISTRY_STATUS_OK != registry_set_value_int(registry, &path, value)) { g_on_sent_callback = NULL; g_on_failure_callback = NULL; return FOTA_STATUS_INTERNAL_ERROR; } return FOTA_STATUS_SUCCESS; - } +#endif int fota_source_report_state(fota_source_state_e state, report_sent_callback_t on_sent, report_sent_callback_t on_failure) { +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY return report_int((int)state, FOTA_SOURCE_STATE_RESOURCE_ID, on_sent, on_failure); // 10252/0/2 +#else + fota_state = state; + // state isn't actually being reported, so just pretend it was successful + if (on_sent) { + on_sent(); + } + return FOTA_STATUS_SUCCESS; +#endif } int fota_source_report_update_result(int result) { +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY return report_int(result, FOTA_SOURCE_UPDATE_RESULT_RESOURCE_ID, NULL, NULL); // 10252/0/3 +#else + // result isn't actually being reported, so just pretend it was successful + return FOTA_STATUS_SUCCESS; +#endif } static void data_req_callback(const uint8_t *buffer, size_t buffer_size, size_t total_size, bool last_block, @@ -406,6 +627,13 @@ static void data_req_callback(const uint8_t *buffer, size_t buffer_size, size_t { bool is_active = fota_is_active_update(); if (is_active) { + // Extract original offset from context + uint32_t offset = (uint32_t) context; + if (!fota_source_config.allow_unaligned_fragments) { + uint32_t extra = offset % fota_source_config.max_frag_size; + buffer_size -= extra; + buffer += extra; + } // removing const qualifier here allows FOTA the manipulation of fragment data in place (like encryption). // TODO: Need to decide whether this is legit. If so, all preceding LWM2M calls should also remove this qualifier. fota_on_fragment((uint8_t *)buffer, buffer_size); @@ -426,8 +654,15 @@ static void data_req_error_callback(get_data_req_error_t error_code, void *conte int fota_source_firmware_request_fragment(const char *uri, uint32_t offset) { - get_handler_send_get_data_request(endpoint, FIRMWARE_DOWNLOAD, uri, offset, true, // TODO: verify async = True - data_req_callback, data_req_error_callback, NULL); + uint32_t extra = 0; + if (!fota_source_config.allow_unaligned_fragments) { + extra = offset % fota_source_config.max_frag_size; + } + + // Make sure that offset is aligned to fragment size in case limited by platform (like currently in COAP) + // Send original offset in context for callback + req_handler_send_data_request(endpoint, FIRMWARE_DOWNLOAD, COAP_MSG_CODE_REQUEST_GET, uri, offset - extra, true, + data_req_callback, data_req_error_callback, (void *) offset, NULL, 0); return FOTA_STATUS_SUCCESS; } diff --git a/fota/fota_source.h b/fota/fota_source.h index 588dbf3..f5cb0d9 100644 --- a/fota/fota_source.h +++ b/fota/fota_source.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -25,12 +25,6 @@ extern "C" { #endif -// Temporary backward compatibility mode - send older version & digest objects -// until integration with service is over -#ifndef FOTA_SOURCE_COMPONENT_BACKWARD_COMPATIBILITY_MODE -#define FOTA_SOURCE_COMPONENT_BACKWARD_COMPATIBILITY_MODE 1 -#endif - typedef enum { // Keep values conforming to the openmobile standard (omitting the ones that aren't reported) FOTA_SOURCE_STATE_INVALID = -1, @@ -45,14 +39,14 @@ typedef enum { typedef struct endpoint_s endpoint_t; +void fota_source_set_config(size_t max_frag_size, bool allow_unaligned_fragments); + int fota_source_init( endpoint_t *in_endpoint, const uint8_t *vendor_id, uint32_t vendor_id_size, const uint8_t *class_id, uint32_t class_id_size, -#if FOTA_SOURCE_COMPONENT_BACKWARD_COMPATIBILITY_MODE const uint8_t *curr_fw_digest, uint32_t curr_fw_digest_size, uint64_t curr_fw_version, -#endif fota_source_state_e source_state); int fota_source_add_component(unsigned int comp_id, const char *name, const char *sem_ver); diff --git a/fota/fota_source_defs.h b/fota/fota_source_defs.h index ac87d0e..f183ce3 100644 --- a/fota/fota_source_defs.h +++ b/fota/fota_source_defs.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // diff --git a/fota/fota_status.h b/fota/fota_status.h index 5781d72..70b8145 100644 --- a/fota/fota_status.h +++ b/fota/fota_status.h @@ -1,5 +1,5 @@ // ---------------------------------------------------------------------------- -// Copyright 2018-2019 ARM Ltd. +// Copyright 2018-2020 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // @@ -44,6 +44,8 @@ typedef enum { FOTA_STATUS_FW_DOWNLOAD_TIMEOUT = -15, /**< timed out downloading asset */ FOTA_STATUS_FW_UNSUPPORTED_DELTA_FORMAT = -16, /**< unsupported delta format */ FOTA_STATUS_FW_UNSUPPORTED_ENCRYPT_FORMAT = -17, /**< unsupported encryption format */ + FOTA_STATUS_FW_DELTA_REQUIRED_MORE_DATA = -18, /**< delta engine requred more data to proceed */ + FOTA_STATUS_MANIFEST_PAYLOAD_CORRUPTED = -102, /**< payload digest does not match to the one specified by manifest */ @@ -57,11 +59,13 @@ typedef enum { FOTA_STATUS_MANIFEST_WRONG_CLASS_ID = -216, /**< manifest with wrong class id */ FOTA_STATUS_MANIFEST_INVALID_SIZE = -217, /**< malformed manifest - invalid size */ FOTA_STATUS_MANIFEST_WRITE_ERROR = -227, /**< manifest processing error, write error */ + FOTA_STATUS_MANIFEST_SEMVER_ERROR = -228, /**< error parsing semantic version */ FOTA_STATUS_SOURCE_STATE_UPDATE_ERROR = -310, /**< resource fetching, user-defined error 2 **/ FOTA_STATUS_RESOURCE_NOT_AVAILABLE = -311, /**< resource fetching, user-defined error 3 **/ FOTA_STATUS_UNEXPECTED_COMPONENT = -312, /**< resource fetching, user-defined error 5 **/ FOTA_STATUS_DOWNLOAD_AUTH_NOT_GRANTED = -313, /**< application rejected download authorization request */ + FOTA_STATUS_FW_INSTALLATION_FAILED = -314, /**< update failed at installation phase */ FOTA_STATUS_FW_SIZE_MISMATCH = -400, /**< payload processing, nonspecific error */ FOTA_STATUS_STORAGE_READ_FAILED = -401, /**< payload processing, user-defined error 1 **/ @@ -77,6 +81,7 @@ typedef enum { FOTA_STATUS_INTERNAL_ERROR = -509, /**< payload writing error, user-defined error 4 **/ FOTA_STATUS_INVALID_ARGUMENT = -510, /**< payload writing error, user-defined error 5 **/ FOTA_STATUS_INSTALL_AUTH_NOT_GRANTED = -511, /**< application rejected install authorization request */ + FOTA_STATUS_INSTALL_DEFER_UNSUPPORTED = -513, /**< application deferred install when not supported */ } fota_status_e; diff --git a/fota/mbed_lib.json b/fota/mbed_lib.json index b1e82ac..4ac356c 100644 --- a/fota/mbed_lib.json +++ b/fota/mbed_lib.json @@ -22,9 +22,9 @@ "macro_name": "MBED_CLOUD_CLIENT_FOTA_ENCRYPTION_SUPPORT", "value": null }, - "encryption-block-size": { - "help": "FW candidate encryption block size - only relevant if fota.encryption-support is true", - "macro_name": "MBED_CLOUD_CLIENT_FOTA_ENCRYPT_BLOCK_SIZE", + "candidate-block-size": { + "help": "FW candidate block size in storage - only relevant if encrypted or if resume is supported", + "macro_name": "MBED_CLOUD_CLIENT_FOTA_CANDIDATE_BLOCK_SIZE", "value": 1024 }, "trace-enable": { @@ -40,18 +40,13 @@ "app-default-cb-no-print": { "help": "Disable prints in default implementation of application callbacks code", "macro_name": "FOTA_APP_DEFAULT_CB_NO_PRINT", - "value": null + "value": 1 }, "is-bootloader": { "help": "True when FOTA runs from bootloader", "macro_name": "FOTA_IS_BOOTLOADER", "value": null }, - "simulate-random": { - "help": "Enable simulation of random generation code", - "macro_name": "FOTA_SIMULATE_RANDOM", - "value": null - }, "fi-mitigation-enable": { "help": "Enable FI mitigation macros", "macro_name": "FOTA_FI_MITIGATION_ENABLE", @@ -62,6 +57,12 @@ "macro_name": "FOTA_NUM_COMPONENTS", "value": 1 }, + "resume-support": { + "help": "Type of resume support: unsupported, restart only, resume", + "macro_name": "MBED_CLOUD_CLIENT_FOTA_RESUME_SUPPORT", + "accepted_values": ["FOTA_RESUME_UNSUPPORTED", "FOTA_RESUME_SUPPORT_RESTART", "FOTA_RESUME_SUPPORT_RESUME"], + "value": "FOTA_RESUME_SUPPORT_RESUME" + }, "delta-block-size": { "help": "size of bsdiff blocks used to create delta-update", "macro_name": "MBED_CLOUD_CLIENT_FOTA_DELTA_BLOCK_SIZE", diff --git a/mbed-client/mbed-client/est_defs.h b/mbed-client/mbed-client/est_defs.h new file mode 100644 index 0000000..ba58452 --- /dev/null +++ b/mbed-client/mbed-client/est_defs.h @@ -0,0 +1,84 @@ +// ---------------------------------------------------------------------------- +// Copyright 2018-2020 ARM Ltd. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------- + +/** \file est_defs.h +* \brief Definitions for certificate chain structures and Enrollment over Secure +* Transport (EST) callback. +*/ + +#ifndef __EST_DEFS_H__ +#define __EST_DEFS_H__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** +* The structure describing a certificate within a certificate chain. +* \param cert_length, The length of the certificate. +* \param cert, A buffer containing the certificate. +* \param next, A pointer to the next certificate in chain, NULL if last certificate. +*/ +struct cert_context_s { + uint16_t cert_length; + uint8_t *cert; + struct cert_context_s *next; +}; + +/** +* The structure describing a certificate chain with. +* \param chain_length, The number of certificates in the certificate chain. +* \param cert_data_context, A context pointer, user should ignore. +* \param first_cert, A pointer to the first certificate in chain. +*/ +struct cert_chain_context_s { + uint8_t chain_length; + void *cert_data_context; + struct cert_context_s *certs; +}; + +typedef enum { + EST_ENROLLMENT_SUCCESS, + EST_ENROLLMENT_FAILURE +} est_enrollment_result_e; + +typedef enum { + EST_STATUS_SUCCESS, + EST_STATUS_INVALID_PARAMETERS, + EST_STATUS_MEMORY_ALLOCATION_FAILURE +} est_status_e; + +/** +* \brief When the enrollment result has been handled by the callback, the free_cert_chain_context +* function must be called with the cert_chain as parameter to free the certificate chain +* buffer(s). +* \param result, The result of the enrollment operation. +* \param cert_chain, A pointer to cert_chain_context_s if enrollment was successful, otherwise NULL. +* \param context, The user context. +*/ +typedef void(*est_enrollment_result_cb)(est_enrollment_result_e result, + struct cert_chain_context_s *cert_chain, + void *context); + +#ifdef __cplusplus +} +#endif + +#endif // __EST_DEFS_H__ diff --git a/mbed-client/mbed-client/lwm2m_callback_handler.h b/mbed-client/mbed-client/lwm2m_callback_handler.h index 53a543f..c234a2b 100644 --- a/mbed-client/mbed-client/lwm2m_callback_handler.h +++ b/mbed-client/mbed-client/lwm2m_callback_handler.h @@ -25,7 +25,11 @@ extern "C" { #endif +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY #include "lwm2m_registry.h" +#else +#include "lwm2m_endpoint.h" +#endif #define CALLBACK_HANDLER_EVENT_INIT 0 ///< Callback handler init event #define CALLBACK_HANDLER_EVENT_ID 40 ///< Callback handler event ID @@ -46,7 +50,11 @@ typedef struct callback_data_s { * * \param registry The registry that is associated with this callback handler. */ +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY void callback_handler_init(registry_t *registry); +#else +void callback_handler_init(endpoint_t *endpoint); +#endif /** * \brief Send callback handler event. diff --git a/mbed-client/mbed-client/lwm2m_config.h b/mbed-client/mbed-client/lwm2m_config.h index 6390d4d..9ec64bb 100644 --- a/mbed-client/mbed-client/lwm2m_config.h +++ b/mbed-client/mbed-client/lwm2m_config.h @@ -16,7 +16,7 @@ #ifndef M2MCONFIG_H #define M2MCONFIG_H -/*! \file m2mconfig.h +/*! \file lwm2m_config.h * \brief File defining all system build time configuration used by mbed-client. */ diff --git a/mbed-client/mbed-client/lwm2m_endpoint.h b/mbed-client/mbed-client/lwm2m_endpoint.h index 176c518..936286a 100644 --- a/mbed-client/mbed-client/lwm2m_endpoint.h +++ b/mbed-client/mbed-client/lwm2m_endpoint.h @@ -22,6 +22,7 @@ #include "lwm2m_notifier.h" #include "lwm2m_send_queue.h" #include "eventOS_event.h" +#include "protoman.h" /** \file lwm2m_endpoint.h * \brief Client Lite internal LwM2M and Device Management endpoint logic API. @@ -93,14 +94,20 @@ typedef struct endpoint_confirmable_response_s { } endpoint_confirmable_response_t; +#ifdef MBED_CLOUD_CLIENT_DISABLE_REGISTRY +typedef struct object_handler_s object_handler_t; +#endif + /** * \brief Main data structure for Client Lite LwM2M endpoint. */ typedef struct endpoint_s { send_queue_t send_queue; ///< Data allocated for send queue. +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY registry_t registry; ///< Data allocated for registry. notifier_t notifier; ///< Data allocated for notifier. +#endif endpoint_confirmable_response_t confirmable_response; ///< Data allocated for storing a response. struct connection_s *connection; ///< Pointer to connection. struct coap_s *coap; ///< Pointer to the CoAP library. @@ -125,8 +132,49 @@ typedef struct endpoint_s { bool coap_ping_request:1; ///< CoAP ping request is pending. #endif +#ifdef MBED_CLOUD_CLIENT_DISABLE_REGISTRY + object_handler_t *object_handlers; //Object owners +#if MBED_CLIENT_ENABLE_AUTO_OBSERVATION + uint16_t auto_obs_token; ///< For internal use only, MUST NOT be accessed from application. +#endif + uint32_t lifetime; + uint8_t security_mode; + char *server_uri; +#endif + } endpoint_t; +#ifdef MBED_CLOUD_CLIENT_DISABLE_REGISTRY +typedef struct register_resource_s register_resource_t; + +struct register_resource_s { + const char *full_res_id; // in form "/1/0/1" - the buffer pointed to must exist for the lifetime of the struct instance + uint16_t aobs_id; + +#if MBED_CLIENT_ENABLE_PUBLISH_RESOURCE_VALUE_IN_REG_MSG + uint8_t *value; //NOTE: Use lwm2m_alloc! + uint16_t value_len; +#endif + register_resource_t *next; +}; + +// Allocate and populate list of resources. Ownership will be transferred to caller, who must free the resources when done. +typedef int (get_resources_cb)(endpoint_t *endpoint, register_resource_t **resources); +typedef sn_coap_hdr_s *(coap_req_cb)(const registry_path_t* path, + endpoint_t *endpoint, + const sn_coap_hdr_s *request, + sn_nsdl_addr_s *src_addr, + sn_coap_hdr_s *response, + int *acked); + +struct object_handler_s { + uint16_t object_id; + get_resources_cb *res_cb; + coap_req_cb *req_cb; + registry_callback_t obj_cb; + object_handler_t *next; +}; +#endif /** * \brief Initialize the endpoint structure. @@ -375,6 +423,55 @@ void endpoint_start_coap_exec_timer(endpoint_t *endpoint); void endpoint_send_coap_ping(endpoint_t *endpoint); #endif +#ifdef MBED_CLOUD_CLIENT_DISABLE_REGISTRY +/** + * @brief Register object handler + * + * Register object handlers allocated with `endpoint_allocate_object_handler`. + * + * \note When registering multiple handlers from a single source they can be passed in as a list, + * and in this case only one needs to set the res_cb pointer. One res_cb instance + * can iterate through all needed resources. + * + * @param endpoint Pointer to the endpoint. + * @param owner A list of objects owned. Ownership is transferred. + */ +void endpoint_register_object_handler(endpoint_t *endpoint, object_handler_t *handler); + +void endpoint_remove_object_handler(endpoint_t *endpoint, uint16_t object_id); + +/** + * @brief Allocate object handler + * + * @param object_id ID of the object. + * @param res_cb Resource list getter callback. + * @param req_cb Coap request handler callback. + * @param obj_cb Object callback. + * @return pointer to object_handler or NULL if no memory + */ +object_handler_t *endpoint_allocate_object_handler(uint16_t object_id, get_resources_cb *res_cb, + coap_req_cb *req_cb, registry_callback_t obj_cb); + +register_resource_t *endpoint_create_register_resource_str(endpoint_t *endpoint, const char *id, + bool auto_obs, const uint8_t *value, + uint16_t len); + +register_resource_t *endpoint_create_register_resource_int(endpoint_t *endpoint, const char *id, + bool auto_obs, int64_t val); + +register_resource_t *endpoint_create_register_resource_opaque(endpoint_t *endpoint, const char *id, + bool auto_obs, const uint8_t *value, + uint16_t len); + +register_resource_t *endpoint_create_register_resource(endpoint_t *endpoint, const char *id, + bool auto_obs); + +coap_req_cb *endpoint_get_coap_request_callback(endpoint_t *endpoint, uint16_t object_id); + +registry_callback_t endpoint_get_object_callback(endpoint_t *endpoint, uint16_t object_id); + +#endif + #ifdef __cplusplus } #endif diff --git a/mbed-client/mbed-client/lwm2m_est_client.h b/mbed-client/mbed-client/lwm2m_est_client.h new file mode 100644 index 0000000..c64a1e7 --- /dev/null +++ b/mbed-client/mbed-client/lwm2m_est_client.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2020 ARM Limited. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef LWM2M_EST_CLIENT_H +#define LWM2M_EST_CLIENT_H + +#include "est_defs.h" + + +/*! \file lwm2m_est_client.h + * \brief Client Lite internal API for sending Certificate Enrollment request. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef MBED_CLIENT_DISABLE_EST_FEATURE + +/** + * \brief Request certificate enrollment from the EST service. + * \param cert_name, The name of certificate to enroll. Null enrolls a LwM2M certificate. + * \param csr_length, The length of the certificate signing request within csr buffer. + * \param csr, A buffer containing the certificate signing request. + * \param result_cb, The callback function that is called when EST enrollment has completed. + * \param context, The user context that is passed to the result_cb callback. + */ +est_status_e est_request_enrollment(const char *cert_name, + uint8_t *csr, + const size_t csr_length, + est_enrollment_result_cb result_cb, + void *context); + +/** + * \brief Release memory allocated for the certificate request. + * \param context Certificate chain context, received by result callback. + */ +void est_free_context(struct cert_chain_context_s *context); + +#else // MBED_CLIENT_DISABLE_EST_FEATURE +#define est_request_enrollment(...) EST_STATUS_INVALID_PARAMETERS +#define est_free_context(...) () +#endif // MBED_CLIENT_DISABLE_EST_FEATURE + +#ifdef __cplusplus +} +#endif + +#endif // LWM2M_EST_CLIENT_H diff --git a/mbed-client/mbed-client/lwm2m_registry.h b/mbed-client/mbed-client/lwm2m_registry.h index bd265ad..f792ec5 100644 --- a/mbed-client/mbed-client/lwm2m_registry.h +++ b/mbed-client/mbed-client/lwm2m_registry.h @@ -159,7 +159,7 @@ registry_status_t registry_remove_object(registry_t *registry, const registry_pa * \param registry Pointer to the registry to be used. * \param path Path to the Resource. * \param value New value for the Resource. This will be copied to the internal structure. - * \param free_on_remove Only available with string and opaque values. If true, the value will be freed after removing or modifying + * \param free_on_remove Only available with string and opaque values. If true, the value will be freed after removing or modifying * the Resource using `lwm2m_free()`. * * \return REGISTRY_STATUS_OK Data set. @@ -410,7 +410,12 @@ typedef registry_status_t (*registry_callback_t)(registry_callback_type_t, const registry_callback_token_t*, const registry_object_value_t*, const registry_notification_status_t, - registry_t *); +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY + registry_t * +#else + void * +#endif + ); /** * \brief Set callback function to specified registry object (path). @@ -455,7 +460,7 @@ bool registry_compare_path(const registry_path_t *path, const registry_path_t *p * \param path Registry path to print. * */ -#if defined(MBED_CONF_MBED_TRACE_ENABLE) && (MBED_CONF_MBED_TRACE_ENABLE == 1) +#if defined(MBED_CONF_MBED_TRACE_ENABLE) && (MBED_CONF_MBED_TRACE_ENABLE == 1) && !defined(MBED_CLOUD_CLIENT_DISABLE_REGISTRY) #define print_registry_path(prefix, path) _print_registry_path(prefix, path) // This is the real printer, that must be used with `print_registry_path()` as it lets the compiler to remove diff --git a/mbed-client/mbed-client/lwm2m_get_req_handler.h b/mbed-client/mbed-client/lwm2m_req_handler.h similarity index 65% rename from mbed-client/mbed-client/lwm2m_get_req_handler.h rename to mbed-client/mbed-client/lwm2m_req_handler.h index 9a2c90f..5a67572 100644 --- a/mbed-client/mbed-client/lwm2m_get_req_handler.h +++ b/mbed-client/mbed-client/lwm2m_req_handler.h @@ -23,8 +23,8 @@ #include -/*! \file lwm2m_get_req_handler.h - * \brief Client Lite internal API for executing direct CoAP GET requests. +/*! \file lwm2m_req_handler.h + * \brief Client Lite internal API for executing direct CoAP GET/POST/PUT requests. */ #ifdef __cplusplus @@ -35,13 +35,16 @@ extern "C" { * \brief Destroy all the allocated data. * */ -void get_handler_destroy(void); +void req_handler_destroy(void); /** - * \brief Send the Constrained Application Protocol (CoAP) GET request to the server. + * \brief Send the Constrained Application Protocol (CoAP) GET/POST/PUT request to the server. + * + * \note POST and PUT request are only supported if COAP_MSG_CODE_REQUEST_GET macro is not defined. * * \param endpoint Endpoint info. * \param type Download type. + * \param msg_code CoAP request type GET/POST/PUT. * \param uri URI path to the data. * \param offset Data offset. * \param async In async mode, the application must call this API again with the updated offset. @@ -49,16 +52,21 @@ void get_handler_destroy(void); * \param data_cb Callback triggered once there is data available. * \param error_cb Callback trigged in case of any error. * \param context Application context. + * \param payload Payload for POST/PUT request, NULL for GET. + * \param payload_len Length of payload or zero in case of GET request. * */ -void get_handler_send_get_data_request(endpoint_t *endpoint, +void req_handler_send_data_request(endpoint_t *endpoint, DownloadType type, + sn_coap_msg_code_e msg_code, const char *uri, const size_t offset, const bool async, get_data_cb data_cb, get_data_error_cb error_cb, - void *context); + void *context, + uint8_t *payload, + uint16_t payload_len); /** * \brief This function is called by the send queue to send a pending request. @@ -67,39 +75,39 @@ void get_handler_send_get_data_request(endpoint_t *endpoint, * \param endpoint Endpoint info. */ -void get_handler_send_message(endpoint_t *endpoint); +void req_handler_send_message(endpoint_t *endpoint); /** - * \brief Handle GET response. + * \brief Handle GET/POST/PUT response. * * \param endpoint Endpoint info. * \param coap_header Incoming CoAP data. * - * \return True if response matches with the GET request, otherwise False. + * \return True if response matches with the GET/POST/PUT request, otherwise False. */ -bool get_handler_handle_response(endpoint_t *endpoint, const sn_coap_hdr_s *coap_header); +bool req_handler_handle_response(endpoint_t *endpoint, const sn_coap_hdr_s *coap_header); /** - * \brief Mark all existing GET requests to be re-sent. + * \brief Mark all existing GET/POST/PUT requests to be re-sent. * */ -void get_handler_set_resend_status(void); +void req_handler_set_resend_status(void); /** * \brief Send all requests that have retry flag set to true. * * \param endpoint Endpoint info. */ -void get_handler_send_pending_request(endpoint_t *endpoint); +void req_handler_send_pending_request(endpoint_t *endpoint); /** - * \brief Remove all pending GET requests. + * \brief Remove all pending GET/POST/PUT requests. * * \param coap_header Incoming CoAP data or NULL. * \param call_error_cb If true, the error callback is called. * \param error_code Error code to be passed to the error callback. */ -void get_handler_free_get_request_list(const sn_coap_hdr_s *coap_header, bool call_error_cb, get_data_req_error_t error_code); +void req_handler_free_request_list(const sn_coap_hdr_s *coap_header, bool call_error_cb, get_data_req_error_t error_code); #ifdef __cplusplus } diff --git a/mbed-client/mbed-client/lwm2m_storage.h b/mbed-client/mbed-client/lwm2m_storage.h index 8bda910..10740ff 100644 --- a/mbed-client/mbed-client/lwm2m_storage.h +++ b/mbed-client/mbed-client/lwm2m_storage.h @@ -22,6 +22,9 @@ */ #include "include/CloudClientStorage.h" +#ifdef MBED_CLOUD_CLIENT_DISABLE_REGISTRY +#include "lwm2m_endpoint.h" +#endif #ifdef __cplusplus extern "C" { @@ -49,9 +52,10 @@ const void *storage_read_certificate_key(size_t *buffer_size, bool bootstrap); const void *storage_read_ca_certificate(size_t *buffer_size, bool bootstrap); #endif //defined(PROTOMAN_SECURITY_ENABLE_CERTIFICATE) +#ifndef MBED_CLOUD_CLIENT_DISABLE_REGISTRY bool storage_set_credentials(registry_t *registry); - bool storage_set_bootstrap_credentials(registry_t *registry); +#endif char *storage_read_internal_endpoint_name(char *buffer, int32_t *buffer_size, const bool bootstrap); bool storage_set_internal_endpoint_name(const char *iep); diff --git a/mbed-client/mbed-protocol-manager/docs/doxygen.conf b/mbed-client/mbed-protocol-manager/docs/doxygen.conf deleted file mode 100644 index eb003f8..0000000 --- a/mbed-client/mbed-protocol-manager/docs/doxygen.conf +++ /dev/null @@ -1,2429 +0,0 @@ -# Doxyfile 1.8.11 - -# This file describes the settings to be used by the documentation system -# doxygen (www.doxygen.org) for a project. -# -# All text after a double hash (##) is considered a comment and is placed in -# front of the TAG it is preceding. -# -# All text after a single hash (#) is considered a comment and will be ignored. -# The format is: -# TAG = value [value, ...] -# For lists, items can also be appended using: -# TAG += value [value, ...] -# Values that contain spaces should be placed between quotes (\" \"). - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- - -# This tag specifies the encoding used for all characters in the config file -# that follow. The default is UTF-8 which is also the encoding used for all text -# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv -# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv -# for the list of possible encodings. -# The default value is: UTF-8. - -DOXYFILE_ENCODING = UTF-8 - -# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by -# double-quotes, unless you are using Doxywizard) that should identify the -# project for which the documentation is generated. This name is used in the -# title of most generated pages and in a few other places. -# The default value is: My Project. - -PROJECT_NAME = "mbed Protocol Manager" - -# The PROJECT_NUMBER tag can be used to enter a project or revision number. This -# could be handy for archiving the generated documentation or if some version -# control system is used. - -PROJECT_NUMBER = - -# Using the PROJECT_BRIEF tag one can provide an optional one line description -# for a project that appears at the top of each page and should give viewer a -# quick idea about the purpose of the project. Keep the description short. - -PROJECT_BRIEF = - -# With the PROJECT_LOGO tag one can specify a logo or an icon that is included -# in the documentation. The maximum height of the logo should not exceed 55 -# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy -# the logo to the output directory. - -PROJECT_LOGO = - -# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path -# into which the generated documentation will be written. If a relative path is -# entered, it will be relative to the location where doxygen was started. If -# left blank the current directory will be used. - -OUTPUT_DIRECTORY = docs/ - -# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- -# directories (in 2 levels) under the output directory of each output format and -# will distribute the generated files over these directories. Enabling this -# option can be useful when feeding doxygen a huge amount of source files, where -# putting all generated files in the same directory would otherwise causes -# performance problems for the file system. -# The default value is: NO. - -CREATE_SUBDIRS = NO - -# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII -# characters to appear in the names of generated files. If set to NO, non-ASCII -# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode -# U+3044. -# The default value is: NO. - -ALLOW_UNICODE_NAMES = NO - -# The OUTPUT_LANGUAGE tag is used to specify the language in which all -# documentation generated by doxygen is written. Doxygen will use this -# information to generate all constant output in the proper language. -# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, -# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), -# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, -# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), -# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, -# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, -# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, -# Ukrainian and Vietnamese. -# The default value is: English. - -OUTPUT_LANGUAGE = English - -# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member -# descriptions after the members that are listed in the file and class -# documentation (similar to Javadoc). Set to NO to disable this. -# The default value is: YES. - -BRIEF_MEMBER_DESC = YES - -# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief -# description of a member or function before the detailed description -# -# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the -# brief descriptions will be completely suppressed. -# The default value is: YES. - -REPEAT_BRIEF = YES - -# This tag implements a quasi-intelligent brief description abbreviator that is -# used to form the text in various listings. Each string in this list, if found -# as the leading text of the brief description, will be stripped from the text -# and the result, after processing the whole list, is used as the annotated -# text. Otherwise, the brief description is used as-is. If left blank, the -# following values are used ($name is automatically replaced with the name of -# the entity):The $name class, The $name widget, The $name file, is, provides, -# specifies, contains, represents, a, an and the. - -ABBREVIATE_BRIEF = - -# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then -# doxygen will generate a detailed section even if there is only a brief -# description. -# The default value is: NO. - -ALWAYS_DETAILED_SEC = NO - -# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all -# inherited members of a class in the documentation of that class as if those -# members were ordinary class members. Constructors, destructors and assignment -# operators of the base classes will not be shown. -# The default value is: NO. - -INLINE_INHERITED_MEMB = NO - -# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path -# before files name in the file list and in the header files. If set to NO the -# shortest path that makes the file name unique will be used -# The default value is: YES. - -FULL_PATH_NAMES = YES - -# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. -# Stripping is only done if one of the specified strings matches the left-hand -# part of the path. The tag can be used to show relative paths in the file list. -# If left blank the directory from which doxygen is run is used as the path to -# strip. -# -# Note that you can specify absolute paths here, but also relative paths, which -# will be relative from the directory where doxygen is started. -# This tag requires that the tag FULL_PATH_NAMES is set to YES. - -STRIP_FROM_PATH = - -# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the -# path mentioned in the documentation of a class, which tells the reader which -# header file to include in order to use a class. If left blank only the name of -# the header file containing the class definition is used. Otherwise one should -# specify the list of include paths that are normally passed to the compiler -# using the -I flag. - -STRIP_FROM_INC_PATH = - -# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but -# less readable) file names. This can be useful is your file systems doesn't -# support long names like on DOS, Mac, or CD-ROM. -# The default value is: NO. - -SHORT_NAMES = NO - -# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the -# first line (until the first dot) of a Javadoc-style comment as the brief -# description. If set to NO, the Javadoc-style will behave just like regular Qt- -# style comments (thus requiring an explicit @brief command for a brief -# description.) -# The default value is: NO. - -JAVADOC_AUTOBRIEF = NO - -# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first -# line (until the first dot) of a Qt-style comment as the brief description. If -# set to NO, the Qt-style will behave just like regular Qt-style comments (thus -# requiring an explicit \brief command for a brief description.) -# The default value is: NO. - -QT_AUTOBRIEF = NO - -# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a -# multi-line C++ special comment block (i.e. a block of //! or /// comments) as -# a brief description. This used to be the default behavior. The new default is -# to treat a multi-line C++ comment block as a detailed description. Set this -# tag to YES if you prefer the old behavior instead. -# -# Note that setting this tag to YES also means that rational rose comments are -# not recognized any more. -# The default value is: NO. - -MULTILINE_CPP_IS_BRIEF = NO - -# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the -# documentation from any documented member that it re-implements. -# The default value is: YES. - -INHERIT_DOCS = YES - -# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new -# page for each member. If set to NO, the documentation of a member will be part -# of the file/class/namespace that contains it. -# The default value is: NO. - -SEPARATE_MEMBER_PAGES = NO - -# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen -# uses this value to replace tabs by spaces in code fragments. -# Minimum value: 1, maximum value: 16, default value: 4. - -TAB_SIZE = 4 - -# This tag can be used to specify a number of aliases that act as commands in -# the documentation. An alias has the form: -# name=value -# For example adding -# "sideeffect=@par Side Effects:\n" -# will allow you to put the command \sideeffect (or @sideeffect) in the -# documentation, which will result in a user-defined paragraph with heading -# "Side Effects:". You can put \n's in the value part of an alias to insert -# newlines. - -ALIASES = - -# This tag can be used to specify a number of word-keyword mappings (TCL only). -# A mapping has the form "name=value". For example adding "class=itcl::class" -# will allow you to use the command class in the itcl::class meaning. - -TCL_SUBST = - -# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources -# only. Doxygen will then generate output that is more tailored for C. For -# instance, some of the names that are used will be different. The list of all -# members will be omitted, etc. -# The default value is: NO. - -OPTIMIZE_OUTPUT_FOR_C = NO - -# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or -# Python sources only. Doxygen will then generate output that is more tailored -# for that language. For instance, namespaces will be presented as packages, -# qualified scopes will look different, etc. -# The default value is: NO. - -OPTIMIZE_OUTPUT_JAVA = NO - -# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran -# sources. Doxygen will then generate output that is tailored for Fortran. -# The default value is: NO. - -OPTIMIZE_FOR_FORTRAN = NO - -# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL -# sources. Doxygen will then generate output that is tailored for VHDL. -# The default value is: NO. - -OPTIMIZE_OUTPUT_VHDL = NO - -# Doxygen selects the parser to use depending on the extension of the files it -# parses. With this tag you can assign which parser to use for a given -# extension. Doxygen has a built-in mapping, but you can override or extend it -# using this tag. The format is ext=language, where ext is a file extension, and -# language is one of the parsers supported by doxygen: IDL, Java, Javascript, -# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran: -# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran: -# Fortran. In the later case the parser tries to guess whether the code is fixed -# or free formatted code, this is the default for Fortran type files), VHDL. For -# instance to make doxygen treat .inc files as Fortran files (default is PHP), -# and .f files as C (default is Fortran), use: inc=Fortran f=C. -# -# Note: For files without extension you can use no_extension as a placeholder. -# -# Note that for custom extensions you also need to set FILE_PATTERNS otherwise -# the files are not read by doxygen. - -EXTENSION_MAPPING = - -# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments -# according to the Markdown format, which allows for more readable -# documentation. See http://daringfireball.net/projects/markdown/ for details. -# The output of markdown processing is further processed by doxygen, so you can -# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in -# case of backward compatibilities issues. -# The default value is: YES. - -MARKDOWN_SUPPORT = YES - -# When enabled doxygen tries to link words that correspond to documented -# classes, or namespaces to their corresponding documentation. Such a link can -# be prevented in individual cases by putting a % sign in front of the word or -# globally by setting AUTOLINK_SUPPORT to NO. -# The default value is: YES. - -AUTOLINK_SUPPORT = YES - -# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want -# to include (a tag file for) the STL sources as input, then you should set this -# tag to YES in order to let doxygen match functions declarations and -# definitions whose arguments contain STL classes (e.g. func(std::string); -# versus func(std::string) {}). This also make the inheritance and collaboration -# diagrams that involve STL classes more complete and accurate. -# The default value is: NO. - -BUILTIN_STL_SUPPORT = NO - -# If you use Microsoft's C++/CLI language, you should set this option to YES to -# enable parsing support. -# The default value is: NO. - -CPP_CLI_SUPPORT = NO - -# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: -# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen -# will parse them like normal C++ but will assume all classes use public instead -# of private inheritance when no explicit protection keyword is present. -# The default value is: NO. - -SIP_SUPPORT = NO - -# For Microsoft's IDL there are propget and propput attributes to indicate -# getter and setter methods for a property. Setting this option to YES will make -# doxygen to replace the get and set methods by a property in the documentation. -# This will only work if the methods are indeed getting or setting a simple -# type. If this is not the case, or you want to show the methods anyway, you -# should set this option to NO. -# The default value is: YES. - -IDL_PROPERTY_SUPPORT = YES - -# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC -# tag is set to YES then doxygen will reuse the documentation of the first -# member in the group (if any) for the other members of the group. By default -# all members of a group must be documented explicitly. -# The default value is: NO. - -DISTRIBUTE_GROUP_DOC = NO - -# If one adds a struct or class to a group and this option is enabled, then also -# any nested class or struct is added to the same group. By default this option -# is disabled and one has to add nested compounds explicitly via \ingroup. -# The default value is: NO. - -GROUP_NESTED_COMPOUNDS = NO - -# Set the SUBGROUPING tag to YES to allow class member groups of the same type -# (for instance a group of public functions) to be put as a subgroup of that -# type (e.g. under the Public Functions section). Set it to NO to prevent -# subgrouping. Alternatively, this can be done per class using the -# \nosubgrouping command. -# The default value is: YES. - -SUBGROUPING = YES - -# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions -# are shown inside the group in which they are included (e.g. using \ingroup) -# instead of on a separate page (for HTML and Man pages) or section (for LaTeX -# and RTF). -# -# Note that this feature does not work in combination with -# SEPARATE_MEMBER_PAGES. -# The default value is: NO. - -INLINE_GROUPED_CLASSES = NO - -# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions -# with only public data fields or simple typedef fields will be shown inline in -# the documentation of the scope in which they are defined (i.e. file, -# namespace, or group documentation), provided this scope is documented. If set -# to NO, structs, classes, and unions are shown on a separate page (for HTML and -# Man pages) or section (for LaTeX and RTF). -# The default value is: NO. - -INLINE_SIMPLE_STRUCTS = NO - -# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or -# enum is documented as struct, union, or enum with the name of the typedef. So -# typedef struct TypeS {} TypeT, will appear in the documentation as a struct -# with name TypeT. When disabled the typedef will appear as a member of a file, -# namespace, or class. And the struct will be named TypeS. This can typically be -# useful for C code in case the coding convention dictates that all compound -# types are typedef'ed and only the typedef is referenced, never the tag name. -# The default value is: NO. - -TYPEDEF_HIDES_STRUCT = NO - -# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This -# cache is used to resolve symbols given their name and scope. Since this can be -# an expensive process and often the same symbol appears multiple times in the -# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small -# doxygen will become slower. If the cache is too large, memory is wasted. The -# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range -# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 -# symbols. At the end of a run doxygen will report the cache usage and suggest -# the optimal cache size from a speed point of view. -# Minimum value: 0, maximum value: 9, default value: 0. - -LOOKUP_CACHE_SIZE = 0 - -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- - -# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in -# documentation are documented, even if no documentation was available. Private -# class members and static file members will be hidden unless the -# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. -# Note: This will also disable the warnings about undocumented members that are -# normally produced when WARNINGS is set to YES. -# The default value is: NO. - -EXTRACT_ALL = NO - -# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will -# be included in the documentation. -# The default value is: NO. - -EXTRACT_PRIVATE = NO - -# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal -# scope will be included in the documentation. -# The default value is: NO. - -EXTRACT_PACKAGE = NO - -# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be -# included in the documentation. -# The default value is: NO. - -EXTRACT_STATIC = NO - -# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined -# locally in source files will be included in the documentation. If set to NO, -# only classes defined in header files are included. Does not have any effect -# for Java sources. -# The default value is: YES. - -EXTRACT_LOCAL_CLASSES = YES - -# This flag is only useful for Objective-C code. If set to YES, local methods, -# which are defined in the implementation section but not in the interface are -# included in the documentation. If set to NO, only methods in the interface are -# included. -# The default value is: NO. - -EXTRACT_LOCAL_METHODS = NO - -# If this flag is set to YES, the members of anonymous namespaces will be -# extracted and appear in the documentation as a namespace called -# 'anonymous_namespace{file}', where file will be replaced with the base name of -# the file that contains the anonymous namespace. By default anonymous namespace -# are hidden. -# The default value is: NO. - -EXTRACT_ANON_NSPACES = NO - -# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all -# undocumented members inside documented classes or files. If set to NO these -# members will be included in the various overviews, but no documentation -# section is generated. This option has no effect if EXTRACT_ALL is enabled. -# The default value is: NO. - -HIDE_UNDOC_MEMBERS = NO - -# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all -# undocumented classes that are normally visible in the class hierarchy. If set -# to NO, these classes will be included in the various overviews. This option -# has no effect if EXTRACT_ALL is enabled. -# The default value is: NO. - -HIDE_UNDOC_CLASSES = NO - -# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend -# (class|struct|union) declarations. If set to NO, these declarations will be -# included in the documentation. -# The default value is: NO. - -HIDE_FRIEND_COMPOUNDS = NO - -# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any -# documentation blocks found inside the body of a function. If set to NO, these -# blocks will be appended to the function's detailed documentation block. -# The default value is: NO. - -HIDE_IN_BODY_DOCS = NO - -# The INTERNAL_DOCS tag determines if documentation that is typed after a -# \internal command is included. If the tag is set to NO then the documentation -# will be excluded. Set it to YES to include the internal documentation. -# The default value is: NO. - -INTERNAL_DOCS = NO - -# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file -# names in lower-case letters. If set to YES, upper-case letters are also -# allowed. This is useful if you have classes or files whose names only differ -# in case and if your file system supports case sensitive file names. Windows -# and Mac users are advised to set this option to NO. -# The default value is: system dependent. - -CASE_SENSE_NAMES = YES - -# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with -# their full class and namespace scopes in the documentation. If set to YES, the -# scope will be hidden. -# The default value is: NO. - -HIDE_SCOPE_NAMES = NO - -# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will -# append additional text to a page's title, such as Class Reference. If set to -# YES the compound reference will be hidden. -# The default value is: NO. - -HIDE_COMPOUND_REFERENCE= NO - -# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of -# the files that are included by a file in the documentation of that file. -# The default value is: YES. - -SHOW_INCLUDE_FILES = YES - -# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each -# grouped member an include statement to the documentation, telling the reader -# which file to include in order to use the member. -# The default value is: NO. - -SHOW_GROUPED_MEMB_INC = NO - -# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include -# files with double quotes in the documentation rather than with sharp brackets. -# The default value is: NO. - -FORCE_LOCAL_INCLUDES = NO - -# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the -# documentation for inline members. -# The default value is: YES. - -INLINE_INFO = YES - -# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the -# (detailed) documentation of file and class members alphabetically by member -# name. If set to NO, the members will appear in declaration order. -# The default value is: YES. - -SORT_MEMBER_DOCS = YES - -# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief -# descriptions of file, namespace and class members alphabetically by member -# name. If set to NO, the members will appear in declaration order. Note that -# this will also influence the order of the classes in the class list. -# The default value is: NO. - -SORT_BRIEF_DOCS = NO - -# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the -# (brief and detailed) documentation of class members so that constructors and -# destructors are listed first. If set to NO the constructors will appear in the -# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. -# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief -# member documentation. -# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting -# detailed member documentation. -# The default value is: NO. - -SORT_MEMBERS_CTORS_1ST = NO - -# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy -# of group names into alphabetical order. If set to NO the group names will -# appear in their defined order. -# The default value is: NO. - -SORT_GROUP_NAMES = NO - -# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by -# fully-qualified names, including namespaces. If set to NO, the class list will -# be sorted only by class name, not including the namespace part. -# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. -# Note: This option applies only to the class list, not to the alphabetical -# list. -# The default value is: NO. - -SORT_BY_SCOPE_NAME = NO - -# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper -# type resolution of all parameters of a function it will reject a match between -# the prototype and the implementation of a member function even if there is -# only one candidate or it is obvious which candidate to choose by doing a -# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still -# accept a match between prototype and implementation in such cases. -# The default value is: NO. - -STRICT_PROTO_MATCHING = NO - -# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo -# list. This list is created by putting \todo commands in the documentation. -# The default value is: YES. - -GENERATE_TODOLIST = YES - -# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test -# list. This list is created by putting \test commands in the documentation. -# The default value is: YES. - -GENERATE_TESTLIST = YES - -# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug -# list. This list is created by putting \bug commands in the documentation. -# The default value is: YES. - -GENERATE_BUGLIST = YES - -# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) -# the deprecated list. This list is created by putting \deprecated commands in -# the documentation. -# The default value is: YES. - -GENERATE_DEPRECATEDLIST= YES - -# The ENABLED_SECTIONS tag can be used to enable conditional documentation -# sections, marked by \if ... \endif and \cond -# ... \endcond blocks. - -ENABLED_SECTIONS = - -# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the -# initial value of a variable or macro / define can have for it to appear in the -# documentation. If the initializer consists of more lines than specified here -# it will be hidden. Use a value of 0 to hide initializers completely. The -# appearance of the value of individual variables and macros / defines can be -# controlled using \showinitializer or \hideinitializer command in the -# documentation regardless of this setting. -# Minimum value: 0, maximum value: 10000, default value: 30. - -MAX_INITIALIZER_LINES = 30 - -# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at -# the bottom of the documentation of classes and structs. If set to YES, the -# list will mention the files that were used to generate the documentation. -# The default value is: YES. - -SHOW_USED_FILES = YES - -# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This -# will remove the Files entry from the Quick Index and from the Folder Tree View -# (if specified). -# The default value is: YES. - -SHOW_FILES = YES - -# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces -# page. This will remove the Namespaces entry from the Quick Index and from the -# Folder Tree View (if specified). -# The default value is: YES. - -SHOW_NAMESPACES = YES - -# The FILE_VERSION_FILTER tag can be used to specify a program or script that -# doxygen should invoke to get the current version for each file (typically from -# the version control system). Doxygen will invoke the program by executing (via -# popen()) the command command input-file, where command is the value of the -# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided -# by doxygen. Whatever the program writes to standard output is used as the file -# version. For an example see the documentation. - -FILE_VERSION_FILTER = - -# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed -# by doxygen. The layout file controls the global structure of the generated -# output files in an output format independent way. To create the layout file -# that represents doxygen's defaults, run doxygen with the -l option. You can -# optionally specify a file name after the option, if omitted DoxygenLayout.xml -# will be used as the name of the layout file. -# -# Note that if you run doxygen from a directory containing a file called -# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE -# tag is left empty. - -LAYOUT_FILE = - -# The CITE_BIB_FILES tag can be used to specify one or more bib files containing -# the reference definitions. This must be a list of .bib files. The .bib -# extension is automatically appended if omitted. This requires the bibtex tool -# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info. -# For LaTeX the style of the bibliography can be controlled using -# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the -# search path. See also \cite for info how to create references. - -CITE_BIB_FILES = - -#--------------------------------------------------------------------------- -# Configuration options related to warning and progress messages -#--------------------------------------------------------------------------- - -# The QUIET tag can be used to turn on/off the messages that are generated to -# standard output by doxygen. If QUIET is set to YES this implies that the -# messages are off. -# The default value is: NO. - -QUIET = NO - -# The WARNINGS tag can be used to turn on/off the warning messages that are -# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES -# this implies that the warnings are on. -# -# Tip: Turn warnings on while writing the documentation. -# The default value is: YES. - -WARNINGS = YES - -# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate -# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag -# will automatically be disabled. -# The default value is: YES. - -WARN_IF_UNDOCUMENTED = YES - -# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for -# potential errors in the documentation, such as not documenting some parameters -# in a documented function, or documenting parameters that don't exist or using -# markup commands wrongly. -# The default value is: YES. - -WARN_IF_DOC_ERROR = YES - -# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that -# are documented, but have no documentation for their parameters or return -# value. If set to NO, doxygen will only warn about wrong or incomplete -# parameter documentation, but not about the absence of documentation. -# The default value is: NO. - -WARN_NO_PARAMDOC = NO - -# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when -# a warning is encountered. -# The default value is: NO. - -WARN_AS_ERROR = NO - -# The WARN_FORMAT tag determines the format of the warning messages that doxygen -# can produce. The string should contain the $file, $line, and $text tags, which -# will be replaced by the file and line number from which the warning originated -# and the warning text. Optionally the format may contain $version, which will -# be replaced by the version of the file (if it could be obtained via -# FILE_VERSION_FILTER) -# The default value is: $file:$line: $text. - -WARN_FORMAT = "$file:$line: $text" - -# The WARN_LOGFILE tag can be used to specify a file to which warning and error -# messages should be written. If left blank the output is written to standard -# error (stderr). - -WARN_LOGFILE = - -#--------------------------------------------------------------------------- -# Configuration options related to the input files -#--------------------------------------------------------------------------- - -# The INPUT tag is used to specify the files and/or directories that contain -# documented source files. You may enter file names like myfile.cpp or -# directories like /usr/src/myproject. Separate the files or directories with -# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING -# Note: If this tag is empty the current directory is searched. - -INPUT = README.md \ - source \ - mbed-protocol-manager - -# This tag can be used to specify the character encoding of the source files -# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses -# libiconv (or the iconv built into libc) for the transcoding. See the libiconv -# documentation (see: http://www.gnu.org/software/libiconv) for the list of -# possible encodings. -# The default value is: UTF-8. - -INPUT_ENCODING = UTF-8 - -# If the value of the INPUT tag contains directories, you can use the -# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and -# *.h) to filter out the source-files in the directories. -# -# Note that for custom extensions or not directly supported extensions you also -# need to set EXTENSION_MAPPING for the extension otherwise the files are not -# read by doxygen. -# -# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp, -# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, -# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, -# *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f, *.for, *.tcl, -# *.vhd, *.vhdl, *.ucf, *.qsf, *.as and *.js. - -FILE_PATTERNS = - -# The RECURSIVE tag can be used to specify whether or not subdirectories should -# be searched for input files as well. -# The default value is: NO. - -RECURSIVE = NO - -# The EXCLUDE tag can be used to specify files and/or directories that should be -# excluded from the INPUT source files. This way you can easily exclude a -# subdirectory from a directory tree whose root is specified with the INPUT tag. -# -# Note that relative paths are relative to the directory from which doxygen is -# run. - -EXCLUDE = - -# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or -# directories that are symbolic links (a Unix file system feature) are excluded -# from the input. -# The default value is: NO. - -EXCLUDE_SYMLINKS = NO - -# If the value of the INPUT tag contains directories, you can use the -# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude -# certain files from those directories. -# -# Note that the wildcards are matched against the file with absolute path, so to -# exclude all test directories for example use the pattern */test/* - -EXCLUDE_PATTERNS = - -# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names -# (namespaces, classes, functions, etc.) that should be excluded from the -# output. The symbol name can be a fully qualified name, a word, or if the -# wildcard * is used, a substring. Examples: ANamespace, AClass, -# AClass::ANamespace, ANamespace::*Test -# -# Note that the wildcards are matched against the file with absolute path, so to -# exclude all test directories use the pattern */test/* - -EXCLUDE_SYMBOLS = - -# The EXAMPLE_PATH tag can be used to specify one or more files or directories -# that contain example code fragments that are included (see the \include -# command). - -EXAMPLE_PATH = - -# If the value of the EXAMPLE_PATH tag contains directories, you can use the -# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and -# *.h) to filter out the source-files in the directories. If left blank all -# files are included. - -EXAMPLE_PATTERNS = - -# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be -# searched for input files to be used with the \include or \dontinclude commands -# irrespective of the value of the RECURSIVE tag. -# The default value is: NO. - -EXAMPLE_RECURSIVE = NO - -# The IMAGE_PATH tag can be used to specify one or more files or directories -# that contain images that are to be included in the documentation (see the -# \image command). - -IMAGE_PATH = - -# The INPUT_FILTER tag can be used to specify a program that doxygen should -# invoke to filter for each input file. Doxygen will invoke the filter program -# by executing (via popen()) the command: -# -# -# -# where is the value of the INPUT_FILTER tag, and is the -# name of an input file. Doxygen will then use the output that the filter -# program writes to standard output. If FILTER_PATTERNS is specified, this tag -# will be ignored. -# -# Note that the filter must not add or remove lines; it is applied before the -# code is scanned, but not when the output code is generated. If lines are added -# or removed, the anchors will not be placed correctly. -# -# Note that for custom extensions or not directly supported extensions you also -# need to set EXTENSION_MAPPING for the extension otherwise the files are not -# properly processed by doxygen. - -INPUT_FILTER = - -# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern -# basis. Doxygen will compare the file name with each pattern and apply the -# filter if there is a match. The filters are a list of the form: pattern=filter -# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how -# filters are used. If the FILTER_PATTERNS tag is empty or if none of the -# patterns match the file name, INPUT_FILTER is applied. -# -# Note that for custom extensions or not directly supported extensions you also -# need to set EXTENSION_MAPPING for the extension otherwise the files are not -# properly processed by doxygen. - -FILTER_PATTERNS = - -# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using -# INPUT_FILTER) will also be used to filter the input files that are used for -# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). -# The default value is: NO. - -FILTER_SOURCE_FILES = NO - -# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file -# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and -# it is also possible to disable source filtering for a specific pattern using -# *.ext= (so without naming a filter). -# This tag requires that the tag FILTER_SOURCE_FILES is set to YES. - -FILTER_SOURCE_PATTERNS = - -# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that -# is part of the input, its contents will be placed on the main page -# (index.html). This can be useful if you have a project on for instance GitHub -# and want to reuse the introduction page also for the doxygen output. - -USE_MDFILE_AS_MAINPAGE = - -#--------------------------------------------------------------------------- -# Configuration options related to source browsing -#--------------------------------------------------------------------------- - -# If the SOURCE_BROWSER tag is set to YES then a list of source files will be -# generated. Documented entities will be cross-referenced with these sources. -# -# Note: To get rid of all source code in the generated output, make sure that -# also VERBATIM_HEADERS is set to NO. -# The default value is: NO. - -SOURCE_BROWSER = NO - -# Setting the INLINE_SOURCES tag to YES will include the body of functions, -# classes and enums directly into the documentation. -# The default value is: NO. - -INLINE_SOURCES = NO - -# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any -# special comment blocks from generated source code fragments. Normal C, C++ and -# Fortran comments will always remain visible. -# The default value is: YES. - -STRIP_CODE_COMMENTS = YES - -# If the REFERENCED_BY_RELATION tag is set to YES then for each documented -# function all documented functions referencing it will be listed. -# The default value is: NO. - -REFERENCED_BY_RELATION = NO - -# If the REFERENCES_RELATION tag is set to YES then for each documented function -# all documented entities called/used by that function will be listed. -# The default value is: NO. - -REFERENCES_RELATION = NO - -# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set -# to YES then the hyperlinks from functions in REFERENCES_RELATION and -# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will -# link to the documentation. -# The default value is: YES. - -REFERENCES_LINK_SOURCE = YES - -# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the -# source code will show a tooltip with additional information such as prototype, -# brief description and links to the definition and documentation. Since this -# will make the HTML file larger and loading of large files a bit slower, you -# can opt to disable this feature. -# The default value is: YES. -# This tag requires that the tag SOURCE_BROWSER is set to YES. - -SOURCE_TOOLTIPS = YES - -# If the USE_HTAGS tag is set to YES then the references to source code will -# point to the HTML generated by the htags(1) tool instead of doxygen built-in -# source browser. The htags tool is part of GNU's global source tagging system -# (see http://www.gnu.org/software/global/global.html). You will need version -# 4.8.6 or higher. -# -# To use it do the following: -# - Install the latest version of global -# - Enable SOURCE_BROWSER and USE_HTAGS in the config file -# - Make sure the INPUT points to the root of the source tree -# - Run doxygen as normal -# -# Doxygen will invoke htags (and that will in turn invoke gtags), so these -# tools must be available from the command line (i.e. in the search path). -# -# The result: instead of the source browser generated by doxygen, the links to -# source code will now point to the output of htags. -# The default value is: NO. -# This tag requires that the tag SOURCE_BROWSER is set to YES. - -USE_HTAGS = NO - -# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a -# verbatim copy of the header file for each class for which an include is -# specified. Set to NO to disable this. -# See also: Section \class. -# The default value is: YES. - -VERBATIM_HEADERS = YES - -# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the -# clang parser (see: http://clang.llvm.org/) for more accurate parsing at the -# cost of reduced performance. This can be particularly helpful with template -# rich C++ code for which doxygen's built-in parser lacks the necessary type -# information. -# Note: The availability of this option depends on whether or not doxygen was -# generated with the -Duse-libclang=ON option for CMake. -# The default value is: NO. - -CLANG_ASSISTED_PARSING = NO - -# If clang assisted parsing is enabled you can provide the compiler with command -# line options that you would normally use when invoking the compiler. Note that -# the include paths will already be set by doxygen for the files and directories -# specified with INPUT and INCLUDE_PATH. -# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES. - -CLANG_OPTIONS = - -#--------------------------------------------------------------------------- -# Configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- - -# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all -# compounds will be generated. Enable this if the project contains a lot of -# classes, structs, unions or interfaces. -# The default value is: YES. - -ALPHABETICAL_INDEX = YES - -# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in -# which the alphabetical index list will be split. -# Minimum value: 1, maximum value: 20, default value: 5. -# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. - -COLS_IN_ALPHA_INDEX = 5 - -# In case all classes in a project start with a common prefix, all classes will -# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag -# can be used to specify a prefix (or a list of prefixes) that should be ignored -# while generating the index headers. -# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. - -IGNORE_PREFIX = - -#--------------------------------------------------------------------------- -# Configuration options related to the HTML output -#--------------------------------------------------------------------------- - -# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output -# The default value is: YES. - -GENERATE_HTML = YES - -# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a -# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of -# it. -# The default directory is: html. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_OUTPUT = html - -# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each -# generated HTML page (for example: .htm, .php, .asp). -# The default value is: .html. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_FILE_EXTENSION = .html - -# The HTML_HEADER tag can be used to specify a user-defined HTML header file for -# each generated HTML page. If the tag is left blank doxygen will generate a -# standard header. -# -# To get valid HTML the header file that includes any scripts and style sheets -# that doxygen needs, which is dependent on the configuration options used (e.g. -# the setting GENERATE_TREEVIEW). It is highly recommended to start with a -# default header using -# doxygen -w html new_header.html new_footer.html new_stylesheet.css -# YourConfigFile -# and then modify the file new_header.html. See also section "Doxygen usage" -# for information on how to generate the default header that doxygen normally -# uses. -# Note: The header is subject to change so you typically have to regenerate the -# default header when upgrading to a newer version of doxygen. For a description -# of the possible markers and block names see the documentation. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_HEADER = - -# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each -# generated HTML page. If the tag is left blank doxygen will generate a standard -# footer. See HTML_HEADER for more information on how to generate a default -# footer and what special commands can be used inside the footer. See also -# section "Doxygen usage" for information on how to generate the default footer -# that doxygen normally uses. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_FOOTER = - -# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style -# sheet that is used by each HTML page. It can be used to fine-tune the look of -# the HTML output. If left blank doxygen will generate a default style sheet. -# See also section "Doxygen usage" for information on how to generate the style -# sheet that doxygen normally uses. -# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as -# it is more robust and this tag (HTML_STYLESHEET) will in the future become -# obsolete. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_STYLESHEET = - -# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined -# cascading style sheets that are included after the standard style sheets -# created by doxygen. Using this option one can overrule certain style aspects. -# This is preferred over using HTML_STYLESHEET since it does not replace the -# standard style sheet and is therefore more robust against future updates. -# Doxygen will copy the style sheet files to the output directory. -# Note: The order of the extra style sheet files is of importance (e.g. the last -# style sheet in the list overrules the setting of the previous ones in the -# list). For an example see the documentation. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_EXTRA_STYLESHEET = - -# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or -# other source files which should be copied to the HTML output directory. Note -# that these files will be copied to the base HTML output directory. Use the -# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these -# files. In the HTML_STYLESHEET file, use the file name only. Also note that the -# files will be copied as-is; there are no commands or markers available. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_EXTRA_FILES = - -# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen -# will adjust the colors in the style sheet and background images according to -# this color. Hue is specified as an angle on a colorwheel, see -# http://en.wikipedia.org/wiki/Hue for more information. For instance the value -# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 -# purple, and 360 is red again. -# Minimum value: 0, maximum value: 359, default value: 220. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_COLORSTYLE_HUE = 220 - -# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors -# in the HTML output. For a value of 0 the output will use grayscales only. A -# value of 255 will produce the most vivid colors. -# Minimum value: 0, maximum value: 255, default value: 100. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_COLORSTYLE_SAT = 100 - -# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the -# luminance component of the colors in the HTML output. Values below 100 -# gradually make the output lighter, whereas values above 100 make the output -# darker. The value divided by 100 is the actual gamma applied, so 80 represents -# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not -# change the gamma. -# Minimum value: 40, maximum value: 240, default value: 80. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_COLORSTYLE_GAMMA = 80 - -# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML -# page will contain the date and time when the page was generated. Setting this -# to YES can help to show when doxygen was last run and thus if the -# documentation is up to date. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_TIMESTAMP = NO - -# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML -# documentation will contain sections that can be hidden and shown after the -# page has loaded. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_DYNAMIC_SECTIONS = NO - -# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries -# shown in the various tree structured indices initially; the user can expand -# and collapse entries dynamically later on. Doxygen will expand the tree to -# such a level that at most the specified number of entries are visible (unless -# a fully collapsed tree already exceeds this amount). So setting the number of -# entries 1 will produce a full collapsed tree by default. 0 is a special value -# representing an infinite number of entries and will result in a full expanded -# tree by default. -# Minimum value: 0, maximum value: 9999, default value: 100. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_INDEX_NUM_ENTRIES = 100 - -# If the GENERATE_DOCSET tag is set to YES, additional index files will be -# generated that can be used as input for Apple's Xcode 3 integrated development -# environment (see: http://developer.apple.com/tools/xcode/), introduced with -# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a -# Makefile in the HTML output directory. Running make will produce the docset in -# that directory and running make install will install the docset in -# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at -# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html -# for more information. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_DOCSET = NO - -# This tag determines the name of the docset feed. A documentation feed provides -# an umbrella under which multiple documentation sets from a single provider -# (such as a company or product suite) can be grouped. -# The default value is: Doxygen generated docs. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_FEEDNAME = "Doxygen generated docs" - -# This tag specifies a string that should uniquely identify the documentation -# set bundle. This should be a reverse domain-name style string, e.g. -# com.mycompany.MyDocSet. Doxygen will append .docset to the name. -# The default value is: org.doxygen.Project. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_BUNDLE_ID = org.doxygen.Project - -# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify -# the documentation publisher. This should be a reverse domain-name style -# string, e.g. com.mycompany.MyDocSet.documentation. -# The default value is: org.doxygen.Publisher. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_PUBLISHER_ID = org.doxygen.Publisher - -# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. -# The default value is: Publisher. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_PUBLISHER_NAME = Publisher - -# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three -# additional HTML index files: index.hhp, index.hhc, and index.hhk. The -# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop -# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on -# Windows. -# -# The HTML Help Workshop contains a compiler that can convert all HTML output -# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML -# files are now used as the Windows 98 help format, and will replace the old -# Windows help format (.hlp) on all Windows platforms in the future. Compressed -# HTML files also contain an index, a table of contents, and you can search for -# words in the documentation. The HTML workshop also contains a viewer for -# compressed HTML files. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_HTMLHELP = NO - -# The CHM_FILE tag can be used to specify the file name of the resulting .chm -# file. You can add a path in front of the file if the result should not be -# written to the html output directory. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -CHM_FILE = - -# The HHC_LOCATION tag can be used to specify the location (absolute path -# including file name) of the HTML help compiler (hhc.exe). If non-empty, -# doxygen will try to run the HTML help compiler on the generated index.hhp. -# The file has to be specified with full path. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -HHC_LOCATION = - -# The GENERATE_CHI flag controls if a separate .chi index file is generated -# (YES) or that it should be included in the master .chm file (NO). -# The default value is: NO. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -GENERATE_CHI = NO - -# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) -# and project file content. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -CHM_INDEX_ENCODING = - -# The BINARY_TOC flag controls whether a binary table of contents is generated -# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it -# enables the Previous and Next buttons. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -BINARY_TOC = NO - -# The TOC_EXPAND flag can be set to YES to add extra items for group members to -# the table of contents of the HTML help documentation and to the tree view. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -TOC_EXPAND = NO - -# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and -# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that -# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help -# (.qch) of the generated HTML documentation. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_QHP = NO - -# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify -# the file name of the resulting .qch file. The path specified is relative to -# the HTML output folder. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QCH_FILE = - -# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help -# Project output. For more information please see Qt Help Project / Namespace -# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace). -# The default value is: org.doxygen.Project. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_NAMESPACE = org.doxygen.Project - -# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt -# Help Project output. For more information please see Qt Help Project / Virtual -# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual- -# folders). -# The default value is: doc. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_VIRTUAL_FOLDER = doc - -# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom -# filter to add. For more information please see Qt Help Project / Custom -# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- -# filters). -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_CUST_FILTER_NAME = - -# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the -# custom filter to add. For more information please see Qt Help Project / Custom -# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- -# filters). -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_CUST_FILTER_ATTRS = - -# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this -# project's filter section matches. Qt Help Project / Filter Attributes (see: -# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes). -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_SECT_FILTER_ATTRS = - -# The QHG_LOCATION tag can be used to specify the location of Qt's -# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the -# generated .qhp file. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHG_LOCATION = - -# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be -# generated, together with the HTML files, they form an Eclipse help plugin. To -# install this plugin and make it available under the help contents menu in -# Eclipse, the contents of the directory containing the HTML and XML files needs -# to be copied into the plugins directory of eclipse. The name of the directory -# within the plugins directory should be the same as the ECLIPSE_DOC_ID value. -# After copying Eclipse needs to be restarted before the help appears. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_ECLIPSEHELP = NO - -# A unique identifier for the Eclipse help plugin. When installing the plugin -# the directory name containing the HTML and XML files should also have this -# name. Each documentation set should have its own identifier. -# The default value is: org.doxygen.Project. -# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. - -ECLIPSE_DOC_ID = org.doxygen.Project - -# If you want full control over the layout of the generated HTML pages it might -# be necessary to disable the index and replace it with your own. The -# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top -# of each HTML page. A value of NO enables the index and the value YES disables -# it. Since the tabs in the index contain the same information as the navigation -# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -DISABLE_INDEX = NO - -# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index -# structure should be generated to display hierarchical information. If the tag -# value is set to YES, a side panel will be generated containing a tree-like -# index structure (just like the one that is generated for HTML Help). For this -# to work a browser that supports JavaScript, DHTML, CSS and frames is required -# (i.e. any modern browser). Windows users are probably better off using the -# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can -# further fine-tune the look of the index. As an example, the default style -# sheet generated by doxygen has an example that shows how to put an image at -# the root of the tree instead of the PROJECT_NAME. Since the tree basically has -# the same information as the tab index, you could consider setting -# DISABLE_INDEX to YES when enabling this option. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_TREEVIEW = NO - -# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that -# doxygen will group on one line in the generated HTML documentation. -# -# Note that a value of 0 will completely suppress the enum values from appearing -# in the overview section. -# Minimum value: 0, maximum value: 20, default value: 4. -# This tag requires that the tag GENERATE_HTML is set to YES. - -ENUM_VALUES_PER_LINE = 4 - -# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used -# to set the initial width (in pixels) of the frame in which the tree is shown. -# Minimum value: 0, maximum value: 1500, default value: 250. -# This tag requires that the tag GENERATE_HTML is set to YES. - -TREEVIEW_WIDTH = 250 - -# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to -# external symbols imported via tag files in a separate window. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -EXT_LINKS_IN_WINDOW = NO - -# Use this tag to change the font size of LaTeX formulas included as images in -# the HTML documentation. When you change the font size after a successful -# doxygen run you need to manually remove any form_*.png images from the HTML -# output directory to force them to be regenerated. -# Minimum value: 8, maximum value: 50, default value: 10. -# This tag requires that the tag GENERATE_HTML is set to YES. - -FORMULA_FONTSIZE = 10 - -# Use the FORMULA_TRANPARENT tag to determine whether or not the images -# generated for formulas are transparent PNGs. Transparent PNGs are not -# supported properly for IE 6.0, but are supported on all modern browsers. -# -# Note that when changing this option you need to delete any form_*.png files in -# the HTML output directory before the changes have effect. -# The default value is: YES. -# This tag requires that the tag GENERATE_HTML is set to YES. - -FORMULA_TRANSPARENT = YES - -# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see -# http://www.mathjax.org) which uses client side Javascript for the rendering -# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX -# installed or if you want to formulas look prettier in the HTML output. When -# enabled you may also need to install MathJax separately and configure the path -# to it using the MATHJAX_RELPATH option. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -USE_MATHJAX = NO - -# When MathJax is enabled you can set the default output format to be used for -# the MathJax output. See the MathJax site (see: -# http://docs.mathjax.org/en/latest/output.html) for more details. -# Possible values are: HTML-CSS (which is slower, but has the best -# compatibility), NativeMML (i.e. MathML) and SVG. -# The default value is: HTML-CSS. -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_FORMAT = HTML-CSS - -# When MathJax is enabled you need to specify the location relative to the HTML -# output directory using the MATHJAX_RELPATH option. The destination directory -# should contain the MathJax.js script. For instance, if the mathjax directory -# is located at the same level as the HTML output directory, then -# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax -# Content Delivery Network so you can quickly see the result without installing -# MathJax. However, it is strongly recommended to install a local copy of -# MathJax from http://www.mathjax.org before deployment. -# The default value is: http://cdn.mathjax.org/mathjax/latest. -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest - -# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax -# extension names that should be enabled during MathJax rendering. For example -# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_EXTENSIONS = - -# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces -# of code that will be used on startup of the MathJax code. See the MathJax site -# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an -# example see the documentation. -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_CODEFILE = - -# When the SEARCHENGINE tag is enabled doxygen will generate a search box for -# the HTML output. The underlying search engine uses javascript and DHTML and -# should work on any modern browser. Note that when using HTML help -# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) -# there is already a search function so this one should typically be disabled. -# For large projects the javascript based search engine can be slow, then -# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to -# search using the keyboard; to jump to the search box use + S -# (what the is depends on the OS and browser, but it is typically -# , /