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;
}
Example #2
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);
}
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);
}
Example #4
0
bool updater_write (uint8_t *buf, uint32_t len) {
    bool result = false;

    sl_LockObjLock (&wlan_LockObj, SL_OS_WAIT_FOREVER);
    if (len == sl_FsWrite(updater_data.fhandle, updater_data.foffset, buf, len)) {
        updater_data.foffset += len;
        result = true;
    }
    sl_LockObjUnlock (&wlan_LockObj);

    return result;
}
Example #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);
}
Example #6
0
ssize_t fs_slfs_write(int fd, const void *buf, size_t count) {
  struct sl_fd_info *fi = &s_sl_fds[fd];
  if (fi->fh <= 0) return set_errno(EBADF);
  _i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf, count);
  DBG(("sl_FsWrite(%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_write(spiffs *fs, u32_t addr, u32_t size, u8_t *src) {
  struct mount_info *m = (struct mount_info *) fs->user_data;
  _i32 r;
  DBG(("failfs_write %d @ %d, cidx %d # %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_WRITABLE;
  if (!m->rw) {
    /* Remount rw. */
    if (fs_switch_container(m, 0, 0) != 0) return SPIFFS_ERR_NOT_WRITABLE;
  }
  r = sl_FsWrite(m->fh, addr, src, size);
  DBG(("write %d", (int) r));
  m->last_write = mg_time();
  return (r == size) ? SPIFFS_OK : SPIFFS_ERR_NOT_WRITABLE;
}
static s32_t failfs_write(u32_t addr, u32_t size, u8_t *src) {
  struct mount_info *m = &s_fsm;
  _i32 r;
  dprintf(("failfs_write %d @ %d, cidx %d # %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_WRITABLE;
  if (!m->rw) {
    /* Remount rw. */
    if (fs_switch_container(m, 0, 0) != 0) return SPIFFS_ERR_NOT_WRITABLE;
  }
  r = sl_FsWrite(m->fh, addr, src, size);
  dprintf(("write %d\n", (int) r));
  return (r == size) ? SPIFFS_OK : SPIFFS_ERR_NOT_WRITABLE;
}
static _i32 fs_write_meta(struct mount_info *m) {
  int r;
  _u32 offset;
  union fs_meta meta;
  memset(&meta, 0xff, sizeof(meta));
  meta.info.seq = m->seq;
  meta.info.fs_size = m->fs.cfg.phys_size;
  meta.info.fs_block_size = m->fs.cfg.log_block_size;
  meta.info.fs_page_size = m->fs.cfg.log_page_size;

  offset = FS_CONTAINER_SIZE(meta.info.fs_size) - sizeof(meta);
  r = sl_FsWrite(m->fh, offset, (_u8 *) &meta, sizeof(meta));
  dprintf(("write meta %llu @ %d: %d\n", m->seq, (int) offset, (int) r));
  if (r == sizeof(meta)) r = 0;
  return r;
}
Example #10
0
static _i32 _WriteBootInfo(sBootInfo_t *psBootInfo)
{
    _i32 lFileHandle;
    _u32 ulToken;
    _i32 status = -1;

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

    return status;
}
_i32 fs_write_meta(_i32 fh, _u64 seq, _u32 fs_size, _u32 fs_block_size,
                   _u32 fs_page_size, _u32 fs_erase_size) {
  int r;
  _u32 offset;
  union fs_container_meta meta;
  memset(&meta, 0xff, sizeof(meta));
  meta.info.seq = seq;
  meta.info.fs_size = fs_size;
  meta.info.fs_block_size = fs_block_size;
  meta.info.fs_page_size = fs_page_size;
  meta.info.fs_erase_size = fs_erase_size;

  offset = FS_CONTAINER_SIZE(meta.info.fs_size) - sizeof(meta);
  r = sl_FsWrite(fh, offset, (_u8 *) &meta, sizeof(meta));
  DBG(("write meta %llu @ %d: %d", seq, (int) offset, (int) r));
  if (r == sizeof(meta)) r = 0;
  return r;
}
Example #12
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);
    }
}
Example #13
0
size_t SLFS::write(const uint8_t *buffer, size_t len)
{
    if (!filehandle) {
        retval = SLFS_LIB_ERR_FILE_NOT_OPEN;
        return 0;
    }
    if (!is_write) {
        retval = SLFS_LIB_ERR_FILE_OPEN_FOR_READ;
        return 0;
    }
    
    if (offset > filesize)
        return 0;

    retval = sl_FsWrite(filehandle, offset, (unsigned char *)buffer, len);
    if (retval < 0) {
        return 0;
    }
    offset += retval;
    return retval;
}
Example #14
0
size_t SLFS::write(uint8_t c)
{
    if (!filehandle) {
        retval = SLFS_LIB_ERR_FILE_NOT_OPEN;
        return 0;
    }
    if (!is_write) {
        retval = SLFS_LIB_ERR_FILE_OPEN_FOR_READ;
        return 0;
    }
    
    if (offset > filesize)
        return 0;

    retval = sl_FsWrite(filehandle, offset, &c, 1);
    if (retval < 1) {
        return 0;
    }
    offset++;
    return 1;
}
Example #15
0
//*****************************************************************************
//
//!  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;
}
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;
}
Example #17
0
int GetFileFromServer(const int socket, const char* filename, const char* filenameInFlash) {
	int transfer_len = 0;
	long retVal = 0;
	long fileHandle = -1;
	unsigned long Token = 0, bytesReceived = 0;
	unsigned char *pBuff = 0;
	unsigned long file_size = 0;
	unsigned char buffer[MAX_BUFF_SIZE + 1];

	UART_PRINT("Start downloading the file %s\r\n", filename);

	memset(buffer, 0, sizeof(buffer));

	// Puts together the HTTP GET string.
	strcpy((char *) buffer, PREFIX_BUFFER);
	strcat((char *) buffer, filename);
	strcat((char *) buffer, POST_BUFFER);

	// Send the HTTP GET string to the opened TCP/IP socket.
	transfer_len = sl_Send(socket, buffer, strlen((const char *) buffer), 0);
	if (transfer_len < 0) {
		// error
		UART_PRINT("Socket Send Error\r\n");
		return -1;
	}

	memset(buffer, 0, sizeof(buffer));

	// get the reply from the server in buffer.
	transfer_len = sl_Recv(socket, buffer, MAX_BUFF_SIZE, 0);

	if (transfer_len > 0) {
		// Check for 404 return code
		if (strstr((const char *) buffer, HTTP_FILE_NOT_FOUND) != 0) {
			UART_PRINT("File not found, check the file and try again\r\n");
			return -1;
		}

		// if not "200 OK" return error
		if (strstr((const char *) buffer, HTTP_STATUS_OK) == 0) {
			UART_PRINT("Error during downloading the file\r\n");
			return -1;
		}

		// check if content length is transfered with headers
		pBuff = (unsigned char *) strstr((const char *) buffer, HTTP_CONTENT_LENGTH);
		if (pBuff != 0) {
			pBuff += strlen(HTTP_CONTENT_LENGTH);

			while (*pBuff != 0x0d)
				pBuff++;
			unsigned long multiplicant = 1;

			pBuff--;
			while (*pBuff != ' ') {
				file_size += (*pBuff - '0') * multiplicant;
				multiplicant *= 10;
				pBuff--;
			}

			if (file_size == 0) {
				UART_PRINT("\nContent Length not detected.\r\n");
				return -1;
			}

			UART_PRINT("Content Length %d\r\n", file_size);
		} else {
			UART_PRINT("\nContent Length not detected.\r\n");
			return -1;
		}

		// "\r\n\r\n" marks the end of headers
		pBuff = (unsigned char *) strstr((const char *) buffer, HTTP_END_OF_HEADER);
		if (pBuff == 0) {
			UART_PRINT("Invalid response\r\n");
			return -1;
		}
		// Increment by 4 to skip "\r\n\r\n"
		pBuff += 4;

		// Adjust buffer data length for header size
		transfer_len -= (pBuff - buffer);
	}

	// Delete eventually existing temporary file
	sl_FsDel((unsigned char *) filenameInFlash, Token);
	// Create a temporary file to save the downloaded file
	// open a user file for writing
	retVal = sl_FsOpen((unsigned char *) filenameInFlash, FS_MODE_OPEN_WRITE, &Token, &fileHandle);
	if (retVal < 0) {
		// File Doesn't exit create a new of file_size KB file
		retVal = sl_FsOpen((unsigned char *) filenameInFlash, FS_MODE_OPEN_CREATE(file_size, _FS_FILE_PUBLIC_WRITE), &Token, &fileHandle);
		if (retVal < 0) {
			UART_PRINT("Error during opening the temporary file\r\n");
			return -1;
		}
	}
	while (bytesReceived < file_size) {
		retVal = sl_FsWrite(fileHandle, bytesReceived, (unsigned char *) pBuff, transfer_len);
		if (retVal < 0) {
			retVal = sl_FsClose(fileHandle, 0, 0, 0);
			retVal = sl_FsDel((unsigned char *) filenameInFlash, Token);
			UART_PRINT("Error during writing the file\r\n");
			return -1;
		}
		bytesReceived += transfer_len;
		if (bytesReceived == file_size) break;

		memset(buffer, 0, sizeof(buffer));
		transfer_len = sl_Recv(socket, buffer, MAX_BUFF_SIZE, 0);
		pBuff = buffer;
	}

	// Close the opened file
	retVal = sl_FsClose(fileHandle, 0, 0, 0);

	if (bytesReceived != file_size) {
		UART_PRINT("Error While File Download\r\n");
		retVal = sl_FsDel((unsigned char *) filenameInFlash, Token);
		return -1;
	} else {
		UART_PRINT("\nDownloading File Completed\r\n");
	}
	return 0;
}
Example #18
0
short saveConfig() {
    long status = 0;
    long configFile = -1;

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

    status = sl_FsOpen((unsigned char *) CONFIG_FILENAME,
                       FS_MODE_OPEN_CREATE(65536, _FS_FILE_OPEN_FLAG_COMMIT | _FS_FILE_PUBLIC_WRITE),
                       NULL, &configFile);
    if (status < 0) {
        ERR_PRINT(status);
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
            UART_PRINT("[Blink] No available blocks. Need to flash your device file system...\r\n");
        }

        return status;
    }

    sl_FsClose(configFile, 0, 0, 0);

    configFile = -1;
    status = sl_FsOpen((unsigned char *) CONFIG_FILENAME, FS_MODE_OPEN_WRITE, NULL, &configFile);
    if (status < 0) {
        ERR_PRINT(status);
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
            UART_PRINT("[Blink] No available blocks. Need to flash your device file system...\r\n");
        }
        sl_FsClose(configFile, 0, 0, 0);
        return status;
    }

    UART_PRINT("[Blink] Application Id            : %s\r\n", g_ApplicationID);
    long readOffset = 0;
    status = sl_FsWrite(configFile, readOffset, (unsigned char *)g_ApplicationID, sizeof(g_ApplicationID));
    if (status < 0) {
        ERR_PRINT(status);
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
            UART_PRINT("[Blink] No available blocks. Need to flash your device file system...\r\n");
        }
        sl_FsClose(configFile, 0, 0, 0);
        return status;
    }

    UART_PRINT("[Blink] Client key                : %s\r\n", g_ClientKey);
    readOffset = readOffset + status;
    status = sl_FsWrite(configFile, readOffset, (unsigned char *)g_ClientKey, sizeof(g_ClientKey));
    if (status < 0) {
        ERR_PRINT(status);
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
            UART_PRINT("[Blink] No available blocks. Need to flash your device file system...\r\n");
        }
        sl_FsClose(configFile, 0, 0, 0);
        return status;
    }

    UART_PRINT("[Blink] Installation Id           : %s\r\n", g_InstallationID);
    readOffset = readOffset + status;
    status = sl_FsWrite(configFile, readOffset, (unsigned char *)g_InstallationID, sizeof(g_InstallationID));
    if (status < 0) {
        ERR_PRINT(status);
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
            UART_PRINT("[Blink] No available blocks. Need to flash your device file system...\r\n");
        }
        sl_FsClose(configFile, 0, 0, 0);
        return status;
    }

    UART_PRINT("[Blink] Session token             : %s\r\n", g_SessionToken);
    readOffset = readOffset + status;
    status = sl_FsWrite(configFile, readOffset, (unsigned char *)g_SessionToken, sizeof(g_SessionToken));
    if (status < 0) {
        ERR_PRINT(status);
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
            UART_PRINT("[Blink] No available blocks. Need to flash your device file system...\r\n");
        }
        sl_FsClose(configFile, 0, 0, 0);
        return status;
    }

    UART_PRINT("[Blink] Device name               : %s\r\n", g_DeviceName);
    readOffset = readOffset + status;
    status = sl_FsWrite(configFile, readOffset, (unsigned char *)g_DeviceName, sizeof(g_DeviceName));
    if (status < 0) {
        ERR_PRINT(status);
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
            UART_PRINT("[Blink] No available blocks. Need to flash your device file system...\r\n");
        }
        sl_FsClose(configFile, 0, 0, 0);
        return status;
    }

    sl_FsClose(configFile, 0, 0, 0);

    return status;
}
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;
}
Example #20
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;
}
short saveClientState(ParseClientInternal *parseClient) {
#ifdef CLIENT_DEBUG
    DEBUG_PRINT("[Parse] Saving client state\r\n");
#endif /* CLIENT_DEBUG */

    snprintf(clientStateFileName, CLIENT_STATE_FILENAME_LEN, CLIENT_STATE_FILENAME, parseClient->applicationId);

    long clientStateFile = -1;

    sl_FsDel((unsigned char *)clientStateFileName, 0);

    short status = sl_FsOpen((unsigned char *)clientStateFileName,
            FS_MODE_OPEN_CREATE(65536, _FS_FILE_OPEN_FLAG_COMMIT | _FS_FILE_PUBLIC_WRITE),
            NULL, &clientStateFile);
    if (status < 0) {
#ifdef CLIENT_DEBUG
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
             DEBUG_PRINT("[Parse] No available blocks. Need to flash your device file system...\r\n");
        }
#endif /* CLIENT_DEBUG */
        return status;
    }

    sl_FsClose(clientStateFile, 0, 0, 0);

    clientStateFile = -1;
    status = sl_FsOpen((unsigned char *)clientStateFileName, FS_MODE_OPEN_WRITE, NULL, &clientStateFile);
    if (status < 0) {
#ifdef CLIENT_DEBUG
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
             DEBUG_PRINT("[Parse] No available blocks. Need to flash your device file system...\r\n");
        }
#endif /* CLIENT_DEBUG */
        sl_FsClose(clientStateFile, 0, 0, 0);
        return status;
    }

#ifdef CLIENT_DEBUG
    DEBUG_PRINT("[Parse] Installation Id: %s\r\n", parseClient->installationId);
#endif /* CLIENT_DEBUG */
    long writeOffset = 0;
    status = sl_FsWrite(clientStateFile, writeOffset, (unsigned char *)parseClient->installationId, sizeof(parseClient->installationId));
    if (status < 0) {
#ifdef CLIENT_DEBUG
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
             DEBUG_PRINT("[Parse] No available blocks. Need to flash your device file system...\r\n");
        }
#endif /* CLIENT_DEBUG */
        sl_FsClose(clientStateFile, 0, 0, 0);
        return status;
    }

#ifdef CLIENT_DEBUG
    DEBUG_PRINT("[Parse] Session token: %s\r\n", parseClient->sessionToken);
#endif /* CLIENT_DEBUG */
    writeOffset = writeOffset + status;
    status = sl_FsWrite(clientStateFile, writeOffset, (unsigned char *)parseClient->sessionToken, sizeof(parseClient->sessionToken));
    if (status < 0) {
#ifdef CLIENT_DEBUG
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
             DEBUG_PRINT("[Parse] No available blocks. Need to flash your device file system...\r\n");
        }
#endif /* CLIENT_DEBUG */
        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 */
    writeOffset = writeOffset + status;
    status = sl_FsWrite(clientStateFile, writeOffset, (unsigned char *)parseClient->lastPushHash, sizeof(parseClient->lastPushHash));
    if (status < 0) {
#ifdef CLIENT_DEBUG
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
             DEBUG_PRINT("[Parse] No available blocks. Need to flash your device file system...\r\n");
        }
#endif /* CLIENT_DEBUG */
        sl_FsClose(clientStateFile, 0, 0, 0);
        return status;
    }

    sl_FsClose(clientStateFile, 0, 0, 0);

    return status;
}
Example #22
0
_i32 sl_extlib_FlcWriteFile(_i32 fileHandle, _i32 offset, _u8 *buf, _i32 len)
{
    return sl_FsWrite(fileHandle, (_u32)(offset), (_u8 *)buf, len);
}
Example #23
0
File: main.c Project: 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;
}
Example #24
0
File: main.cpp Project: hangc2/wif
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();
}
Example #25
0
static int tcmp(const struct json_token *tok, const char *str) {
  struct mg_str s = {.p = tok->ptr, .len = tok->len};
  return mg_vcmp(&s, str);
}

enum mgos_upd_file_action mgos_upd_file_begin(
    struct mgos_upd_hal_ctx *ctx, const struct mgos_upd_file_info *fi) {
  struct mg_str part_name = MG_MK_STR("");
  enum mgos_upd_file_action ret = MGOS_UPDATER_SKIP_FILE;
  struct find_part_info find_part_info = {fi->name, &part_name, &ctx->cur_part};
  ctx->cur_part.len = part_name.len = 0;
  json_walk(ctx->parts->ptr, ctx->parts->len, find_part, &find_part_info);
  if (ctx->cur_part.len == 0) return ret;
  /* Drop any indexes from part name, we'll add our own. */
  while (1) {
    char c = part_name.p[part_name.len - 1];
    if (c != '.' && !(c >= '0' && c <= '9')) break;
    part_name.len--;
  }
  struct json_token type = JSON_INVALID_TOKEN;
  const char *fname = NULL;
  uint32_t falloc = 0;
  json_scanf(ctx->cur_part.ptr, ctx->cur_part.len,
             "{load_addr:%u, falloc:%u, type: %T}", &ctx->app_load_addr,
             &falloc, &type);

  if (falloc == 0) falloc = fi->size;
  if (tcmp(&type, "app") == 0) {
    struct boot_cfg cur_cfg;
    int r = read_boot_cfg(ctx->cur_boot_cfg_idx, &cur_cfg);
    if (r < 0) {
      ctx->status_msg = "Could not read current boot cfg";
      return MGOS_UPDATER_ABORT;
    }
#if CC3200_SAFE_CODE_UPDATE
    /*
     * When safe code update is enabled, we write code to a new file.
     * Otherwise we write to the same slot we're using currently, which is
     * unsafe, makes reverting code update not possible, but saves space.
     */
    create_fname(
        mg_mk_str_n(cur_cfg.app_image_file, strlen(cur_cfg.app_image_file) - 2),
        ctx->new_boot_cfg_idx, ctx->app_image_file,
        sizeof(ctx->app_image_file));
#else
    {
      strncpy(ctx->app_image_file, cur_cfg.app_image_file,
              sizeof(ctx->app_image_file));
    }
#endif
    if (ctx->app_load_addr >= 0x20000000) {
      fname = ctx->app_image_file;
    } else {
      ctx->status_msg = "Bad/missing app load_addr";
      ret = MGOS_UPDATER_ABORT;
    }
  } else if (tcmp(&type, "fs") == 0) {
    json_scanf(
        ctx->cur_part.ptr, ctx->cur_part.len,
        "{fs_size: %u, fs_block_size: %u, fs_page_size: %u, fs_erase_size: %u}",
        &ctx->fs_size, &ctx->fs_block_size, &ctx->fs_page_size,
        &ctx->fs_erase_size);
    if (ctx->fs_size > 0 && ctx->fs_block_size > 0 && ctx->fs_page_size > 0 &&
        ctx->fs_erase_size > 0) {
      char fs_container_prefix[MAX_FS_CONTAINER_PREFIX_LEN];
      create_fname(part_name, ctx->new_boot_cfg_idx, fs_container_prefix,
                   sizeof(fs_container_prefix));
      /* Delete container 1 (if any) so that 0 is the only one. */
      cc32xx_vfs_dev_slfs_container_delete_container(fs_container_prefix, 1);
      cc32xx_vfs_dev_slfs_container_fname(fs_container_prefix, 0,
                                          (_u8 *) ctx->fs_container_file);
      fname = ctx->fs_container_file;
      if (fi->size > ctx->fs_size) {
        /* Assume meta has already been added. */
        falloc = fi->size;
      } else {
        falloc = FS_CONTAINER_SIZE(fi->size);
      }
    } else {
      ctx->status_msg = "Missing FS parameters";
      ret = MGOS_UPDATER_ABORT;
    }
  }
  if (fname != NULL) {
    int r = prepare_to_write(ctx, fi, fname, falloc, &ctx->cur_part);
    if (r < 0) {
      LOG(LL_ERROR, ("err = %d", r));
      ret = MGOS_UPDATER_ABORT;
    } else {
      ret = (r > 0 ? MGOS_UPDATER_PROCESS_FILE : MGOS_UPDATER_SKIP_FILE);
    }
  }
  if (ret == MGOS_UPDATER_SKIP_FILE) {
    DBG(("Skipping %s %.*s", fi->name, (int) part_name.len, part_name.p));
  }
  return ret;
}

int mgos_upd_file_data(struct mgos_upd_hal_ctx *ctx,
                       const struct mgos_upd_file_info *fi,
                       struct mg_str data) {
  _i32 r = sl_FsWrite(ctx->cur_fh, fi->processed, (_u8 *) data.p, data.len);
  if (r != data.len) {
    ctx->status_msg = "Write failed";
    r = -1;
  }
  return r;
}