Ejemplo n.º 1
0
//--------------------------------------------------------------------------------------------------
static void RemoveApp
(
    const char* appNamePtr ///< The app name.
)
{
    le_appRemove_ConnectService();

    le_result_t result = le_appRemove_Remove(appNamePtr);

    if (result == LE_OK)
    {
        exit(EXIT_SUCCESS);
    }
    else if (result == LE_BUSY)
    {
        fprintf(stderr, "Failed to remove app '%s'. System busy, check logs.\n", appNamePtr);
    }
    else if (result == LE_NOT_FOUND)
    {
        fprintf(stderr, "App '%s' is not installed\n", appNamePtr);
    }
    else
    {
        fprintf(stderr, "Failed to remove app '%s' (%s)\n", appNamePtr, LE_RESULT_TXT(result));
    }

    exit(EXIT_FAILURE);
}
Ejemplo n.º 2
0
//--------------------------------------------------------------------------------------------------
static le_result_t GetUserUid
(
    le_cfg_IteratorRef_t i, ///< [in] Configuration tree iterator.
    uid_t*          uidPtr  ///< [out] Pointer to where the user ID will be put if successful.
)
//--------------------------------------------------------------------------------------------------
{
    le_result_t result;

    char userName[LIMIT_MAX_USER_NAME_BYTES];
    result = le_cfg_GetNodeName(i, "", userName, sizeof(userName));

    if (result != LE_OK)
    {
        LE_CRIT("Configuration node name too long under 'system/users/'.");
        return LE_OVERFLOW;
    }

    // Convert the user name into a user ID.
    result = user_GetUid(userName, uidPtr);
    if (result != LE_OK)
    {
        LE_CRIT("Failed to get user ID for user '%s'. (%s)", userName, LE_RESULT_TXT(result));
        return LE_NOT_FOUND;
    }

    return LE_OK;
}
Ejemplo n.º 3
0
//--------------------------------------------------------------------------------------------------
LE_SHARED void cfgInstall_Add
(
    const char* appName
)
//--------------------------------------------------------------------------------------------------
{
    le_result_t result;

    char filePath[256] = "/opt/legato/apps/";

    result = le_utf8_Append(filePath, appName, sizeof(filePath), NULL);
    LE_FATAL_IF(result != LE_OK, "App name '%s' is too long.", appName);

    result = le_utf8_Append(filePath, "/root.cfg", sizeof(filePath), NULL);
    LE_FATAL_IF(result != LE_OK, "App name '%s' is too long.", appName);

    LE_INFO("Importing configuration for application '%s' from '%s'.", appName, filePath);

    le_cfg_IteratorRef_t i = le_cfg_CreateWriteTxn("/apps");

    result = le_cfgAdmin_ImportTree(i, filePath, appName);

    LE_FATAL_IF(result != LE_OK,
                "Failed to import configuration from '%s' to 'root:/apps/%s' (%s)",
                filePath,
                appName,
                LE_RESULT_TXT(result));

    le_cfg_CommitTxn(i);
}
Ejemplo n.º 4
0
//--------------------------------------------------------------------------------------------------
static void PrintEntry
(
    void
)
{
    // Check path.
    if (Path[strlen(Path)-1] == '/')
    {
        fprintf(stderr, "Path must not end with a separator.\n");
        exit(EXIT_FAILURE);
    }

    // Read entry.
    uint8_t buf[LE_SECSTORE_MAX_ITEM_SIZE];
    size_t bufSize = sizeof(buf);

    le_result_t result = secStoreAdmin_Read(Path, buf, &bufSize);

    // Print entry.
    if (result == LE_OK)
    {
        printf("%s", (char*)buf);
    }
    else if (result == LE_NOT_FOUND)
    {
        fprintf(stderr, "Entry %s not found.\n", Path);
        exit(EXIT_FAILURE);
    }
    else
    {
        INTERNAL_ERR("Could not read item %s.  Result code %s.", Path, LE_RESULT_TXT(result));
    }
}
Ejemplo n.º 5
0
//--------------------------------------------------------------------------------------------------
void msgService_SendServiceId
(
    le_msg_ServiceRef_t serviceRef, ///< [in] Pointer to the service whose ID is to be sent.
    int                 socketFd    ///< [in] File descriptor of the connected socket to send on.
)
//--------------------------------------------------------------------------------------------------
{
    svcdir_ServiceId_t serviceId;

    memset(&serviceId, 0, sizeof(serviceId));

    serviceId.maxProtocolMsgSize = le_msg_GetProtocolMaxMsgSize(serviceRef->id.protocolRef);

    le_utf8_Copy(serviceId.protocolId,
                 le_msg_GetProtocolIdStr(serviceRef->id.protocolRef),
                 sizeof(serviceId.protocolId),
                 NULL);

    le_utf8_Copy(serviceId.serviceName,
                 serviceRef->id.name,
                 sizeof(serviceId.serviceName),
                 NULL);

    le_result_t result = unixSocket_SendDataMsg(socketFd, &serviceId, sizeof(serviceId));
    if (result != LE_OK)
    {
        LE_FATAL("Failed to send. Result = %d (%s)", result, LE_RESULT_TXT(result));
    }
    // NOTE: This is only done when the socket is newly opened, so this shouldn't ever
    //       return LE_NO_MEMORY to indicate send buffers being full.
}
Ejemplo n.º 6
0
// -------------------------------------------------------------------------------------------------
static int CallApi
(
    const char* command,                             ///< [IN] The name of the command to run.
    const char* kmodName,                            ///< [IN] Name of the module to work with.
    le_result_t (*functionPtr)(const char* namePtr)  ///< [IN] The function to work with that
                                                     ///<      module.
)
// -------------------------------------------------------------------------------------------------
{
    // Call the function, check the result.  Print the right message.  Return the error code.
    le_result_t result = (*functionPtr)(kmodName);

    if (result != LE_OK)
    {
        fprintf(stderr,
                "Could not %s the required module, %s. (%s)\n"
                "See the device log for details.\n",
                command,
                kmodName,
                LE_RESULT_TXT(result));

        return EXIT_FAILURE;
    }

    // Because our commands are all lower case, and we're starting the sentence with it, let's make
    // the first character uppercase.
    char* modifiedCmdStr = strdup(command);

    modifiedCmdStr[0] = toupper(modifiedCmdStr[0]);
    printf("%s of module %s has been successful.\n", modifiedCmdStr, kmodName);
    free(modifiedCmdStr);

    return EXIT_SUCCESS;
}
Ejemplo n.º 7
0
//--------------------------------------------------------------------------------------------------
static pid_t GetTasksId
(
    int fd                      ///< [IN] File descriptor to an opened procs or tasks file.
)
{
    // Read a pid from the file.
    pid_t pid;
    char pidStr[100];
    le_result_t result = fd_ReadLine(fd, pidStr, sizeof(pidStr));

    LE_FATAL_IF(result == LE_OVERFLOW, "Buffer to read PID is too small.");

    if (result == LE_OK)
    {
        // Convert the string to a pid and store it in the caller's buffer.
        le_result_t r = le_utf8_ParseInt(&pid, pidStr);

        if (r == LE_OK)
        {
            return pid;
        }

        LE_ERROR("Could not convert '%s' to a PID.  %s.", pidStr, LE_RESULT_TXT(r));
        result = LE_FAULT;
    }

    return result;
}
Ejemplo n.º 8
0
//-------------------------------------------------------------------------------------------------
static const char* GetUpdateType
(
    void
)
//--------------------------------------------------------------------------------------------------
{
    le_avc_UpdateType_t type;
    le_result_t res = le_avc_GetUpdateType(&type);
    if (res != LE_OK)
    {
        LE_CRIT("Unable to get update type (%s)", LE_RESULT_TXT(res));
        return "UNKNOWN";
    }
    else
    {
        switch (type)
        {
        case LE_AVC_FIRMWARE_UPDATE:
            return "FIRMWARE";

        case LE_AVC_APPLICATION_UPDATE:
            return "APPLICATION";

        case LE_AVC_FRAMEWORK_UPDATE:
            return "FRAMEWORK";

        case LE_AVC_UNKNOWN_UPDATE:
            return "UNKNOWN";
        }

        LE_CRIT("Unexpected update type %d", type);
        return "UNKNOWN";
    }
}
Ejemplo n.º 9
0
//--------------------------------------------------------------------------------------------------
static void PrintSize
(
    void
)
{
    uint64_t size;

    le_result_t result = secStoreAdmin_GetSize(Path, &size);

    if (result == LE_OK)
    {
        printf("%" PRIu64 "\n", size);
    }
    else if (result == LE_NOT_FOUND)
    {
        fprintf(stderr, "Path %s not found.\n", Path);
        exit(EXIT_FAILURE);
    }
    else
    {
        INTERNAL_ERR("Could not get size for path %s.  Result code %s.",
                     Path,
                     LE_RESULT_TXT(result));
    }
}
Ejemplo n.º 10
0
//--------------------------------------------------------------------------------------------------
void le_msg_AdvertiseService
(
    le_msg_ServiceRef_t serviceRef  ///< [in] Reference to the service.
)
//--------------------------------------------------------------------------------------------------
{
    LE_FATAL_IF(serviceRef->state != LE_MSG_SERVICE_HIDDEN,
                "Re-advertising before hiding service '%s:%s'.",
                serviceRef->id.name,
                le_msg_GetProtocolIdStr(serviceRef->id.protocolRef));

    serviceRef->state = LE_MSG_SERVICE_CONNECTING;

    // Open a socket.
    int fd = unixSocket_CreateSeqPacketUnnamed();
    serviceRef->directorySocketFd = fd;

    // Check for failure.
    LE_FATAL_IF(fd == LE_NOT_PERMITTED, "Permission to open socket denied.");
    LE_FATAL_IF(fd == LE_FAULT, "Failed to open socket.");

    // Warn if one of the three standard I/O streams have been somehow connected to the
    // Service Directory.
    if (fd < 3)
    {
        const char* streamNameStr;
        switch (fd)
        {
            case 0:
                streamNameStr = "stdin";
                break;
            case 1:
                streamNameStr = "stdout";
                break;
            case 2:
                streamNameStr = "stderr";
                break;
        }
        LE_WARN("Service Directory connection mapped to %s.", streamNameStr);
    }

    // Set the socket non-blocking.
    fd_SetNonBlocking(fd);

    // Start monitoring the socket for events.
    StartMonitoringDirectorySocket(serviceRef);

    // Connect the socket to the Service Directory.
    le_result_t result = unixSocket_Connect(fd, LE_SVCDIR_SERVER_SOCKET_NAME);
    LE_FATAL_IF((result != LE_OK) && (result != LE_WOULD_BLOCK),
                "Failed to connect to Service Directory. Result = %d (%s).",
                result,
                LE_RESULT_TXT(result));

    // Wait for writeability notification on the socket.  See DirectorySocketWriteable().
}
Ejemplo n.º 11
0
//--------------------------------------------------------------------------------------------------
void le_msg_AdvertiseService
(
    le_msg_ServiceRef_t serviceRef  ///< [in] Reference to the service.
)
//--------------------------------------------------------------------------------------------------
{
    // Open a socket and connect it to the Service Directory.
    int fd = unixSocket_CreateSeqPacketUnnamed();

    // Check for failure.
    LE_FATAL_IF(fd == LE_NOT_PERMITTED, "Permission to open socket denied.");
    LE_FATAL_IF(fd == LE_FAULT, "Failed to open socket.");

    // Warn if one of the three standard I/O streams have been somehow connected to the
    // Service Directory.
    if (fd < 3)
    {
        const char* streamNameStr;
        switch (fd)
        {
            case 0:
                streamNameStr = "stdin";
                break;
            case 1:
                streamNameStr = "stdout";
                break;
            case 2:
                streamNameStr = "stderr";
                break;
        }
        LE_WARN("Service Directory connection mapped to %s.", streamNameStr);
    }

    le_result_t result = unixSocket_Connect(fd, LE_SVCDIR_SERVER_SOCKET_NAME);
    LE_FATAL_IF(result != LE_OK,
                "Failed to connect to Service Directory. Result = %d (%s).",
                result,
                LE_RESULT_TXT(result));

    serviceRef->directorySocketFd = fd;

    // Set the socket non-blocking.
    fd_SetNonBlocking(fd);

    // Start monitoring the socket for events.
    StartMonitoringDirectorySocket(serviceRef);

    // Send the Service ID to the Service Directory.
    msgService_SendServiceId(serviceRef, fd);

    // Wait for the Service Directory to respond by either dropping the connection
    // (meaning that we have been denied permission to offer this service) or by
    // forwarding us file descriptors for authenticated client connections.
}
Ejemplo n.º 12
0
//--------------------------------------------------------------------------------------------------
le_result_t le_fwupdate_InstallAndMarkGood
(
    void
)
{
    le_result_t result;
    /* request the swap and sync */
    result = pa_fwupdate_Install(true);
    /* the previous function returns only if there has been an error */
    LE_ERROR(" !!! Error %s", LE_RESULT_TXT(result));
    return result;
}
Ejemplo n.º 13
0
//--------------------------------------------------------------------------------------------------
static void GetTextCallback
(
    le_atServer_CmdRef_t    cmdRef,
    le_result_t             result,
    char*                   textPtr,
    uint32_t                len,
    void*                   ctxPtr
)
{
    le_atServer_FinalRsp_t resp = LE_ATSERVER_OK;

    LE_INFO("callback [%s:%u:%s]", LE_RESULT_TXT(result), len, textPtr);
    LE_ASSERT_OK(le_atServer_SendIntermediateResponse(cmdRef, textPtr));
    LE_ASSERT_OK(le_atServer_SendIntermediateResponse(cmdRef, LE_RESULT_TXT(result)));
    if (LE_OK != result)
    {
        resp = LE_ATSERVER_ERROR;
    }

    // final response using the deprecated API
    LE_ASSERT_OK(le_atServer_SendFinalResponse(cmdRef, resp, false, ""));
}
Ejemplo n.º 14
0
//--------------------------------------------------------------------------------------------------
static le_result_t WriteFs
(
    const char  *pathPtr,   ///< File path
    uint8_t     *bufPtr,    ///< Data buffer
    size_t      size        ///< Buffer size
)
{
    le_fs_FileRef_t fileRef;
    le_result_t result;

    result = le_fs_Open(pathPtr, LE_FS_WRONLY | LE_FS_CREAT, &fileRef);
    if (LE_OK != result)
    {
        LE_ERROR("failed to open %s: %s", pathPtr, LE_RESULT_TXT(result));
        return result;
    }

    result = le_fs_Write(fileRef, bufPtr, size);
    if (LE_OK != result)
    {
        LE_ERROR("failed to write %s: %s", pathPtr, LE_RESULT_TXT(result));
        if (LE_OK != le_fs_Close(fileRef))
        {
            LE_ERROR("failed to close %s", pathPtr);
        }
        return result;
    }

    result = le_fs_Close(fileRef);
    if (LE_OK != result)
    {
        LE_ERROR("failed to close %s: %s", pathPtr, LE_RESULT_TXT(result));
        return result;
    }

    return LE_OK;
}
Ejemplo n.º 15
0
//--------------------------------------------------------------------------------------------------
static inline void SafeStrAppend
(
    char        *destBufferPtr,         ///< [IN]  Buffer to append to.
    size_t       destBufferSize,        ///< [IN]  Buffer size.
    size_t      *currentDestStrLenPtr,  ///< [OUT] Length of resulting string.
    const char  *appendStrPtr           ///< [IN]  String to append to buffer.
)
{
    le_result_t result = le_utf8_Append(destBufferPtr, appendStrPtr, destBufferSize,
                            currentDestStrLenPtr);
    if (result != LE_OK)
    {
        LE_WARN("Error appending to string: %s", LE_RESULT_TXT(result));
    }
}
Ejemplo n.º 16
0
//--------------------------------------------------------------------------------------------------
static le_result_t GetAppUid
(
    le_cfg_IteratorRef_t i, ///< [in] Configuration tree iterator.
    uid_t*          uidPtr  ///< [out] Pointer to where the user ID will be put if successful.
)
//--------------------------------------------------------------------------------------------------
{
    le_result_t result;

    char appName[LIMIT_MAX_APP_NAME_BYTES];
    result = le_cfg_GetNodeName(i, "", appName, sizeof(appName));
    if (result != LE_OK)
    {
        LE_CRIT("Configuration node name too long under 'system/apps/'.");
        return LE_OVERFLOW;
    }

    // If this is an "unsandboxed" app, use the root user ID.
    if (le_cfg_GetBool(i, "sandboxed", true) == false)
    {
        char path[256];
        le_cfg_GetPath(i, "", path, sizeof(path));
        LE_DEBUG("'%s' = <root>", path);

        *uidPtr = 0;
        return LE_OK;
    }

    // Convert the app name into a user name by prefixing it with "app".
    char userName[LIMIT_MAX_USER_NAME_BYTES] = "app";
    result = le_utf8_Append(userName, appName, sizeof(userName), NULL);
    if (result != LE_OK)
    {
        LE_CRIT("Failed to convert app name into user name.");
        return LE_OVERFLOW;
    }

    // Convert the app user name into a user ID.
    result = user_GetUid(userName, uidPtr);
    if (result != LE_OK)
    {
        LE_CRIT("Failed to get user ID for user '%s'. (%s)", userName, LE_RESULT_TXT(result));
        return LE_NOT_FOUND;
    }

    return LE_OK;
}
Ejemplo n.º 17
0
static void SampleHumidity
(
    psensor_Ref_t ref
)
{
    double sample;
    le_result_t result = humidity_Read(&sample);
   
    if (result == LE_OK)
    {
	psensor_PushNumeric(ref, 0 /* now */, sample);
    }
    else
    {
	LE_ERROR("Failed to read sensor (%s)", LE_RESULT_TXT(result));
    }
}
Ejemplo n.º 18
0
// -------------------------------------------------------------------------------------------------
static void ReportImportExportFail
(
    le_result_t result,        ///< The result value we're checking.
    const char* operationPtr,  ///< Name of the attempted operation.
    const char* nodePathPtr,   ///< The path to the node in the config tree.
    const char* filePathPtr    ///< The path the file involved in the import/export.
)
// -------------------------------------------------------------------------------------------------
{
    fprintf(stderr,
            "%s failure, %d: %s.\nFile Path: %s\nNode Path: %s\n",
             operationPtr,
             result,
             LE_RESULT_TXT(result),
             filePathPtr,
             nodePathPtr);
}
Ejemplo n.º 19
0
//--------------------------------------------------------------------------------------------------
le_result_t dstr_CopyToCstr
(
    char* destStrPtr,               ///< [OUT] The destiniation string buffer.
    size_t destStrMax,              ///< [IN]  The maximum string the buffer can handle.
    const dstr_Ref_t sourceStrRef,  ///< [IN]  The dynamic string to copy to said buffer.
    size_t* totalCopied             ///< [IN]  If supplied, this is the total number of bytes copied
                                    ///<       to the target string buffer.
)
//--------------------------------------------------------------------------------------------------
{
    dstr_Ref_t segmentRef = NULL;

    if (totalCopied)
    {
        *totalCopied = 0;
    }

    for (segmentRef = FirstSegmentRef(sourceStrRef);
         segmentRef != NULL;
         segmentRef = NextSegmentRef(sourceStrRef, segmentRef))
    {
        size_t bytesCopied = 0;
        le_result_t result = le_utf8_Copy(destStrPtr,
                                          segmentRef->body.value,
                                          destStrMax,
                                          &bytesCopied);

        if (totalCopied)
        {
            *totalCopied += bytesCopied;
        }

        if (result == LE_OVERFLOW)
        {
            return LE_OVERFLOW;
        }

        LE_FATAL_IF(result != LE_OK, "Unexpected result code returned, %s.", LE_RESULT_TXT(result));

        destStrMax -= bytesCopied;
        destStrPtr += bytesCopied;

    }

    return LE_OK;
}
Ejemplo n.º 20
0
//--------------------------------------------------------------------------------------------------
static void DeletePath
(
    void
)
{
    le_result_t result = secStoreAdmin_Delete(Path);

    if (result == LE_NOT_FOUND)
    {
        fprintf(stderr, "Entry %s not found.\n", Path);
        exit(EXIT_FAILURE);
    }
    else if (result != LE_OK)
    {
        INTERNAL_ERR("Could not delete path %s.  Result code %s.", Path, LE_RESULT_TXT(result));
    }
}
Ejemplo n.º 21
0
//--------------------------------------------------------------------------------------------------
static void DirectorySocketReadable
(
    int fd
)
//--------------------------------------------------------------------------------------------------
{
    Service_t* servicePtr = le_event_GetContextPtr();
    le_result_t result;

    int clientSocketFd;

    // Receive the Client connection file descriptor from the Service Directory.
    result = unixSocket_ReceiveMsg(fd,
                                   NULL,   // dataBuffPtr
                                   0,      // dataBuffSize
                                   &clientSocketFd,
                                   NULL);  // credPtr
    if (result == LE_CLOSED)
    {
        LE_DEBUG("Connection has closed.");
    }
    else if (result != LE_OK)
    {
        LE_FATAL("Failed to receive client fd from Service Directory (%d: %s).",
                 result,
                 LE_RESULT_TXT(result));
    }
    else if (clientSocketFd < 0)
    {
        LE_ERROR("Received something other than a file descriptor from Service Directory for (%s:%s).",
                 servicePtr->id.name,
                 le_msg_GetProtocolIdStr(servicePtr->id.protocolRef));
    }
    else
    {
        // Create a server-side Session object for that connection to this Service.
        le_msg_SessionRef_t sessionRef = msgSession_CreateServerSideSession(servicePtr, clientSocketFd);

        // If successful, call the registered "open" handler, if there is one.
        if (sessionRef != NULL)
        {
            CallOpenHandler(servicePtr, sessionRef);
        }
    }
}
Ejemplo n.º 22
0
static void SampleTemperature
(
    psensor_Ref_t ref
)
{
    double sample;

    le_result_t result = temperature_Read(&sample);

    if (result == LE_OK)
    {
        psensor_PushNumeric(ref, 0 /* now */, sample);
    }
    else
    {
        LE_ERROR("Failed to read sensor (%s).", LE_RESULT_TXT(result));
    }
}
Ejemplo n.º 23
0
//--------------------------------------------------------------------------------------------------
static void PrintTotalSizes
(
    void
)
{
    uint64_t totalSize, freeSize;

    le_result_t result = secStoreAdmin_GetTotalSpace(&totalSize, &freeSize);

    if (result == LE_OK)
    {
        printf("Total %" PRIu64 "\n", totalSize);
        printf("Free %" PRIu64 "\n", freeSize);
    }
    else
    {
        INTERNAL_ERR("Could not get available secure storage space.  Result code %s.",
                     LE_RESULT_TXT(result));
    }
}
Ejemplo n.º 24
0
static void MultiTreeTest()
{
    char strBuffer[STR_SIZE] = { 0 };

    static char pathBuffer[STR_SIZE] = { 0 };
    snprintf(pathBuffer, STR_SIZE, "foo:/%s/quickMultiTreeTest/value", TestRootDir);


    le_cfg_QuickSetString(pathBuffer, "hello world");


    le_result_t result = le_cfg_QuickGetString(pathBuffer, strBuffer, STR_SIZE, "");
    LE_FATAL_IF(result != LE_OK,
                "Test: %s - Could not read value from tree, foo.  Reason = %s",
                TestRootDir,
                LE_RESULT_TXT(result));
    LE_FATAL_IF(strcmp(strBuffer, "hello world") != 0,
                "Test: %s - Did not get expected value from tree foo.  Got '%s'.",
                TestRootDir,
                strBuffer);
}
Ejemplo n.º 25
0
//--------------------------------------------------------------------------------------------------
static void NewSessionHandler
(
    le_msg_SessionRef_t sessionRef,
    void*               contextPtr
)
//--------------------------------------------------------------------------------------------------
{
    LE_INFO("Client started a new session.");

    LE_INFO("contextPtr = %p.", contextPtr);
    LE_TEST(contextPtr == &ServiceOpenContextPtr);

    // Because the unit tests are run always as a single, non-root user, we expect the user ID
    // of the client to be the same user ID that we are running as.
    uid_t clientUserId;
    uid_t myUserId = getuid();
    le_result_t result = le_msg_GetClientUserId(sessionRef, &clientUserId);
    LE_INFO("le_msg_GetClientUserId() returned '%s' with UID %u.",
            LE_RESULT_TXT(result),
            clientUserId);
    LE_INFO("getuid() returned %u.", myUserId);
    LE_TEST(clientUserId == myUserId);
}
Ejemplo n.º 26
0
//--------------------------------------------------------------------------------------------------
static void PopulateAppInfoObjects
(
    void
)
//--------------------------------------------------------------------------------------------------
{
    appCfg_Iter_t appIterRef = appCfg_CreateAppsIter();
    char appName[MAX_APP_NAME_BYTES] = "";
    char versionBuffer[MAX_VERSION_STR_BYTES] = "";
    le_result_t result;

    int foundAppCount = 0;

    result = appCfg_GetNextItem(appIterRef);

    while (result == LE_OK)
    {
        result = appCfg_GetAppName(appIterRef, appName, sizeof(appName));

        if ((result == LE_OK) &&
            (false == IsHiddenApp(appName)))
        {
            LE_DEBUG("Loading object instance for app, '%s'.", appName);

            assetData_InstanceDataRef_t instanceRef = GetObject9InstanceForApp(appName, false);

            if (appCfg_GetVersion(appIterRef, versionBuffer, sizeof(versionBuffer)) == LE_OVERFLOW)
            {
                LE_WARN("Warning, app, '%s' version string truncated to '%s'.",
                        appName,
                        versionBuffer);
            }

            if (0 == strlen(versionBuffer))
            {
                // Use the application hash if the version is empty
                le_appInfo_GetHash(appName, versionBuffer, sizeof(versionBuffer));
            }

            assetData_client_SetString(instanceRef, O9F_PKG_VERSION, versionBuffer);

            assetData_client_SetBool(instanceRef,   O9F_UPDATE_SUPPORTED_OBJECTS, false);

            // No need to save the status in config tree, while populating object9
            SetObj9State(instanceRef, US_INSTALLED, UR_INSTALLED, false);

            foundAppCount++;
        }
        else
        {
            LE_WARN("Application name too large or is hidden, '%s.'", appName);
        }

        result = appCfg_GetNextItem(appIterRef);
    }

    appCfg_DeleteIter(appIterRef);
    LE_FATAL_IF(result != LE_NOT_FOUND,
                "Application cache initialization, unexpected error returned, (%d): \"%s\"",
                result,
                LE_RESULT_TXT(result));

    int index = 0;

    LE_DEBUG("Found app count %d.", foundAppCount);

    while (foundAppCount > 0)
    {
        assetData_InstanceDataRef_t instanceRef = NULL;
        le_result_t result = assetData_GetInstanceRefById(LWM2M_NAME, 9, index, &instanceRef);

        LE_DEBUG("Index %d.", index);

        if (result == LE_OK)
        {
            assetData_client_GetString(instanceRef, O9F_PKG_NAME, appName, sizeof(appName));

            LE_DEBUG("Mapping app '%s'.", appName);

            SetObject9InstanceForApp(appName, instanceRef);
            foundAppCount--;
        }

        index++;
    }
}
Ejemplo n.º 27
0
//--------------------------------------------------------------------------------------------------
le_result_t le_cellnet_SetSimPinCode
(
    le_sim_Id_t simId,
        ///< [IN]
        ///< SIM identifier.

    const char* pinCodePtr
        ///< [IN]
        ///< PIN code to insert in the secure storage.
)
{

    le_result_t result=LE_OK;
    size_t pinCodeLength = strlen(pinCodePtr);

    LE_DEBUG("simId= %d",simId);

    if (simId >= LE_SIM_ID_MAX)
    {
        LE_ERROR("Invalid simId (%d) provided!", simId);
        result = LE_OUT_OF_RANGE;
    }
    else
    {
        //void entry is taken into account
        if (strncmp(pinCodePtr,"",LE_SIM_PIN_MAX_LEN)!=0)
        {
            if (pinCodeLength > LE_SIM_PIN_MAX_LEN)
            {
                LE_KILL_CLIENT("PIN code exceeds %d", LE_SIM_PIN_MAX_LEN);
                return LE_FAULT;
            }
            else if (pinCodeLength < LE_SIM_PIN_MIN_LEN)
            {
                LE_ERROR("SIM PIN code is not long enough (min 4 digits)");
                result = LE_UNDERFLOW;
            }
            else
            {
                // test SIM pincode format
                int i;
                bool test_ok = true;
                for (i=0; ((i<pinCodeLength) && test_ok); i++)
                {
                    if ((pinCodePtr[i] < 0x30) || (pinCodePtr[i] > 0x39))
                    {
                        test_ok = false;
                        break;
                    }
                }
                if (false == test_ok)
                {
                    LE_ERROR("SIM PIN code format error");
                    result = LE_FORMAT_ERROR;
                }
            }
        }
    }

    if (LE_OK == result)
    {
        // Set the secure storage path for the SIM
        char secStorePath[LE_SECSTORE_MAX_NAME_BYTES];
        snprintf(secStorePath, sizeof(secStorePath), "%s/%d/%s",
                 SECSTORE_NODE_SIM, simId, SECSTORE_NODE_PIN);

        result = le_secStore_Write(secStorePath, (uint8_t*)pinCodePtr,
                                   strnlen(pinCodePtr, LE_SIM_PIN_MAX_BYTES));

        if (LE_OK == result)
        {
            LE_DEBUG("SIM PIN code correctly inserted in secure storage");

            // New SIM pincode is taken into account
            LoadSimFromSecStore(simId);
            GetAndSendCellNetStateEvent();
        }
        else
        {
            LE_ERROR("Unable to store PIN code, error %s\n", LE_RESULT_TXT(result));
        }
    }

    return result;
}
Ejemplo n.º 28
0
//--------------------------------------------------------------------------------------------------
static void LoadSimFromSecStore
(
    le_sim_Id_t simId
)
{
    uint32_t attemptCounter = SECSTORE_ATTEMPT_MAX;
    le_result_t result;
    le_sim_States_t simState;

    LE_DEBUG("Start reading SIM-%d information in secure storage",simId);

    do
    {
        simState = le_sim_GetState(simId);

        switch (simState)
        {
            case LE_SIM_INSERTED:
            {
                // Set the secure storage path for the SIM
                char secStorePath[LE_SECSTORE_MAX_NAME_BYTES];
                snprintf(secStorePath, sizeof(secStorePath), "%s/%d/%s",
                         SECSTORE_NODE_SIM, simId, SECSTORE_NODE_PIN);

                char simPin[LE_SIM_PIN_MAX_BYTES] = {0};
                size_t simSize = LE_SIM_PIN_MAX_BYTES;

                // Read PIN code stored in secure storage
                result = le_secStore_Read(secStorePath, (uint8_t *)simPin, &simSize);
                if (LE_NOT_FOUND == result)
                {
                    LE_ERROR("SIM PIN code isn't found in the secure storage");
                    return;
                }
                else if (LE_OVERFLOW == result)
                {
                    LE_WARN("PIN string too large for SIM-%d", simId);
                    return;
                }
                else if (LE_OK != result)
                {
                    LE_ERROR("Unable to retrieve PIN for SIM-%d, error %s",
                             simId, LE_RESULT_TXT(result));
                    return;
                }
                if (0 == strncmp(simPin, "", sizeof(simPin)))
                {
                    LE_WARN("PIN not set for SIM-%d", simId);
                    return;
                }
                if (LE_OK != (result = le_sim_EnterPIN(simId, simPin)))
                {
                    LE_ERROR("Error.%d Failed to enter SIM pin for SIM-%d", result, simId);
                    return;
                }
                LE_DEBUG("Sim-%d is unlocked", simId);

                attemptCounter = 1;
                break;
            }
            case LE_SIM_BLOCKED:
            {
                LE_EMERG("Be careful the sim-%d is BLOCKED, need to enter PUK code",simId);
                attemptCounter = 1;
                break;
            }
            case LE_SIM_BUSY:
                if (attemptCounter==1)
                {
                    LE_WARN("Could not load the configuration because "
                            "the SIM is still busy after %d attempts", SECSTORE_ATTEMPT_MAX);
                }
                else
                {
                    LE_WARN("Sim-%d was busy when loading configuration,"
                            "retry in 1 seconds",simId);
                }
                sleep(1); // Retry in 1 second.
                break;
            case LE_SIM_READY:
                LE_DEBUG("Sim-%d is ready",simId);
                attemptCounter = 1;
                break;
            case LE_SIM_ABSENT:
                LE_WARN("Sim-%d is absent",simId);
                attemptCounter = 1;
                break;
            case LE_SIM_POWER_DOWN:
                LE_WARN("Sim-%d is powered down",simId);
                break;
            case LE_SIM_STATE_UNKNOWN:
                break;
        }
    } while (--attemptCounter);

    LE_DEBUG("Load SIM information is done");
}
Ejemplo n.º 29
0
//--------------------------------------------------------------------------------------------------
le_result_t le_cellnet_GetSimPinCode
(
    le_sim_Id_t simId,
        ///< [IN]
        ///< SIM identifier.

    char* pinCodePtr,
        ///< [OUT]
        ///< Read the PIN code from the secure storage.

    size_t pinCodeNumElements
        ///< [IN]

)
{
    if (pinCodePtr == NULL)
    {
        LE_KILL_CLIENT("pinCodePtr is NULL.");
        return LE_FAULT;
    }

    le_result_t result=LE_OK;

    LE_DEBUG("simId= %d",simId);

    if (simId >= LE_SIM_ID_MAX)
    {
        LE_ERROR("Invalid simId (%d) provided!", simId);
        result = LE_OUT_OF_RANGE;
    }
    else
    {
        // Set the secure storage path for the SIM
        char secStorePath[LE_SECSTORE_MAX_NAME_BYTES];
        snprintf(secStorePath, sizeof(secStorePath), "%s/%d/%s",
                 SECSTORE_NODE_SIM, simId, SECSTORE_NODE_PIN);

        char simPin[LE_SIM_PIN_MAX_BYTES] = {0};
        size_t simSize = LE_SIM_PIN_MAX_BYTES;

        // Read PIN code stored in secure storage
        result = le_secStore_Read(secStorePath, (uint8_t *)simPin, &simSize);

        if (LE_NOT_FOUND == result)
        {
            LE_ERROR("SIM PIN code isn't found in the secure storage");
        }
        else if (LE_OVERFLOW == result)
        {
            LE_ERROR("Retrieved SIM PIN code exceeds the supplied buffer");
        }
        else if (LE_OK != result)
        {
            LE_ERROR("Unable to retrieve PIN, error %s", LE_RESULT_TXT(result));
        }
        else
        {
            // void entry is taken into account
            if (   (0 != strncmp(simPin, "", LE_SIM_PIN_MAX_LEN))
                && (strlen(simPin) < LE_SIM_PIN_MIN_LEN))
            {
                LE_ERROR("Retrieved SIM PIN code is not long enough (min 4 digits)");
                result = LE_UNDERFLOW;
            }
            else
            {
                // Copy pincode
                result = le_utf8_Copy( pinCodePtr, simPin, LE_SIM_PIN_MAX_BYTES, NULL);
                if (result == LE_OK)
                {
                    LE_DEBUG("SIM PIN code retrieved OK");
                }
                else
                {
                    LE_DEBUG("SIM PIN code not retrieved: too long for buffer");
                }
            }
        }
    }
    return result;
}
Ejemplo n.º 30
0
//--------------------------------------------------------------------------------------------------
static le_result_t GetServerUid
(
    le_cfg_IteratorRef_t    i,  ///< [in] Config tree iterator positioned at binding config.
    uid_t*  uidPtr              ///< [out] The application's user ID.
)
//--------------------------------------------------------------------------------------------------
{
    le_result_t result;

    char userName[LIMIT_MAX_USER_NAME_BYTES];

    // If an app name is present in the binding config,
    if (le_cfg_NodeExists(i, "app"))
    {
        // Make sure there isn't also a user name.
        if (le_cfg_NodeExists(i, "user"))
        {
            char path[LIMIT_MAX_PATH_BYTES];
            le_cfg_GetPath(i, "", path, sizeof(path));
            LE_CRIT("Both server user and app nodes appear under binding (@ %s)", path);
            return LE_DUPLICATE;
        }

        // Get the app name.
        char appName[LIMIT_MAX_APP_NAME_BYTES];
        result = le_cfg_GetString(i, "app", appName, sizeof(appName), "");
        if (result != LE_OK)
        {
            char path[LIMIT_MAX_PATH_BYTES];
            le_cfg_GetPath(i, "app", path, sizeof(path));
            LE_CRIT("Server app name too big (@ %s)", path);
            return result;
        }
        if (appName[0] == '\0')
        {
            char path[LIMIT_MAX_PATH_BYTES];
            le_cfg_GetPath(i, "app", path, sizeof(path));
            LE_CRIT("Server app name empty (@ %s)", path);
            return LE_NOT_FOUND;
        }

        // Find out if the server app is sandboxed.  If not, it runs as root.
        char path[LIMIT_MAX_PATH_BYTES];
        if (snprintf(path, sizeof(path), "/apps/%s/sandboxed", appName) >= sizeof(path))
        {
            LE_CRIT("Config node path too long (app name '%s').", appName);
            return LE_OVERFLOW;
        }
        if (!le_cfg_GetBool(i, path, true))
        {
            *uidPtr = 0;

            return LE_OK;
        }

        // It is not sandboxed.  Convert the app name into a user name.
        result = user_AppNameToUserName(appName, userName, sizeof(userName));
        if (result != LE_OK)
        {
            LE_CRIT("Failed to convert app name '%s' into a user name.", appName);

            return result;
        }
    }
    // If a server app name is not present in the binding config,
    else
    {
        // Get the server user name instead.
        result = le_cfg_GetString(i, "user", userName, sizeof(userName), "");
        if (result != LE_OK)
        {
            char path[LIMIT_MAX_PATH_BYTES];

            le_cfg_GetPath(i, "user", path, sizeof(path));
            LE_CRIT("Server user name too big (@ %s)", path);

            return result;
        }
        if (userName[0] == '\0')
        {
            char path[LIMIT_MAX_PATH_BYTES];

            le_cfg_GetPath(i, "", path, sizeof(path));
            LE_CRIT("Server user name or app name missing (@ %s)", path);

            return LE_NOT_FOUND;
        }
    }

    // Convert the server's user name into a user ID.
    result = user_GetUid(userName, uidPtr);
    if (result != LE_OK)
    {
        // Note: This can happen if the server application isn't installed yet.
        //       When the server application is installed, sdir load will be run
        //       again and the bindings will be correctly set up at that time.
        if (strncmp(userName, "app", 3) == 0)
        {
            LE_DEBUG("Couldn't get UID for application '%s'.  Perhaps it is not installed yet?",
                     userName + 3);
        }
        else
        {
            char path[LIMIT_MAX_PATH_BYTES];
            le_cfg_GetPath(i, "", path, sizeof(path));
            LE_CRIT("Couldn't convert server user name '%s' to UID (%s @ %s)",
                    userName,
                    LE_RESULT_TXT(result),
                    path);
        }

        return result;
    }

    return LE_OK;
}