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;
}
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;
}
Beispiel #3
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;
}
Beispiel #4
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;
}
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;
}
Beispiel #6
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;
}
Beispiel #7
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);
}
Beispiel #8
0
ssize_t fs_slfs_read(int fd, void *buf, size_t count) {
  struct sl_fd_info *fi = &s_sl_fds[fd];
  if (fi->fh <= 0) return set_errno(EBADF);
  /* Simulate EOF. sl_FsRead @ file_size return SL_FS_ERR_OFFSET_OUT_OF_RANGE.
   */
  if (fi->pos == fi->size) return 0;
  _i32 r = sl_FsRead(fi->fh, fi->pos, buf, count);
  DBG(("sl_FsRead(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
       (int) r));
  if (r >= 0) {
    fi->pos += r;
    return r;
  }
  return set_errno(sl_fs_to_errno(r));
}
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;
}
Beispiel #10
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);
}
Beispiel #11
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;
}
Beispiel #12
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);
            }
        }
    }
}
Beispiel #13
0
String SLFS::readBytes(size_t maxlen)
{
    char *sh = NULL;
    size_t len;

    if (!filehandle) {
        retval = SLFS_LIB_ERR_FILE_NOT_OPEN;
        return String("");
    }
    if (is_write) {
        retval = SLFS_LIB_ERR_FILE_OPEN_FOR_WRITE;
        return String("");
    }
    
    if (offset == filesize)
        return String("");

    len = filesize-offset;
    if (len > maxlen)
        len = maxlen;

    // Free up some memory before allocating our next buffer
    if (_readBytesInstance != NULL) {
        delete _readBytesInstance;  // Execute String's destructor, freeing the buffer in the process
        _readBytesInstance = NULL;
    }

    // Allocate suitable buffer space to hold the file contents
    sh = (char *) malloc(len+1);
    sh[len] = '\0';
    
    retval = sl_FsRead(filehandle, offset, (uint8_t *)sh, len);
    if (retval < 0) {
        free(sh);
        return String("");
    }
    offset += retval;

    // Allocate a new String instance to hold the contents (which is strcpy'd by String's constructor)
    _readBytesInstance = new String(sh);
    free(sh);  // Creating a new String performs a strcpy, so 'sh' is no longer needed.
    return *_readBytesInstance;  // Caller will usually assign this to another String object, triggering yet another strcpy.
}
Beispiel #14
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;
}
Beispiel #16
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;
}
Beispiel #17
0
size_t SLFS::readBytes(void *buffer, size_t len)
{
    unsigned char *cbuf = (unsigned char *)buffer;

    if (!filehandle) {
        retval = SLFS_LIB_ERR_FILE_NOT_OPEN;
        return 0;
    }
    if (is_write) {
        retval = SLFS_LIB_ERR_FILE_OPEN_FOR_WRITE;
        return 0;
    }
    
    if (offset == filesize)
        return 0;
    
    retval = sl_FsRead(filehandle, offset, cbuf, len);
    if (retval < 0)
        return 0;
    offset += retval;
    return retval;
}
Beispiel #18
0
int SLFS::peek(void)
{
    uint8_t buf[4];

    if (!filehandle) {
        retval = SLFS_LIB_ERR_FILE_NOT_OPEN;
        return (int)retval;
    }
    if (is_write) {
        retval = SLFS_LIB_ERR_FILE_OPEN_FOR_WRITE;
        return (int)retval;
    }
    
    if (offset == filesize)
        return -1;
    
    retval = sl_FsRead(filehandle, offset, buf, 1);
    if (retval != 1) {
        return -1;
    }
    return (int)buf[0];
}
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;
}
Beispiel #20
0
/**
 * Process a static-content HTTP request
 * This function is called after a request was already initialized, and a Flash content entry was identified during a call to HttpStatic_InitRequest()
 * This function calls HttpResponse_*() to send the content data to the browser.
 * @param request Pointer to all data available about the request
 * @return nonzero if request was handled. zero if not.
 */
int HttpStatic_ProcessRequest(struct HttpRequest* request)
{
	struct HttpBlob location,contentType;
	struct HttpBlob* content = (struct HttpBlob*)malloc(sizeof(struct HttpBlob));
	unsigned long Offset = 0;
	SlFsFileInfo_t pFsFileInfo;
	UINT32 TotalLength;
	UINT8 HeaderFlag =0;

	location.pData = NULL;
	location.uLength = 0;
	contentType = location;

	/*  if HTTP_REQUEST_FLAG_METHOD_POST==1 (i.e. it is POST)
		HttpResponse_CannedError() responds to client with status HTTP_STATUS_ERROR_INTERNAL
		POST method is not supported for static pages	*/
	if (request->uFlags & HTTP_REQUEST_FLAG_METHOD_POST)
	{
		 /* HttpResponse_CannedError responds to client with 500 ERROR_INTERNAL  */
   		 if(!HttpResponse_CannedError(request->uConnection,
                                    HTTP_STATUS_ERROR_INTERNAL))
   		 	 return 0;
   		 else
   		 	 return 1;
	}

	//sl_FsGetInfo((unsigned char *)g_cFileName, NULL, &pFsFileInfo);
	sl_FsGetInfo((unsigned char *)g_cFileName, 0, &pFsFileInfo);
	TotalLength = (&pFsFileInfo)->FileLen;

	while(TotalLength > 0)
	{
		content->uLength = ((TotalLength < 1000) ? (TotalLength):(1000));

		UINT8* (buffer) = (UINT8*)malloc(content->uLength);
		content->pData = buffer;

		/* if got here than it is a GET method
		HttpResponse_Headers() responds to client with status HTTP_STATUS_OK */
		if(sl_FsRead(glFileHandle,
                 Offset, (unsigned char *)
                 content->pData,
                 content->uLength) < 0)
		{
			/* call HttpResponse_CannedError responds to client with 500 ERROR_INTERNAL  */
			if(!HttpResponse_CannedError( request->uConnection,
                                    HTTP_STATUS_ERROR_NOT_ACCEPTED))
				return 0;
			else
				return 1;
		}
		else
		{
			if(!HeaderFlag)
			{
				if(!HttpResponse_Headers( request->uConnection,
                                  HTTP_STATUS_OK,
                                  0, 
                                  TotalLength,
                                  contentType,
                                  location))
					return 0;
				HeaderFlag = 1;
			}

			/* HttpResponse_Content() sends requested page to the client */
			if(!HttpResponse_Content(request->uConnection, *content))
				return 0;
		}

		TotalLength -= content->uLength;
		Offset += content->uLength;
		free(buffer);
	}

	sl_FsClose(glFileHandle,0,0,0);

	free(content);

	return 1;
}
int ComputeSHA(const char *sourceFile, uint8_t *resultHash) {
	long sfileHandle = -1;
	unsigned long sToken = 0;
	long retVal = 0;
	unsigned long bytesRead = 0;
	unsigned long readsize = 0;
	uint8_t buffer[BLOCKSIZE];
	SlFsFileInfo_t sFileInfo;

	UART_PRINT("\r\nStarted comuting hash\r\n");

	//Enable MD5SHA module
	PRCMPeripheralClkEnable(PRCM_DTHE, PRCM_RUN_MODE_CLK);
	MAP_SHAMD5IntRegister(SHAMD5_BASE, SHAMD5IntHandler);

	//reset modul
	PRCMPeripheralReset(PRCM_DTHE);

	//clear flags
	g_bContextReadyFlag = false;
	g_bInputReadyFlag = false;

	//Enable Interrupts
	SHAMD5IntEnable(SHAMD5_BASE, SHAMD5_INT_CONTEXT_READY | SHAMD5_INT_PARTHASH_READY | SHAMD5_INT_INPUT_READY | SHAMD5_INT_OUTPUT_READY);

	//wait for context ready flag.
	while (!g_bContextReadyFlag)
		;

	//Configure SHA/MD5 module
	SHAMD5ConfigSet(SHAMD5_BASE, SHAMD5_ALGO_SHA1);

	// get file size
	retVal = sl_FsGetInfo((unsigned char *) sourceFile, sToken, &sFileInfo);
	if (retVal < 0) {
		// File Doesn't exit create a new of 45 KB file
		UART_PRINT("Error during opening the source file\r\n");
		return -1;
	}

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

	SHAMD5DataLengthSet(SHAMD5_BASE, (uint32_t) sFileInfo.FileLen);

	// Copy the files from temporary file to original file
	// If user file has checksum which can be used to verify the temporary
	// file then file should be verified before copying
	while (bytesRead < sFileInfo.FileLen) {
		if ((sFileInfo.FileLen - bytesRead) > BLOCKSIZE) readsize = BLOCKSIZE;
		else readsize = (sFileInfo.FileLen - bytesRead);

		memset(buffer, 0, sizeof(buffer));
		retVal = sl_FsRead(sfileHandle, bytesRead, (unsigned char *) buffer, readsize);
		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;
		}
		SHAMD5DataWrite(SHAMD5_BASE, buffer);
		bytesRead += readsize;
	}

	// 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;
	}
	UART_PRINT("Hash successfully\r\n");
	SHAMD5ResultRead(SHAMD5_BASE, resultHash);
	return 0;
}
Beispiel #22
0
short loadConfig() {
    long status;
    long configFile;

    UART_PRINT("[Blink] Loading configuration\r\n");

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

    long readOffset = 0;
    status = sl_FsRead(configFile, readOffset, (unsigned char *)g_ApplicationID, sizeof(g_ApplicationID));
    if (status < 0) {
        ERR_PRINT(status);
        sl_FsClose(configFile, 0, 0, 0);
        return status;
    }
    UART_PRINT("[Blink] Application Id            : %s\r\n", g_ApplicationID);

    readOffset = readOffset + status;
    status = sl_FsRead(configFile, readOffset, (unsigned char *)g_ClientKey, sizeof(g_ClientKey));
    if (status < 0) {
        ERR_PRINT(status);
        sl_FsClose(configFile, 0, 0, 0);
        return status;
    }
    UART_PRINT("[Blink] Client key                : %s\r\n", g_ClientKey);

    readOffset = readOffset + status;
    status = sl_FsRead(configFile, readOffset, (unsigned char *)g_InstallationID, sizeof(g_InstallationID));
    if (status < 0) {
        ERR_PRINT(status);
        sl_FsClose(configFile, 0, 0, 0);
        return status;
    }
    UART_PRINT("[Blink] Installation Id           : %s\r\n", g_InstallationID);

    readOffset = readOffset + status;
    status = sl_FsRead(configFile, readOffset, (unsigned char *)g_SessionToken, sizeof(g_SessionToken));
    if (status < 0) {
        ERR_PRINT(status);
        sl_FsClose(configFile, 0, 0, 0);
        return status;
    }
    UART_PRINT("[Blink] Session token             : %s\r\n", g_SessionToken);

    readOffset = readOffset + status;
    status = sl_FsRead(configFile, readOffset, (unsigned char *)g_DeviceName, sizeof(g_DeviceName));
    if (status < 0) {
        ERR_PRINT(status);
        sl_FsClose(configFile, 0, 0, 0);
        return status;
    }
    UART_PRINT("[Blink] Device name               : %s\r\n", g_DeviceName);

    sl_FsClose(configFile, 0, 0, 0);

    return status;
}
Beispiel #23
0
static void TFTPTask(void *pvParameters)
{
    SlSecParams_t secParams;
    unsigned char *pucFileBuffer = NULL;  // Data read or to be written
    unsigned long uiFileSize;

    const char *FileRead = "readFromServer.txt";  // File to be read using TFTP. Change string to filename
    const char *FileWrite = "writeToServer.txt"; // File to be written using TFTP. Change string to filename.

    long pFileHandle;			// Pointer to file handle
    SlFsFileInfo_t pFsFileInfo;
    long lRetVal = -1;
    unsigned short uiTftpErrCode;


//get wifi information
  //  get_wifi_info(ap_ssid, secPrams);

    // Configuring security parameters for the AP
    secParams.Key = (_i8*)SSID_KEY;
    secParams.KeyLen = 30;
    secParams.Type = SL_SEC_TYPE_WPA_WPA2;

    lRetVal = Network_IF_InitDriver(ROLE_STA);


    // Connecting to WLAN AP - Set with static parameters defined at the top
    // After this call we will be connected and have IP address
    lRetVal = Network_IF_ConnectAP((char*)SSID,secParams);

    UART_PRINT("Connecting to TFTP server %d.%d.%d.%d\n\r",\
                  SL_IPV4_BYTE(TFTP_IP, 3),SL_IPV4_BYTE(TFTP_IP, 2),
                  SL_IPV4_BYTE(TFTP_IP, 1),SL_IPV4_BYTE(TFTP_IP, 0));
    if(TFTP_READ)
    {
        uiFileSize = FILE_SIZE_MAX;

        pucFileBuffer = new unsigned char[uiFileSize];
        if(NULL == pucFileBuffer)
        {
            UART_PRINT("Can't Allocate Resources\r\n");
            LOOP_FOREVER();
        }

        memset(pucFileBuffer,'\0',uiFileSize);

        lRetVal = sl_TftpRecv(TFTP_IP, FileRead, (char *)pucFileBuffer,\
                                &uiFileSize, &uiTftpErrCode );
        UART_PRINT("file read is %s\n", pucFileBuffer);

        if(lRetVal < 0)
        {
            free(pucFileBuffer);
            ERR_PRINT(lRetVal);
            LOOP_FOREVER();
        }

        lRetVal = sl_FsGetInfo((unsigned char *)FileRead, 0, &pFsFileInfo);

        if(lRetVal < 0 )
            lRetVal = sl_FsOpen((unsigned char *)FileRead,\
                    FS_MODE_OPEN_CREATE(FILE_SIZE_MAX,_FS_FILE_OPEN_FLAG_COMMIT|\
                      _FS_FILE_PUBLIC_WRITE), NULL,&pFileHandle);
        else
            lRetVal = sl_FsOpen((unsigned char *)FileRead,FS_MODE_OPEN_WRITE, \
                                NULL,&pFileHandle);

        if(lRetVal < 0)
        {
            free(pucFileBuffer);
            ERR_PRINT(lRetVal);
            LOOP_FOREVER();
        }

        lRetVal = sl_FsWrite(pFileHandle,0, pucFileBuffer, uiFileSize);

        if(lRetVal < 0)
        {
            free(pucFileBuffer);
            lRetVal = sl_FsClose(pFileHandle,0,0,0);
            ERR_PRINT(lRetVal);
            LOOP_FOREVER();
        }

        UART_PRINT("TFTP Read Successful \r\n");

        lRetVal = sl_FsClose(pFileHandle,0,0,0);

    }

    if(TFTP_WRITE)
    {
    	/* open same file which has been written with the server's file content */
        lRetVal = sl_FsOpen((unsigned char *)FileRead,FS_MODE_OPEN_READ, \
                                NULL,&pFileHandle);
        if(lRetVal < 0)
        {
            free(pucFileBuffer);
            ERR_PRINT(lRetVal);
            LOOP_FOREVER();
        }

        lRetVal = sl_FsGetInfo((unsigned char *)FileRead, 0, &pFsFileInfo);
        if(lRetVal < 0)
        {
            lRetVal = sl_FsClose(pFileHandle,0,0,0);
            free(pucFileBuffer);
            ERR_PRINT(lRetVal);
            LOOP_FOREVER();
        }

        uiFileSize = (&pFsFileInfo)->FileLen;

        lRetVal = sl_FsRead(pFileHandle, 0,  pucFileBuffer, uiFileSize);
        if(lRetVal < 0)
        {
            lRetVal = sl_FsClose(pFileHandle,0,0,0);
            free(pucFileBuffer);
            ERR_PRINT(lRetVal);
            LOOP_FOREVER();
        }

        lRetVal = sl_FsClose(pFileHandle,0,0,0);
        /* write to server with different file name */
        lRetVal = sl_TftpSend(TFTP_IP, FileWrite,(char *) pucFileBuffer,\
                            &uiFileSize, &uiTftpErrCode  );
        if(lRetVal < 0)
        {
            free(pucFileBuffer);
            ERR_PRINT(lRetVal);
            LOOP_FOREVER();
        }

        UART_PRINT("TFTP Write Successful \r\n");
    }

    LOOP_FOREVER();
}
static _i32 fs_switch_container(struct mount_info *m, _u32 mask_begin,
                                _u32 mask_len) {
  int r;
  int new_cidx = m->cidx ^ 1;
  _i32 old_fh = m->fh, new_fh;
  _u8 *buf;
  _u32 offset, len, buf_size;
  LOG(LL_DEBUG, ("%s %d -> %d", m->cpfx, m->cidx, new_cidx));
  if (old_fh > 0 && m->rw) {
    /*
     * During the switch the destination container will be unusable.
     * If switching from a writeable container (likely in response to an erase),
     * close the old container first to make it safe and reopen for reading.
     */
    fs_close_container(m);
    old_fh = -1;
  }
  if (old_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, &old_fh);
    DBG(("fopen %s %d", m->cpfx, r));
    if (r < 0) {
      r = SPIFFS_ERR_NOT_READABLE;
      goto out_close_old;
    }
  }
  miot_wdt_feed();
  new_fh = fs_create_container(m->cpfx, new_cidx, m->fs.cfg.phys_size);
  if (new_fh < 0) {
    r = new_fh;
    goto out_close_old;
  }

  buf_size = 1024;
  buf = get_buf(&buf_size);
  if (buf == NULL) {
    r = SPIFFS_ERR_INTERNAL;
    goto out_close_new;
  }

  for (offset = 0; offset < m->fs.cfg.phys_size;) {
    len = buf_size;
    if (offset == mask_begin) {
      offset = mask_begin + mask_len;
    } else if (offset + len > mask_begin && offset < mask_begin + mask_len) {
      len = mask_begin - offset;
    }
    if (offset + len > m->fs.cfg.phys_size) {
      len = m->fs.cfg.phys_size - offset;
    }
    DBG(("copy %d @ %d", (int) len, (int) offset));
    if (len > 0) {
      r = sl_FsRead(old_fh, offset, buf, len);
      if (r != len) {
        r = SPIFFS_ERR_NOT_READABLE;
        goto out_free;
      }
      r = sl_FsWrite(new_fh, offset, buf, len);
      if (r != len) {
        r = SPIFFS_ERR_NOT_WRITABLE;
        goto out_free;
      }
      offset += len;
    }
  }

  m->seq--;
  m->cidx = new_cidx;
  m->fh = new_fh;
  new_fh = -1;
  m->rw = 1;

  r = fs_write_mount_meta(m);

  m->last_write = mg_time();

out_free:
  free(buf);
out_close_new:
  if (new_fh > 0) sl_FsClose(new_fh, NULL, NULL, 0);
out_close_old:
  sl_FsClose(old_fh, NULL, NULL, 0);
  LOG((r == 0 ? LL_DEBUG : LL_ERROR), ("%d", r));
  return r;
}
static _i32 fs_switch_container(struct mount_info *m, _u32 mask_begin,
                                _u32 mask_len) {
  int r;
  int new_cidx = m->cidx ^ 1;
  _i32 old_fh = m->fh, new_fh;
  _u8 *buf;
  _u32 offset, len, buf_size;
  dprintf(("switch %d -> %d\n", m->cidx, new_cidx));
  if (old_fh < 0) {
    r = sl_FsOpen(container_fname(m->cidx), FS_MODE_OPEN_READ, NULL, &old_fh);
    dprintf(("fopen %d\n", r));
    if (r < 0) {
      r = SPIFFS_ERR_NOT_READABLE;
      goto out_close_old;
    }
  }
  new_fh = fs_create_container(new_cidx, m->fs.cfg.phys_size);
  if (new_fh < 0) {
    r = new_fh;
    goto out_close_old;
  }

  buf_size = 8192;
  buf = get_buf(&buf_size);
  if (buf == NULL) {
    r = SPIFFS_ERR_INTERNAL;
    goto out_close_new;
  }

  for (offset = 0; offset < m->fs.cfg.phys_size;) {
    len = buf_size;
    if (offset == mask_begin) {
      offset = mask_begin + mask_len;
    } else if (offset + len > mask_begin && offset < mask_begin + mask_len) {
      len = mask_begin - offset;
    }
    if (offset + len > m->fs.cfg.phys_size) {
      len = m->fs.cfg.phys_size - offset;
    }
    dprintf(("copy %d @ %d\n", (int) len, (int) offset));
    if (len > 0) {
      r = sl_FsRead(old_fh, offset, buf, len);
      if (r != len) {
        r = SPIFFS_ERR_NOT_READABLE;
        goto out_free;
      }
      r = sl_FsWrite(new_fh, offset, buf, len);
      if (r != len) {
        r = SPIFFS_ERR_NOT_WRITABLE;
        goto out_free;
      }
      offset += len;
    }
  }

  m->seq--;
  m->cidx = new_cidx;
  m->fh = new_fh;
  new_fh = -1;
  m->rw = 1;

  r = fs_write_meta(m);

out_free:
  free(buf);
out_close_new:
  if (new_fh > 0) sl_FsClose(new_fh, NULL, NULL, 0);
out_close_old:
  sl_FsClose(old_fh, NULL, NULL, 0);
  dprintf(("switch: %d\n", r));
  return r;
}
Beispiel #26
0
_i32 sl_extlib_FlcReadFile(_i32 fileHandle, _i32 offset, _u8 *buf, _i32 len)
{
    return sl_FsRead(fileHandle, (_u32)(offset), (_u8 *)buf, len);
}
Beispiel #27
0
//****************************************************************************
//
//! \internal
//!
//! Set the factory image as the new boot image
//!
//! return None
//
//****************************************************************************
static int FactoryResetTask(void *pvParameters)
{
  sBootInfo_t sBootInfo;
  long lFileHandle;
  unsigned long ulToken;
  static unsigned char ucTaskOwnState = FACTORY_RST_STATE_WAIT_BTN;

  switch(ucTaskOwnState)
  {

  case FACTORY_RST_STATE_WAIT_BTN:
    //
    // Wait for button press
    //
    TaskSyncObjWait(&g_FactResetSyncObj);

    //
    // Switch to RUN state
    //
    ucTaskOwnState = FACTORY_RST_STATE_RUN;

    //
    // Break
    //
    break;

  case FACTORY_RST_STATE_RUN:

    //
    // Read the boot Info
    //
    if( 0 == sl_FsOpen((unsigned char *)IMG_BOOT_INFO, FS_MODE_OPEN_READ,
                       &ulToken, &lFileHandle) )
    {
        if( 0 > sl_FsRead(lFileHandle, 0, (unsigned char *)&sBootInfo,
                         sizeof(sBootInfo_t)) )
        {
          return TASK_RET_DONE;
        }
        sl_FsClose(lFileHandle, 0, 0, 0);
    }

    //
    // Set the factory default
    //
    sBootInfo.ucActiveImg = IMG_ACT_FACTORY;
    sBootInfo.ulImgStatus = IMG_STATUS_NOTEST;

    //
    // Save the new configuration
    //
    if( 0 == sl_FsOpen((unsigned char *)IMG_BOOT_INFO, FS_MODE_OPEN_WRITE,
                       &ulToken, &lFileHandle) )
    {
        sl_FsWrite(lFileHandle, 0, (unsigned char *)&sBootInfo,
                   sizeof(sBootInfo_t));
        sl_FsClose(lFileHandle, 0, 0, 0);
    }

    //
    // Force reboot
    //
    g_ulSysState  = SYS_STATE_REBOOT;

    //
    // Return done.
    //
    return TASK_RET_DONE;
  }

  return TASK_RET_IN_PROG;
}