Пример #1
0
_i32 sl_extlib_FlcOpenFile(_u8 *file_name, _i32 file_size, _u32 *ulToken, _i32 *lFileHandle, _i32 open_flags)
{
	if(open_flags == _FS_MODE_OPEN_READ)
	{
		return sl_FsOpen((_u8 *)file_name,
				_FS_MODE_OPEN_READ, ulToken, lFileHandle);
	}
	else
	{
		/* MCU image name should be changed */
		if(strstr((char *)file_name, "/sys/mcuimgA") != NULL)
		{
			/* mcuimg1 is for factory default,
	      mcuimg2,3 are for OTA updates */
			file_name[11] = (_u8)_McuImageGetNewIndex() + '1';
			/* make sure that the file is not opened as
	      fail-safe since it might fill the entire SFLASH and
	      it is not required for the MCU image */
			open_flags &= ~_FS_FILE_OPEN_FLAG_COMMIT;
			Report("sl_extlib_FlcOpenFile: MCU image"
					"name converted to %s \r\n", file_name);
		}
		return sl_FsOpen((_u8 *)file_name,
				FS_MODE_OPEN_CREATE(file_size, open_flags),
				ulToken, lFileHandle);
	}
}
void ensureCertificateFile(const unsigned char *certificate, unsigned int certificateLen) {
    long certificateFile = -1;

    short status = sl_FsOpen((unsigned char *)SSL_CA_CERT_FILE_NAME, FS_MODE_OPEN_READ, NULL, &certificateFile);
    if (status < 0) {
#ifdef SSL_DEBUG
        DEBUG_PRINT("[Parse] Creating certificate file\r\n");
#endif /* SSL_DEBUG */

        sl_FsClose(certificateFile, 0, 0, 0);
        certificateFile = -1;

        status = sl_FsOpen((unsigned char *)SSL_CA_CERT_FILE_NAME,
                FS_MODE_OPEN_CREATE(65536, _FS_FILE_OPEN_FLAG_COMMIT | _FS_FILE_PUBLIC_WRITE),
                NULL, &certificateFile);
        if (status < 0) {
#ifdef SSL_DEBUG
            DEBUG_PRINT("[Parse] Error creating certificate file: %d\r\n", status);
            if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
                 DEBUG_PRINT("[Parse] No available blocks. Need to flash your device file system...\r\n");
            }
#endif /* SSL_DEBUG */
            return;
        }

        sl_FsClose(certificateFile, 0, 0, 0);
        certificateFile = -1;

        status = sl_FsOpen((unsigned char *)SSL_CA_CERT_FILE_NAME, FS_MODE_OPEN_WRITE, NULL, &certificateFile);
        if (status < 0) {
#ifdef SSL_DEBUG
            DEBUG_PRINT("[Parse] Error creating certificate file: %d\r\n", status);
            if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
                 DEBUG_PRINT("[Parse] No available blocks. Need to flash your device file system...\r\n");
            }
#endif /* SSL_DEBUG */
            sl_FsClose(certificateFile, 0, 0, 0);
            return;
        }

        status = sl_FsWrite(certificateFile, 0, (unsigned char*)certificate, certificateLen);
        if (status < 0) {
#ifdef SSL_DEBUG
            DEBUG_PRINT("[Parse] Error creating certificate file: %d\r\n", status);
            if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
                 DEBUG_PRINT("[Parse] No available blocks. Need to flash your device file system...\r\n");
            }
#endif /* SSL_DEBUG */
        }
    }

    sl_FsClose(certificateFile, 0, 0, 0);
}
Пример #3
0
void updater_finnish (void) {
    _i32 fhandle;

    if (updater_data.fhandle > 0) {
        sl_LockObjLock (&wlan_LockObj, SL_OS_WAIT_FOREVER);
        // close the file being updated
        sl_FsClose(updater_data.fhandle, NULL, NULL, 0);
#ifdef WIPY
        // if we still have an image pending for verification, leave the boot info as it is
        if (!strncmp(IMG_PREFIX, updater_data.path, strlen(IMG_PREFIX)) && sBootInfo.Status != IMG_STATUS_CHECK) {
#else
        if (!strncmp(IMG_PREFIX, updater_data.path, strlen(IMG_PREFIX))) {
#endif
#ifdef DEBUG
            if (!sl_FsOpen((unsigned char *)IMG_BOOT_INFO, FS_MODE_OPEN_READ, NULL, &fhandle)) {

                ASSERT (sizeof(sBootInfo_t) == sl_FsRead(fhandle, 0, (unsigned char *)&sBootInfo, sizeof(sBootInfo_t)));
                sl_FsClose(fhandle, 0, 0, 0);
#endif
                // open the boot info file for writing
                ASSERT (sl_FsOpen((unsigned char *)IMG_BOOT_INFO, FS_MODE_OPEN_WRITE, NULL, &fhandle) == 0);
#ifdef DEBUG
            }
            else {
                // the boot info file doesn't exist yet
                _u32 BootInfoCreateFlag  = _FS_FILE_OPEN_FLAG_COMMIT | _FS_FILE_PUBLIC_WRITE | _FS_FILE_PUBLIC_READ;
                ASSERT (sl_FsOpen ((unsigned char *)IMG_BOOT_INFO, FS_MODE_OPEN_CREATE((2 * sizeof(sBootInfo_t)),
                                   BootInfoCreateFlag), NULL, &fhandle) == 0);
            }
#endif

            // save the new boot info
#ifdef WIPY
            sBootInfo.PrevImg = sBootInfo.ActiveImg;
            if (sBootInfo.ActiveImg == IMG_ACT_UPDATE1) {
                sBootInfo.ActiveImg = IMG_ACT_UPDATE2;
            } else {
                sBootInfo.ActiveImg = IMG_ACT_UPDATE1;
            }
// the launchxl doesn't have enough flash space for 2 user updates
#else
            sBootInfo.PrevImg = IMG_ACT_FACTORY;
            sBootInfo.ActiveImg = IMG_ACT_UPDATE1;
#endif
            sBootInfo.Status = IMG_STATUS_CHECK;
            ASSERT (sizeof(sBootInfo_t) == sl_FsWrite(fhandle, 0, (unsigned char *)&sBootInfo, sizeof(sBootInfo_t)));
            sl_FsClose(fhandle, 0, 0, 0);
        }
        sl_LockObjUnlock (&wlan_LockObj);
        updater_data.fhandle = -1;
    }
    sl_LockObjUnlock (&updater_LockObj);
}
static s32_t failfs_read(spiffs *fs, u32_t addr, u32_t size, u8_t *dst) {
  struct mount_info *m = (struct mount_info *) fs->user_data;
  _i32 r;
  DBG(("failfs_read %d @ %d, cidx %u # %llu, fh %d, valid %d, rw %d",
       (int) size, (int) addr, m->cidx, m->seq, (int) m->fh, m->valid, m->rw));
  if (!m->valid) return SPIFFS_ERR_NOT_READABLE;
  do {
    if (m->fh < 0) {
      _u8 fname[MAX_FS_CONTAINER_FNAME_LEN];
      fs_container_fname(m->cpfx, m->cidx, fname);
      r = sl_FsOpen(fname, FS_MODE_OPEN_READ, NULL, &m->fh);
      DBG(("fopen %d", (int) r));
      if (r < 0) return SPIFFS_ERR_NOT_READABLE;
    }
    r = sl_FsRead(m->fh, addr, dst, size);
    DBG(("read %d", (int) r));
    if (r == SL_FS_ERR_INVALID_HANDLE) {
      /*
       * This happens when SimpleLink is reinitialized - all file handles are
       * invalidated. SL has to be reinitialized to e.g. configure WiFi.
       */
      m->fh = -1;
    }
  } while (m->fh < 0);
  return (r == size) ? SPIFFS_OK : SPIFFS_ERR_NOT_READABLE;
}
Пример #5
0
static int prepare_to_write(struct mgos_upd_hal_ctx *ctx,
                            const struct mgos_upd_file_info *fi,
                            const char *fname, uint32_t falloc,
                            struct json_token *part) {
  struct json_token expected_sha1 = JSON_INVALID_TOKEN;
  json_scanf(part->ptr, part->len, "{cs_sha1: %T}", &expected_sha1);
  if (verify_checksum(fname, fi->size, &expected_sha1)) {
    LOG(LL_INFO,
        ("Digest matched for %s %u (%.*s)", fname, (unsigned int) fi->size,
         (int) expected_sha1.len, expected_sha1.ptr));
    return 0;
  }
  LOG(LL_INFO, ("Storing %s %u -> %s %u (%.*s)", fi->name,
                (unsigned int) fi->size, fname, (unsigned int) falloc,
                (int) expected_sha1.len, expected_sha1.ptr));
  ctx->cur_fn = (const _u8 *) fname;
  sl_FsDel(ctx->cur_fn, 0);
  _i32 r = sl_FsOpen(ctx->cur_fn, FS_MODE_OPEN_CREATE(falloc, 0), NULL,
                     &ctx->cur_fh);
  if (r < 0) {
    ctx->status_msg = "Failed to create file";
    return r;
  }
  return 1;
}
Пример #6
0
//*****************************************************************************
//
//! \brief    This funtion:
//!             - opens the user file for reading
//!             - reads the data into application's 'DYNAMIC LIB' section
//!             - closes the user file
//!
//!  \param[in] p_library_name : Library's name to be loaded
//!
//!  \return 0: Success, -ve: Failure
//
//*****************************************************************************
static signed long load_library(const unsigned char *p_library_name)
{
    unsigned char *p_dynamic_lib_section = NULL;
    signed long file_handle = -1;
    unsigned long token = 0;
    signed long ret_val = -1;

    p_dynamic_lib_section = (unsigned char *)START_OF_DYNAMIC_LIB_SECTION;

    // Erase contents @ START_OF_DYNAMIC_LIB_SECTION 
    memset(p_dynamic_lib_section, '\0', TOTAL_SIZE_OF_DYNAMIC_LIB_SECTION);

    // Open the library 
    ret_val = sl_FsOpen((unsigned char *)p_library_name, FS_MODE_OPEN_READ,\
                            &token, &file_handle);
    if(ret_val < 0)
    {
        sl_FsClose(file_handle, 0, 0, 0);
        ASSERT_ON_ERROR(ret_val);
    }

    // Load the contents @ START_OF_DYNAMIC_LIB_SECTION 
    ret_val = sl_FsRead(file_handle, OFFSET_TO_DYNAMIC_LIB_SECTION,\
                        p_dynamic_lib_section,  TOTAL_SIZE_OF_DYNAMIC_LIB_SECTION);
    if ((ret_val < 0))
    {
        sl_FsClose(file_handle, 0, 0, 0);
        ASSERT_ON_ERROR(ret_val);
    }

    /* The first few bytes in this section has the function-table */
    gp_ftable = (s_fptr *)p_dynamic_lib_section;
    if((NULL == gp_ftable->p_add) ||
        (NULL == gp_ftable->p_sub) ||
         (NULL == gp_ftable->p_init) ||
          (NULL == gp_ftable->p_display))
    {
        /* Not all required functions are defined by the library - Assert */
    	ASSERT_ON_ERROR(-1);
    }

    /* Call functions of the library that was loaded dynamically */

    /** Registering the wrapper-functions w/ the library
      * There is no way for the libraries (that were loaded dynamically) to know
      * the address of functions (and other global variables) defined in ‘loader’.
      * Hence, to allow these library functions to access ‘loader’s’ functions
      * (and other global variables), ‘loader shall have all such functions
      * wrapped, and the address of the wrapper function(s) shall be registered
      * with the library
      */
    gp_ftable->p_init(&wptr_table);

    sl_FsClose(file_handle, 0, 0, 0);
    return 0;
}
Пример #7
0
int VerifyFile(const char *fileToVerify, const char *fileWithSHAHash) {
	unsigned long sToken = 0;
	long sfileHandle = -1;
	uint8_t firstHash[20];
	uint8_t secoundHash[21];
	long retVal;
	memset(firstHash, 0, sizeof(firstHash));
	memset(secoundHash, 0, sizeof(secoundHash));

	// get hash of file to verify
	if (ComputeSHA(fileToVerify, firstHash) < 0) {
		UART_PRINT("Error computing SHA1SUM of %s\r\n", fileToVerify);
		return -1;
	}

	// open the source file for reading
	retVal = sl_FsOpen((unsigned char *) fileWithSHAHash, FS_MODE_OPEN_READ, &sToken, &sfileHandle);
	if (retVal < 0) {
		UART_PRINT("Error during opening the source file %s\r\n", fileWithSHAHash);
		return -1;
	}

	// transform the hash from file with sha hash to byte values. The Sha1Sum is decoded in ascii chars
	unsigned int i;
	for (i = 0; i < sizeof(firstHash); i++) {
		retVal = sl_FsRead(sfileHandle, i * 2, (unsigned char *) &secoundHash[i], 2);
		if (retVal < 0) {
			// Error close the file and delete the temporary file
			retVal = sl_FsClose(sfileHandle, 0, 0, 0);
			UART_PRINT("Error during reading the file\r\n");
			return -1;
		}
		uint8_t tempValue;
		if (secoundHash[i] > '9') tempValue = (secoundHash[i] - 'a' + 10) << 4;
		else tempValue = (secoundHash[i] - '0') << 4;

		if (secoundHash[i + 1] > '9') tempValue += (secoundHash[i + 1] - 'a' + 10);
		else tempValue += (secoundHash[i + 1] - '0');
		secoundHash[i] = tempValue;
	}

	// Close the opened files
	retVal = sl_FsClose(sfileHandle, 0, 0, 0);
	if (retVal < 0) {
		// Error close the file and delete the temporary file
		UART_PRINT("Error during close the file\r\n");
		return -1;
	}

	if (memcmp(secoundHash, firstHash, sizeof(firstHash)) != 0) {
		UART_PRINT("\r\nHash-Sums are different\r\n");
		return -1;
	}
	return 0;
}
Пример #8
0
_i32 sl_extlib_FlcOpenFile(_u8 *file_name, _i32 file_size, _u32 *ulToken, _i32 *lFileHandle, _i32 open_flags)
{
	char uclocalFilename[100];

	if(open_flags == _FS_MODE_OPEN_READ)
	{
		return sl_FsOpen((_u8 *)file_name,
				_FS_MODE_OPEN_READ, ulToken, lFileHandle);
	}
	else
	{
		/* MCU image name should be changed */
		if(strstr((char *)file_name, "/sys/mcuimgA") != NULL)
		{
			switch(_McuImageGetNewIndex())
			{
			case IMG_ACT_USER1:
				strcpy(uclocalFilename,IMG_USER_1);
				break;

			case IMG_ACT_USER2:
				strcpy(uclocalFilename,IMG_USER_2);
				break;
			}

			/* make sure that the file is not opened as
			fail-safe since it might fill the entire SFLASH and
	      		it is not required for the MCU image */

			open_flags &= ~_FS_FILE_OPEN_FLAG_COMMIT;
			Report("sl_extlib_FlcOpenFile: MCU image"
					"name converted to %s \r\n", uclocalFilename);
		}
		else
		{
			strcpy(uclocalFilename,(char *)file_name);
		}
		return sl_FsOpen((_u8 *)uclocalFilename,
				FS_MODE_OPEN_CREATE(file_size, open_flags),
				ulToken, lFileHandle);
	}
}
Пример #9
0
//*****************************************************************************
//! Load the proper image based on the information from the boot info
//! and launch it.
//*****************************************************************************
static void bootmgr_image_loader(sBootInfo_t *psBootInfo) {
    _i32 fhandle;
    _u8 *image;

    // search for the active image
    switch (psBootInfo->ActiveImg) {
    case IMG_ACT_UPDATE1:
        image = (unsigned char *)IMG_UPDATE1;
        break;
    case IMG_ACT_UPDATE2:
        image = (unsigned char *)IMG_UPDATE2;
        break;
    default:
        image = (unsigned char *)IMG_FACTORY;
        break;
    }

    // do we have a new image that needs to be verified?
    if ((psBootInfo->ActiveImg != IMG_ACT_FACTORY) && (psBootInfo->Status == IMG_STATUS_CHECK)) {
        if (!bootmgr_verify(image)) {
            // verification failed, delete the broken file
            sl_FsDel(image, 0);
            // switch to the previous image
            psBootInfo->ActiveImg = psBootInfo->PrevImg;
            psBootInfo->PrevImg = IMG_ACT_FACTORY;
        }
        // in any case, change the status to "READY"
        psBootInfo->Status = IMG_STATUS_READY;
        // write the new boot info
        if (!sl_FsOpen((unsigned char *)IMG_BOOT_INFO, FS_MODE_OPEN_WRITE, NULL, &fhandle)) {
            sl_FsWrite(fhandle, 0, (unsigned char *)psBootInfo, sizeof(sBootInfo_t));
            // close the file
            sl_FsClose(fhandle, 0, 0, 0);
        }
    }

    // this one might modify the boot info hence it MUST be called after
    // bootmgr_verify! (so that the changes are not saved to flash)
    wait_for_safe_boot(psBootInfo);

    // select the active image again, since it might have changed
    switch (psBootInfo->ActiveImg) {
    case IMG_ACT_UPDATE1:
        image = (unsigned char *)IMG_UPDATE1;
        break;
    case IMG_ACT_UPDATE2:
        image = (unsigned char *)IMG_UPDATE2;
        break;
    default:
        image = (unsigned char *)IMG_FACTORY;
        break;
    }
    bootmgr_load_and_execute(image);
}
static _i32 fs_create_container(int cidx, _u32 fs_size) {
  _i32 fh = -1;
  const _u8 *fname = container_fname(cidx);
  _u32 fsize = FS_CONTAINER_SIZE(fs_size);
  int r = sl_FsDel(fname, 0);
  dprintf(("del %s -> %d\n", fname, r));
  r = sl_FsOpen(fname, FS_MODE_OPEN_CREATE(fsize, 0), NULL, &fh);
  dprintf(("open %s %d -> %d %d\n", fname, (int) fsize, (int) r, (int) fh));
  if (r != 0) return r;
  return fh;
}
Пример #11
0
//*****************************************************************************
//
//!  This funtion includes the following steps:
//!    -open the user file for reading
//!    -read the data and compare with the stored buffer
//!    -close the user file
//!
//!  /param[in] ulToken : file token
//!  /param[in] lFileHandle : file handle
//!
//!  /return 0: success, -ve:failure
//
//*****************************************************************************
long ReadFileFromDevice(unsigned long ulToken, long lFileHandle)
{
    long lRetVal = -1;
    int iLoopCnt = 0;

    //
    // open a user file for reading
    //
    lRetVal = sl_FsOpen((unsigned char *)USER_FILE_NAME,
                        FS_MODE_OPEN_READ,
                        &ulToken,
                        &lFileHandle);
    if(lRetVal < 0)
    {
        lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);
        ASSERT_ON_ERROR(FILE_OPEN_READ_FAILED);
    }

    //
    // read the data and compare with the stored buffer
    //
    for (iLoopCnt = 0;
            iLoopCnt < (SL_MAX_FILE_SIZE / sizeof(gaucOldMacDonald));
            iLoopCnt++)
    {
        lRetVal = sl_FsRead(lFileHandle,
                    (unsigned int)(iLoopCnt * sizeof(gaucOldMacDonald)),
                     gaucCmpBuf, sizeof(gaucOldMacDonald));
        if ((lRetVal < 0) || (lRetVal != sizeof(gaucOldMacDonald)))
        {
            lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);
            ASSERT_ON_ERROR(FILE_READ_FAILED);
        }

        lRetVal = memcmp(gaucOldMacDonald,
                         gaucCmpBuf,
                         sizeof(gaucOldMacDonald));
        if (lRetVal != 0)
        {
            ASSERT_ON_ERROR(FILE_NOT_MATCHED);
        }
    }

    //
    // close the user file
    //
    lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);
    if (SL_RET_CODE_OK != lRetVal)
    {
        ASSERT_ON_ERROR(FILE_CLOSE_ERROR);
    }

    return SUCCESS;
}
Пример #12
0
int fs_slfs_open(const char *pathname, int flags, mode_t mode) {
  int fd;
  for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) {
    if (s_sl_fds[fd].fh <= 0) break;
  }
  if (fd >= MAX_OPEN_SLFS_FILES) return set_errno(ENOMEM);
  struct sl_fd_info *fi = &s_sl_fds[fd];

  _u32 am = 0;
  fi->size = (size_t) -1;
  if (pathname[0] == '/') pathname++;
  int rw = (flags & 3);
  if (rw == O_RDONLY) {
    SlFsFileInfo_t sl_fi;
    _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
    if (r == SL_FS_OK) {
      fi->size = sl_fi.FileLen;
    }
    am = FS_MODE_OPEN_READ;
  } else {
    if (!(flags & O_TRUNC) || (flags & O_APPEND)) {
      // FailFS files cannot be opened for append and will be truncated
      // when opened for write.
      return set_errno(ENOTSUP);
    }
    if (flags & O_CREAT) {
      size_t i, size = FS_SLFS_MAX_FILE_SIZE;
      for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
        if (s_sl_file_size_hints[i].name != NULL &&
            strcmp(s_sl_file_size_hints[i].name, pathname) == 0) {
          size = s_sl_file_size_hints[i].size;
          free(s_sl_file_size_hints[i].name);
          s_sl_file_size_hints[i].name = NULL;
          break;
        }
      }
      DBG(("creating %s with max size %d", pathname, (int) size));
      am = FS_MODE_OPEN_CREATE(size, 0);
    } else {
      am = FS_MODE_OPEN_WRITE;
    }
  }
  _i32 r = sl_FsOpen((_u8 *) pathname, am, NULL, &fi->fh);
  DBG(("sl_FsOpen(%s, 0x%x) = %d, %d", pathname, (int) am, (int) r,
       (int) fi->fh));
  if (r == SL_FS_OK) {
    fi->pos = 0;
    r = fd;
  } else {
    fi->fh = -1;
    r = set_errno(sl_fs_to_errno(r));
  }
  return r;
}
_i32 fs_create_container(const char *cpfx, int cidx, _u32 fs_size) {
  _i32 fh = -1;
  _u8 fname[MAX_FS_CONTAINER_FNAME_LEN];
  _u32 fsize = FS_CONTAINER_SIZE(fs_size);
  fs_container_fname(cpfx, cidx, fname);
  int r = sl_FsDel(fname, 0);
  DBG(("del %s -> %d", fname, r));
  r = sl_FsOpen(fname, FS_MODE_OPEN_CREATE(fsize, 0), NULL, &fh);
  LOG((r == 0 ? LL_DEBUG : LL_ERROR),
      ("open %s %d -> %d %d", fname, (int) fsize, (int) r, (int) fh));
  if (r != 0) return r;
  return fh;
}
short loadClientState(ParseClientInternal *parseClient) {
    snprintf(clientStateFileName, CLIENT_STATE_FILENAME_LEN, CLIENT_STATE_FILENAME, parseClient->applicationId);

    long clientStateFile;

#ifdef CLIENT_DEBUG
    DEBUG_PRINT("[Parse] Loading client state\r\n");
#endif /* CLIENT_DEBUG */

    short status = sl_FsOpen((unsigned char *)clientStateFileName, FS_MODE_OPEN_READ, NULL, &clientStateFile);
    if (status < 0) {
        sl_FsClose(clientStateFile, 0, 0, 0);
        return status;
    }

    long readOffset = 0;
    status = sl_FsRead(clientStateFile, readOffset, (unsigned char *)parseClient->installationId, sizeof(parseClient->installationId));
    if (status < 0) {
        sl_FsClose(clientStateFile, 0, 0, 0);
        return status;
    }
#ifdef CLIENT_DEBUG
    DEBUG_PRINT("[Parse] Installation Id: %s\r\n", parseClient->installationId);
#endif /* CLIENT_DEBUG */

    readOffset = readOffset + status;
    status = sl_FsRead(clientStateFile, readOffset, (unsigned char *)parseClient->sessionToken, sizeof(parseClient->sessionToken));
    if (status < 0) {
        sl_FsClose(clientStateFile, 0, 0, 0);
        return status;
    }
#ifdef CLIENT_DEBUG
    DEBUG_PRINT("[Parse] Session token: %s\r\n", parseClient->sessionToken);
#endif /* CLIENT_DEBUG */

    readOffset = readOffset + status;
    status = sl_FsRead(clientStateFile, readOffset, (unsigned char *)parseClient->lastPushHash, sizeof(parseClient->lastPushHash));
    if (status < 0) {
        sl_FsClose(clientStateFile, 0, 0, 0);
        return status;
    }
#ifdef CLIENT_DEBUG
    DEBUG_PRINT("[Parse] Last push hash: %s\r\n", parseClient->lastPushHash);
#endif /* CLIENT_DEBUG */

    sl_FsClose(clientStateFile, 0, 0, 0);

    return status;
}
Пример #15
0
static bool sflash_access (_u32 mode, _i32 (* sl_FsFunction)(_i32 FileHdl, _u32 Offset, _u8* pData, _u32 Len)) {
    _i32 fileHandle;
    bool retval = false;

    // wlan must be enabled in order to access the serial flash
    sl_LockObjLock (&wlan_LockObj, SL_OS_WAIT_FOREVER);

    if (0 == sl_FsOpen(sflash_block_name, mode, NULL, &fileHandle)) {
        if (SFLASH_BLOCK_SIZE == sl_FsFunction (fileHandle, 0, sflash_block_cache, SFLASH_BLOCK_SIZE)) {
            retval = true;
        }
        sl_FsClose (fileHandle, NULL, NULL, 0);
    }
    sl_LockObjUnlock (&wlan_LockObj);
    return retval;
}
static s32_t failfs_read(u32_t addr, u32_t size, u8_t *dst) {
  struct mount_info *m = &s_fsm;
  _i32 r;
  dprintf(("failfs_read %d @ %d, cidx %u # %llu, fh %d, valid %d, rw %d\n",
           (int) size, (int) addr, m->cidx, m->seq, (int) m->fh, m->valid,
           m->rw));
  if (!m->valid) return SPIFFS_ERR_NOT_READABLE;
  if (m->fh < 0) {
    r = sl_FsOpen(container_fname(m->cidx), FS_MODE_OPEN_READ, NULL, &m->fh);
    dprintf(("fopen %d\n", (int) r));
    if (r < 0) return SPIFFS_ERR_NOT_READABLE;
  }
  r = sl_FsRead(m->fh, addr, dst, size);
  dprintf(("read %d\n", (int) r));
  return (r == size) ? SPIFFS_OK : SPIFFS_ERR_NOT_READABLE;
}
Пример #17
0
//*****************************************************************************
//! Verifies the integrity of the new application binary
//*****************************************************************************
static bool bootmgr_verify (_u8 *image) {
    SlFsFileInfo_t FsFileInfo;
    _u32 reqlen, offset = 0;
    _i32 fHandle;

    // open the file for reading
    if (0 == sl_FsOpen(image, FS_MODE_OPEN_READ, NULL, &fHandle)) {
        // get the file size
        sl_FsGetInfo(image, 0, &FsFileInfo);

        if (FsFileInfo.FileLen > BOOTMGR_HASH_SIZE) {
            FsFileInfo.FileLen -= BOOTMGR_HASH_SIZE;
            CRYPTOHASH_SHAMD5Start(BOOTMGR_HASH_ALGO, FsFileInfo.FileLen);
            do {
                if ((FsFileInfo.FileLen - offset) > BOOTMGR_BUFF_SIZE) {
                    reqlen = BOOTMGR_BUFF_SIZE;
                }
                else {
                    reqlen = FsFileInfo.FileLen - offset;
                }

                offset += sl_FsRead(fHandle, offset, bootmgr_file_buf, reqlen);
                CRYPTOHASH_SHAMD5Update(bootmgr_file_buf, reqlen);
            } while (offset < FsFileInfo.FileLen);

            CRYPTOHASH_SHAMD5Read (bootmgr_file_buf);

            // convert the resulting hash to hex
            for (_u32 i = 0; i < (BOOTMGR_HASH_SIZE / 2); i++) {
                snprintf ((char *)&bootmgr_hash_buf[(i * 2)], 3, "%02x", bootmgr_file_buf[i]);
            }

            // read the hash from the file and close it
            sl_FsRead(fHandle, offset, bootmgr_file_buf, BOOTMGR_HASH_SIZE);
            sl_FsClose (fHandle, NULL, NULL, 0);
            bootmgr_file_buf[BOOTMGR_HASH_SIZE] = '\0';
            // compare both hashes
            if (!strcmp((const char *)bootmgr_hash_buf, (const char *)bootmgr_file_buf)) {
                // it's a match
                return true;
            }
        }
        // close the file
        sl_FsClose(fHandle, NULL, NULL, 0);
    }
    return false;
}
Пример #18
0
bool updater_start (void) {
    _u32 AccessModeAndMaxSize = FS_MODE_OPEN_WRITE;
    SlFsFileInfo_t FsFileInfo;
    bool result = false;

    sl_LockObjLock (&wlan_LockObj, SL_OS_WAIT_FOREVER);
    if (0 != sl_FsGetInfo((_u8 *)updater_data.path, 0, &FsFileInfo)) {
        // file doesn't exist, create it
        AccessModeAndMaxSize = FS_MODE_OPEN_CREATE(updater_data.fsize, 0);
    }
    if (!sl_FsOpen((_u8 *)updater_data.path, AccessModeAndMaxSize, NULL, &updater_data.fhandle)) {
        updater_data.foffset = 0;
        result = true;
    }
    sl_LockObjUnlock (&wlan_LockObj);
    return result;
}
Пример #19
0
static int read_file(const char *fn, int offset, int len, read_file_cb_t cb,
                     void *arg) {
  _i32 fh;
  int r = sl_FsOpen((const _u8 *) fn, FS_MODE_OPEN_READ, NULL, &fh);
  if (r < 0) return r;
  while (len > 0) {
    _u8 buf[512];
    int to_read = MIN(len, sizeof(buf));
    r = sl_FsRead(fh, offset, buf, to_read);
    if (r != to_read) break;
    if (cb(buf, to_read, arg) != to_read) break;
    offset += to_read;
    len -= to_read;
  }
  sl_FsClose(fh, NULL, NULL, 0);
  return (len == 0 ? 0 : -1);
}
Пример #20
0
DRESULT sflash_disk_init (void) {
    _i32 fileHandle;
    SlFsFileInfo_t FsFileInfo;

    if (!sflash_init_done) {
        // Allocate space for the block cache
        ASSERT ((sflash_block_cache = mem_Malloc(SFLASH_BLOCK_SIZE)) != NULL);
        sflash_init_done = true;
        sflash_prblock = UINT32_MAX;
        sflash_cache_is_dirty = false;

        // In order too speed up booting, check the last block, if exists, then
        // it means that the file system has been already created
        print_block_name (SFLASH_BLOCK_COUNT - 1);
        sl_LockObjLock (&wlan_LockObj, SL_OS_WAIT_FOREVER);
        if (!sl_FsGetInfo(sflash_block_name, 0, &FsFileInfo)) {
            sl_LockObjUnlock (&wlan_LockObj);
            return RES_OK;
        }
        sl_LockObjUnlock (&wlan_LockObj);

        // Proceed to format the memory
        for (int i = 0; i < SFLASH_BLOCK_COUNT; i++) {
            print_block_name (i);
            sl_LockObjLock (&wlan_LockObj, SL_OS_WAIT_FOREVER);
            // Create the block file if it doesn't exist
            if (sl_FsGetInfo(sflash_block_name, 0, &FsFileInfo) != 0) {
                if (!sl_FsOpen(sflash_block_name, FS_MODE_OPEN_CREATE(SFLASH_BLOCK_SIZE, 0), NULL, &fileHandle)) {
                    sl_FsClose(fileHandle, NULL, NULL, 0);
                    sl_LockObjUnlock (&wlan_LockObj);
                    memset(sflash_block_cache, 0xFF, SFLASH_BLOCK_SIZE);
                    if (!sflash_access(FS_MODE_OPEN_WRITE, sl_FsWrite)) {
                        return RES_ERROR;
                    }
                }
                else {
                    // Unexpected failure while creating the file
                    sl_LockObjUnlock (&wlan_LockObj);
                    return RES_ERROR;
                }
            }
            sl_LockObjUnlock (&wlan_LockObj);
        }
    }
    return RES_OK;
}
Пример #21
0
static _i32 _ReadBootInfo(sBootInfo_t *psBootInfo)
{
    _i32 lFileHandle;
    _u32 ulToken;
    _i32 status = -1;

    if( 0 == sl_FsOpen((_u8 *)IMG_BOOT_INFO, FS_MODE_OPEN_READ, &ulToken, &lFileHandle) )
    {
        if( 0 < sl_FsRead(lFileHandle, 0, (_u8 *)psBootInfo, sizeof(sBootInfo_t)) )
        {
            status = 0;
            Report("ReadBootInfo: ucActiveImg=%d, ulImgStatus=0x%x\n\r", psBootInfo->ucActiveImg, psBootInfo->ulImgStatus);
        }
        sl_FsClose(lFileHandle, 0, 0, 0);
    }

    return status;
}
Пример #22
0
//*****************************************************************************
//! Loads the application from sFlash and executes
//*****************************************************************************
static void bootmgr_load_and_execute (_u8 *image) {
    SlFsFileInfo_t pFsFileInfo;
    _i32 fhandle;
    // open the application binary
    if (!sl_FsOpen(image, FS_MODE_OPEN_READ, NULL, &fhandle)) {
        // get the file size
        if (!sl_FsGetInfo(image, 0, &pFsFileInfo)) {
            // read the application into SRAM
            if (pFsFileInfo.FileLen == sl_FsRead(fhandle, 0, (unsigned char *)APP_IMG_SRAM_OFFSET, pFsFileInfo.FileLen)) {
                // close the file
                sl_FsClose(fhandle, 0, 0, 0);
                // stop the network services
                sl_Stop(SL_STOP_TIMEOUT);
                // execute the application
                bootmgr_run_app(APP_IMG_SRAM_OFFSET);
            }
        }
    }
}
Пример #23
0
int load_image(const char *fn, _u8 *dst) {
  _i32 fh;
  SlFsFileInfo_t fi;
  _i32 r = sl_FsGetInfo((const _u8 *) fn, 0, &fi);
  dbg_putc(r == 0 ? '+' : '-');
  if (r != 0) return r;
  {
    char buf[20];
    __utoa(fi.FileLen, buf, 10);
    dbg_puts(buf);
  }
  r = sl_FsOpen((const _u8 *) fn, FS_MODE_OPEN_READ, NULL, &fh);
  dbg_putc(r == 0 ? '+' : '-');
  if (r != 0) return r;
  r = sl_FsRead(fh, 0, dst, fi.FileLen);
  if (r != fi.FileLen) return r;
  sl_FsClose(fh, NULL, NULL, 0);
  return 0;
}
static int fs_get_info(const char *cpfx, int cidx,
                       struct fs_container_info *info) {
  _u8 fname[MAX_FS_CONTAINER_FNAME_LEN];
  union fs_container_meta meta;
  SlFsFileInfo_t fi;
  _i32 fh;
  _u32 offset;
  fs_container_fname(cpfx, cidx, fname);
  _i32 r = sl_FsGetInfo(fname, 0, &fi);
  DBG(("finfo %s %d %d %d", fname, (int) r, (int) fi.FileLen,
       (int) fi.AllocatedLen));
  if (r != 0) return r;
  if (fi.AllocatedLen < sizeof(meta)) return -200;
  r = sl_FsOpen(fname, FS_MODE_OPEN_READ, NULL, &fh);
  DBG(("fopen %s %d", fname, (int) r));
  if (r != 0) return r;

  offset = fi.FileLen - sizeof(meta);
  r = sl_FsRead(fh, offset, (_u8 *) &meta, sizeof(meta));
  DBG(("read meta @ %d: %d", (int) offset, (int) r));

  if (r != sizeof(meta)) {
    r = -201;
    goto out_close;
  }
  if (meta.info.seq > FS_INITIAL_SEQ || meta.info.seq == 0 ||
      meta.info.fs_size == ~0UL) {
    r = -202;
    goto out_close;
  }

  memcpy(info, &meta.info, sizeof(*info));
  DBG(("found fs: %llu %d %d %d %d", info->seq, (int) info->fs_size,
       (int) info->fs_block_size, (int) info->fs_page_size,
       (int) info->fs_erase_size));
  r = 0;

out_close:
  sl_FsClose(fh, NULL, NULL, 0);
  return r;
}
Пример #25
0
//*****************************************************************************
//! Load the proper image based on information from boot info and executes it.
//*****************************************************************************
static void bootmgr_image_loader(sBootInfo_t *psBootInfo) {
    _i32 fhandle;
    if (safe_mode_boot()) {
         _u32 count = 0;
         while ((BOOTMGR_SAFE_MODE_ENTER_TOOGLE_MS * count++) < BOOTMGR_SAFE_MODE_ENTER_MS) {
             // toogle the led
             MAP_GPIOPinWrite(MICROPY_SYS_LED_PORT, MICROPY_SYS_LED_PORT_PIN, ~MAP_GPIOPinRead(MICROPY_SYS_LED_PORT, MICROPY_SYS_LED_PORT_PIN));
             UtilsDelay(UTILS_DELAY_US_TO_COUNT(BOOTMGR_SAFE_MODE_ENTER_TOOGLE_MS * 1000));
         }
         psBootInfo->ActiveImg = IMG_ACT_FACTORY;
         // turn the led off
         MAP_GPIOPinWrite(MICROPY_SYS_LED_PORT, MICROPY_SYS_LED_PORT_PIN, 0);
         // request a safe boot to the application
         PRCMRequestSafeBoot();
    }
    // do we have a new update image that needs to be verified?
    else if ((psBootInfo->ActiveImg == IMG_ACT_UPDATE) && (psBootInfo->Status == IMG_STATUS_CHECK)) {
        if (!bootmgr_verify()) {
            // delete the corrupted file
            sl_FsDel((_u8 *)IMG_UPDATE, 0);
            // switch to the factory image
            psBootInfo->ActiveImg = IMG_ACT_FACTORY;
        }
        // in any case, set the status as "READY"
        psBootInfo->Status = IMG_STATUS_READY;
        // write the new boot info
        if (!sl_FsOpen((unsigned char *)IMG_BOOT_INFO, FS_MODE_OPEN_WRITE, NULL, &fhandle)) {
            sl_FsWrite(fhandle, 0, (unsigned char *)psBootInfo, sizeof(sBootInfo_t));
            // close the file
            sl_FsClose(fhandle, 0, 0, 0);
        }
    }

    // now boot the active image
    if (IMG_ACT_UPDATE == psBootInfo->ActiveImg) {
        bootmgr_load_and_execute((unsigned char *)IMG_UPDATE);
    }
    else {
        bootmgr_load_and_execute((unsigned char *)IMG_FACTORY);
    }
}
Пример #26
0
int32_t SLFS::open(const uint8_t *filename, int32_t mode)
{
    SlFsFileInfo_t finfo;

    if (filehandle) {
        retval = SLFS_LIB_ERR_FILE_ALREADY_OPEN;
        return retval;
    }

    retval = sl_FsOpen((unsigned char*)filename, mode, NULL, &filehandle);
    if (retval != SL_FS_OK)
        return retval;

    offset = 0;
    filesize = 0;
    if (mode == FS_MODE_OPEN_READ) {
        is_write = false;

        // Discover actual filesize
        retval = sl_FsGetInfo((unsigned char*)filename, 0, &finfo);
        if (retval != SL_FS_OK) {
            sl_FsClose(filehandle, NULL, NULL, 0);
            filehandle = 0;
            return retval;
        }
        filesize = finfo.FileLen;
    } else {
        is_write = true;

        // Discover maximum file size, store in 'filesize' so we know when to reject writes.
        retval = sl_FsGetInfo((unsigned char*)filename, 0, &finfo);
        if (retval != SL_FS_OK) {
            sl_FsClose(filehandle, NULL, NULL, 0);
            filehandle = 0;
            return retval;
        }
        filesize = finfo.AllocatedLen;
    }

    return retval;
}
Пример #27
0
bool updater_check_path (void *path) {
    sl_LockObjLock (&updater_LockObj, SL_OS_WAIT_FOREVER);
    if (!strcmp(UPDATER_IMG_PATH, path)) {
        updater_data.fsize = IMG_SIZE;
        updater_data.path = IMG_UPDATE1;
// the launchxl doesn't have enough flash space for 2 user update images
#ifdef WIPY
        // check which one should be the next active image
         _i32 fhandle;
        if (!sl_FsOpen((unsigned char *)IMG_BOOT_INFO, FS_MODE_OPEN_READ, NULL, &fhandle)) {
            ASSERT (sizeof(sBootInfo_t) == sl_FsRead(fhandle, 0, (unsigned char *)&sBootInfo, sizeof(sBootInfo_t)));
            sl_FsClose(fhandle, 0, 0, 0);
            // if we still have an image pending for verification, keep overwriting it
            if ((sBootInfo.Status == IMG_STATUS_CHECK && sBootInfo.ActiveImg == IMG_ACT_UPDATE2) ||
                 (sBootInfo.ActiveImg == IMG_ACT_UPDATE1 && sBootInfo.Status != IMG_STATUS_CHECK)) {
                updater_data.path = IMG_UPDATE2;
            }
        }
#endif
    } else if (!strcmp(UPDATER_SRVPACK_PATH, path)) {
        updater_data.path = IMG_SRVPACK;
        updater_data.fsize = SRVPACK_SIZE;
    } else if (!strcmp(UPDATER_SIGN_PATH, path)) {
        updater_data.path = SRVPACK_SIGN;
        updater_data.fsize = SIGN_SIZE;
    } else if (!strcmp(UPDATER_CA_PATH, path)) {
        updater_data.path = CA_FILE;
        updater_data.fsize = CA_KEY_SIZE;
    } else if (!strcmp(UPDATER_CERT_PATH, path)) {
        updater_data.path = CERT_FILE;
        updater_data.fsize = CA_KEY_SIZE;
    } else if (!strcmp(UPDATER_KEY_PATH, path)) {
        updater_data.path = KEY_FILE;
        updater_data.fsize = CA_KEY_SIZE;
    } else {
        sl_LockObjUnlock (&updater_LockObj);
        return false;
    }
    return true;
}
Пример #28
0
/**
 * Initialize HttpStatic module state for a new request, and identify the request
 * This function examines the specified resource string, and looks it up in the Flash Database.
 * If found, it commits to process this request by returning nonzero. Otherwise it returns zero.
 * @param uConnection The number of the connection. This value is guaranteed to satisfy: 0 <= uConnection < HTTP_CORE_MAX_CONNECTIONS
 * @param resource The resource part of the URL, as specified by the browser in the request, including any query string (and hash).
 *                 Note: The resource string exists ONLY during the call to this function. The string pointer should not be copied by this function.
 * @return nonzero if request is to be handled by this module. zero if not.
 */
int HttpStatic_InitRequest(UINT16 uConnection, struct HttpBlob resource)
{
	char *pcWWWFsDir = "www";
	memset(g_cFileName,'\0',40);

	if(resource.uLength ==1 && *(resource.pData)=='/')
	{
		strcpy(g_cFileName,"www/main.html");
	}
	else
	{	
		strcpy(g_cFileName,pcWWWFsDir);
		strncat(g_cFileName,(char*)resource.pData,resource.uLength);
	}

	if(sl_FsOpen((unsigned char*)g_cFileName,FS_MODE_OPEN_READ,NULL,&glFileHandle)<0)
		return 0;
	else
	{
		return 1;
	}
}
static int fs_get_info(int cidx, struct fs_info *info) {
  union fs_meta meta;
  SlFsFileInfo_t fi;
  _i32 fh;
  _u32 offset;
  _i32 r = sl_FsGetInfo(container_fname(cidx), 0, &fi);
  dprintf(("finfo %s %d %d %d\n", container_fname(cidx), (int) r,
           (int) fi.FileLen, (int) fi.AllocatedLen));
  if (r != 0) return r;
  if (fi.AllocatedLen < sizeof(meta)) return -200;
  r = sl_FsOpen(container_fname(cidx), FS_MODE_OPEN_READ, NULL, &fh);
  dprintf(("fopen %s %d\n", container_fname(cidx), (int) r));
  if (r != 0) return r;

  offset = fi.FileLen - sizeof(meta);
  r = sl_FsRead(fh, offset, (_u8 *) &meta, sizeof(meta));
  dprintf(("read meta @ %d: %d\n", (int) offset, (int) r));

  if (r != sizeof(meta)) {
    r = -201;
    goto out_close;
  }
  if (meta.info.seq > INITIAL_SEQ || meta.info.fs_size < 0) {
    r = -202;
    goto out_close;
  }

  memcpy(info, &meta.info, sizeof(*info));
  dprintf(("found fs: %llu %d %d %d\n", info->seq, (int) info->fs_size,
           (int) info->fs_block_size, (int) info->fs_page_size));
  r = 0;

out_close:
  sl_FsClose(fh, NULL, NULL, 0);
  return r;
}
Пример #30
0
/* Standard libc interface to TI SimpleLink FS. */

#if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS)

#include "common/platforms/simplelink/sl_fs_slfs.h"

#include <errno.h>

#if CS_PLATFORM == CS_P_CC3200
#include <inc/hw_types.h>
#endif

#include "common/cs_dbg.h"
#include "common/mg_mem.h"

#if SL_MAJOR_VERSION_NUM < 2
int slfs_open(const unsigned char *fname, uint32_t flags) {
  _i32 fh;
  _i32 r = sl_FsOpen(fname, flags, NULL /* token */, &fh);
  return (r < 0 ? r : fh);
}
#else /* SL_MAJOR_VERSION_NUM >= 2 */
int slfs_open(const unsigned char *fname, uint32_t flags) {
  return sl_FsOpen(fname, flags, NULL /* token */);
}