示例#1
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;
}
示例#2
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;
}
示例#3
0
文件: main.c 项目: gale320/cc3200
//*****************************************************************************
//
//!  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;
}
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);
}
示例#5
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);
}
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;
}
void fs_close_container(struct mount_info *m) {
  if (!m->valid || m->fh == -1) return;
  LOG(LL_DEBUG, ("fh %d", (int) m->fh));
  sl_FsClose(m->fh, NULL, NULL, 0);
  m->fh = -1;
  m->rw = 0;
}
示例#8
0
void mgos_upd_hal_ctx_free(struct mgos_upd_hal_ctx *ctx) {
  if (ctx == NULL) return;
  if (ctx->cur_fh >= 0) sl_FsClose(ctx->cur_fh, NULL, NULL, 0);
  if (ctx->cur_fn != NULL) sl_FsDel(ctx->cur_fn, 0);
  memset(ctx, 0, sizeof(*ctx));
  free(ctx);
}
static int fs_format(int cidx) {
  s32_t r;
  struct mount_info *m = &s_fsm;
  _u32 fsc_size = FS_CONTAINER_SIZE(FS_SIZE);
  dprintf(("formatting %d s=%u, cs=%d\n", cidx, FS_SIZE, (int) fsc_size));

  m->cidx = cidx;
  r = fs_create_container(cidx, FS_SIZE);
  if (r < 0) goto out;
  m->fh = r;
  m->valid = m->rw = m->formatting = 1;
  /* Touch a byte at the end to open a "hole". */
  r = sl_FsWrite(m->fh, fsc_size - 1, (_u8 *) "\xff", 1);
  dprintf(("write 1 @ %d %d\n", (int) (fsc_size - 1), (int) r));
  if (r != 1) goto out_close;

  /* There must be a mount attempt before format. It'll fail and that's ok. */
  r = fs_mount_spiffs(m, FS_SIZE, FS_BLOCK_SIZE, FS_PAGE_SIZE);
  dprintf(("mount: %d\n", (int) r));
  r = SPIFFS_format(&m->fs);
  dprintf(("format: %d\n", (int) r));
  if (r != SPIFFS_OK) goto out_close;

  m->seq = INITIAL_SEQ;
  r = fs_write_meta(m);

out_close:
  sl_FsClose(m->fh, NULL, NULL, 0);
out:
  m->fh = -1;
  m->valid = m->formatting = m->rw = 0;
  return r;
}
示例#10
0
int mgos_upd_file_end(struct mgos_upd_hal_ctx *ctx,
                      const struct mgos_upd_file_info *fi, struct mg_str tail) {
  int r = tail.len;
  assert(tail.len == 0);
  if (ctx->cur_fn == (_u8 *) ctx->fs_container_file) {
    if (!cc32xx_vfs_dev_slfs_container_write_meta(
            ctx->cur_fh, FS_INITIAL_SEQ, ctx->fs_size, ctx->fs_block_size,
            ctx->fs_page_size, ctx->fs_erase_size)) {
      ctx->status_msg = "Failed to write fs meta";
      r = -1;
    }
  }
  if (sl_FsClose(ctx->cur_fh, NULL, NULL, 0) != 0) {
    ctx->status_msg = "Close failed";
    r = -1;
  } else {
    struct json_token sha1 = JSON_INVALID_TOKEN;
    json_scanf(ctx->cur_part.ptr, ctx->cur_part.len, "{cs_sha1: %T}", &sha1);
    if (!verify_checksum((const char *) ctx->cur_fn, fi->size, &sha1)) {
      ctx->status_msg = "Checksum mismatch";
      r = -1;
    }
  }
  ctx->cur_fh = -1;
  ctx->cur_fn = NULL;
  return r;
}
void fs_close_container(struct mount_info *m) {
  if (!m->valid || !m->rw) return;
  dprintf(("closing fh %d\n", (int) m->fh));
  sl_FsClose(m->fh, NULL, NULL, 0);
  m->fh = -1;
  m->rw = 0;
}
示例#12
0
文件: main.c 项目: Ga-vin/micropython
//*****************************************************************************
//! 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;
}
示例#13
0
int fs_slfs_close(int fd) {
  struct sl_fd_info *fi = &s_sl_fds[fd];
  if (fi->fh <= 0) return set_errno(EBADF);
  _i32 r = sl_FsClose(fi->fh, NULL, NULL, 0);
  LOG(LL_DEBUG, ("sl_FsClose(%d) = %d", (int) fi->fh, (int) r));
  s_sl_fds[fd].fh = -1;
  return set_errno(sl_fs_to_errno(r));
}
示例#14
0
文件: flc.c 项目: yuch7/cc3200-MCU
_i32 sl_extlib_FlcCloseFile(_i32 fileHandle, _u8 *pCeritificateFileName,_u8 *pSignature ,_u32 SignatureLen)
{
    if (SignatureLen == 0)
    {
        pSignature = 0;
    }
    return sl_FsClose(fileHandle, pCeritificateFileName, pSignature, SignatureLen);
}
示例#15
0
文件: main.c 项目: Ga-vin/micropython
//*****************************************************************************
//! 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);
}
示例#16
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;
}
示例#17
0
int32_t SLFS::close(void)
{
    if (!filehandle) {
        retval = SLFS_LIB_ERR_FILE_NOT_OPEN;
        return retval;
    }
    
    offset = 0;
    filesize = 0;
    retval = sl_FsClose(filehandle, NULL, NULL, 0);
    filehandle = 0;
    is_write = false;

    return retval;
}
示例#18
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;
}
示例#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
文件: flc.c 项目: yuch7/cc3200-MCU
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
文件: main.c 项目: Ga-vin/micropython
//*****************************************************************************
//! 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
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;
}
示例#27
0
static void FileTest(void) {

	UART_PRINT("Hello World");

	int retVal = 0;
	long handle;
	unsigned long token;
	SlFsFileInfo_t tempInfo;

	//retVal = sl_FsOpen((unsigned char *)"/www/main.html", FS_MODE_OPEN_READ, &token, &handle);

	if (retVal == -1) {
		UART_PRINT("ERROR file open \n\r");
		return;
	}

	UART_PRINT("file open \n\r");

	retVal = sl_FsGetInfo((unsigned char *)&filename, token, &tempInfo);

	if (retVal == -1) {
		UART_PRINT("ERROR file info \n\r");
		return;
	}

	UART_PRINT("file info \n\r");

	UART_PRINT("file len: %d", tempInfo.FileLen);

	retVal = sl_FsClose(handle, NULL, NULL, 0);

	if (retVal == -1) {
		UART_PRINT("ERROR file close \n\r");
		return;
	}

	UART_PRINT("file close \n\r");
}
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;
}
示例#29
0
文件: main.c 项目: dlugaz/All
//****************************************************************************
//
//! \brief Obtain the file from the server
//!
//!  This function requests the file from the server and save it on serial flash.
//!  To request a different file for different user needs to modify the
//!  PREFIX_BUFFER macros.
//!
//! \param[in] cli - Instance of the HTTP connection
//!
//! \return         0 for success and negative for error
//
//****************************************************************************
static int GetData(HTTPCli_Handle cli)
{
    long          lRetVal = 0;
    long          fileHandle = -1;
    unsigned long Token = 0;
    int id;
    int len=0;
    bool moreFlag = 0;
    HTTPCli_Field fields[3] = {
                                {HTTPCli_FIELD_NAME_HOST, HOST_NAME},
                                {HTTPCli_FIELD_NAME_ACCEPT, "text/html, application/xhtml+xml, */*"},
                                {NULL, NULL}
                              };

    const char *ids[4] = {
                            HTTPCli_FIELD_NAME_CONTENT_LENGTH,
                            HTTPCli_FIELD_NAME_TRANSFER_ENCODING,
                            HTTPCli_FIELD_NAME_CONNECTION,
                            NULL
                         };


    UART_PRINT("Start downloading the file\r\n");

    // Set request fields
    HTTPCli_setRequestFields(cli, fields);

    memset(g_buff, 0, sizeof(g_buff));

    // Make HTTP 1.1 GET request
    lRetVal = HTTPCli_sendRequest(cli, HTTPCli_METHOD_GET, PREFIX_BUFFER, 0);
    if (lRetVal < 0)
    {
        // error
        ASSERT_ON_ERROR(TCP_SEND_ERROR);
    }

    // Test getResponseStatus: handle
    lRetVal = HTTPCli_getResponseStatus(cli);
    if (lRetVal != 200)
    {
        FlushHTTPResponse(cli);
        if(lRetVal == 404)
        {
            ASSERT_ON_ERROR(FILE_NOT_FOUND_ERROR);
        }
        ASSERT_ON_ERROR(INVALID_SERVER_RESPONSE);
    }

    HTTPCli_setResponseFields(cli, ids);

    // Read response headers
    while ((id = HTTPCli_getResponseField(cli, (char *)g_buff, sizeof(g_buff), &moreFlag)) 
               != HTTPCli_FIELD_ID_END)
    {

        if(id == 0)
        {
            UART_PRINT("Content length: %s\n\r", g_buff);
        }
        else if(id == 1)
        {
            if(!strncmp((const char *)g_buff, "chunked", sizeof("chunked")))
            {
                UART_PRINT("Chunked transfer encoding\n\r");
            }
        }
        else if(id == 2)
        {
            if(!strncmp((const char *)g_buff, "close", sizeof("close")))
            {
                ASSERT_ON_ERROR(FORMAT_NOT_SUPPORTED);
            }
        }

    }

    // Open file to save the downloaded file
    lRetVal = sl_FsOpen((_u8 *)FILE_NAME, FS_MODE_OPEN_WRITE, &Token, &fileHandle);
    if(lRetVal < 0)
    {
        // File Doesn't exit create a new of 40 KB file
        lRetVal = sl_FsOpen((unsigned char *)FILE_NAME, \
                           FS_MODE_OPEN_CREATE(SIZE_40K, \
                           _FS_FILE_OPEN_FLAG_COMMIT|_FS_FILE_PUBLIC_WRITE),
                           &Token, &fileHandle);
        ASSERT_ON_ERROR(lRetVal);

    }



    while(1)
    {
        len = HTTPCli_readResponseBody(cli, (char *)g_buff, sizeof(g_buff) - 1, &moreFlag);
        if(len < 0)
        {
            // Close file without saving
            lRetVal = sl_FsClose(fileHandle, 0, (unsigned char*) "A", 1);
            return lRetVal;
        }

        lRetVal = sl_FsWrite(fileHandle, bytesReceived,
                                (unsigned char *)g_buff, len);

        if(lRetVal < len)
        {
            UART_PRINT("Failed during writing the file, Error-code: %d\r\n", \
                         FILE_WRITE_ERROR);
            // Close file without saving
            lRetVal = sl_FsClose(fileHandle, 0, (unsigned char*) "A", 1);
            return lRetVal;
        }
        bytesReceived +=len;

        if ((len - 2) >= 0 && g_buff[len - 2] == '\r' && g_buff [len - 1] == '\n'){
            break;
        }

        if(!moreFlag)
        {
            break;
        }
    }

    //
    // If user file has checksum which can be used to verify the temporary
    // file then file should be verified
    // In case of invalid file (FILE_NAME) should be closed without saving to
    // recover the previous version of file
    //

    // Save and close file
    UART_PRINT("Total bytes received: %d\n\r", bytesReceived);
    lRetVal = sl_FsClose(fileHandle, 0, 0, 0);
    ASSERT_ON_ERROR(lRetVal);

    return SUCCESS;
}
示例#30
0
文件: main.c 项目: gale320/cc3200
//*****************************************************************************
//
//!  This funtion includes the following steps:
//!  -open a user file for writing
//!  -write "Old MacDonalds" child song 37 times to get just below a 64KB file
//!  -close the user file
//!
//!  /param[out] ulToken : file token
//!  /param[out] lFileHandle : file handle
//!
//!  /return  0:Success, -ve: failure
//
//*****************************************************************************
long WriteFileToDevice(unsigned long *ulToken, long *lFileHandle)
{
    long lRetVal = -1;
    int iLoopCnt = 0;

    //
    //  create a user file
    //
    lRetVal = sl_FsOpen((unsigned char *)USER_FILE_NAME,
                FS_MODE_OPEN_CREATE(65536, \
                          _FS_FILE_OPEN_FLAG_COMMIT|_FS_FILE_PUBLIC_WRITE),
                        ulToken,
                        lFileHandle);
    if(lRetVal < 0)
    {
        //
        // File may already be created
        //
        lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
        ASSERT_ON_ERROR(lRetVal);
    }
    else
    {
        //
        // close the user file
        //
        lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
        if (SL_RET_CODE_OK != lRetVal)
        {
            ASSERT_ON_ERROR(FILE_CLOSE_ERROR);
        }
    }
    
    //
    //  open a user file for writing
    //
    lRetVal = sl_FsOpen((unsigned char *)USER_FILE_NAME,
                        FS_MODE_OPEN_WRITE, 
                        ulToken,
                        lFileHandle);
    if(lRetVal < 0)
    {
        lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
        ASSERT_ON_ERROR(FILE_OPEN_WRITE_FAILED);
    }
    
    //
    // write "Old MacDonalds" child song as many times to get just below a 64KB file
    //
    for (iLoopCnt = 0; 
            iLoopCnt < (SL_MAX_FILE_SIZE / sizeof(gaucOldMacDonald)); 
            iLoopCnt++)
    {
        lRetVal = sl_FsWrite(*lFileHandle,
                    (unsigned int)(iLoopCnt * sizeof(gaucOldMacDonald)), 
                    (unsigned char *)gaucOldMacDonald, sizeof(gaucOldMacDonald));
        if (lRetVal < 0)
        {
            lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
            ASSERT_ON_ERROR(FILE_WRITE_FAILED);
        }
    }
    
    //
    // 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;
}