Esempio n. 1
0
boolean OTAUpdateClass::copyFile(const char* src, const char* dst) {
    char buffer[DIGEST_SIZE_BUFFER];

    LFlash.begin();
    LFile fsrc = LFlash.open(src, FILE_READ);
    if(!fsrc) {
        DEBUG_UPDATE("OTAUpdate::copyFile - error opening src %s\r\n", src);
        return false;
    }
    LFile fdst = LFlash.open(dst, FILE_WRITE);
    if(!fsrc) {
        fsrc.close();
        DEBUG_UPDATE("OTAUpdate::copyFile - error opening dst %s\r\n", dst);
        return false;
    }

    fdst.seek(0);
    int size = fsrc.size();
    int done = 0;
    while(done < size) {
        int read = fsrc.read(buffer, DIGEST_SIZE_BUFFER);
        fdst.write(buffer, read);
        done += read;
    }
    fsrc.close();
    fdst.close();

    return true;
}
Esempio n. 2
0
boolean OTAUpdateClass::downloadFile(const char* name) {
	// make some http requests to check for firmware updates
	LGPRSClient c;
	uint8_t buffer[DIGEST_SIZE_BUFFER];
	int n , size, max_millis;
	
	// download the firmware
	if(!c.connect(this->host, 80)) {
		DEBUG_UPDATE("OTAUpdate::downloadFile - error connecting to update host\r\n");
		return false;
	}
	// connected... send the get request
	DEBUG_UPDATE("OTAUpdate::downloadFile %s:80 'GET /%s/%s'\r\n", this->host, this->path, &name[4]);
	c.printf("GET /%s/%s\n", this->path, &name[4]);

	// save the result
	max_millis = millis() + 10000;
	LFlash.begin();
	LFlash.remove((char*) name);
	
	LFile ota = LFlash.open(name, FILE_WRITE);
	ota.seek(0);
	size = 0;
	
	while(c.connected()) {
		int n = c.read(buffer, 1024);
		if(n > 0) {
			max_millis = millis() + 2000;
			ota.write(buffer, n);
			size += n;
		} else {
			if(millis() > max_millis) {
				DEBUG_UPDATE("OTAUpdate::downloadFile - timed out!\r\n");
				c.stop();
				ota.close();
				return false;
			} else {
				delay(100);
			}
		}		
	}
	c.stop();
	ota.close();
	
	DEBUG_UPDATE("OTAUpdate::downloadFile - done! got %d bytes\r\n", size);
	return size > 0;
}
Esempio n. 3
0
boolean OTAUpdateClass::startFirmware(const char* name) {
    DEBUG_UPDATE("OTAUpdate::startFirmware - %s\r\n", name);

    // update autostart.txt for the new firmware
    LFlash.begin();
    LFile dst = LFlash.open("autostart.txt", FILE_WRITE);
    if(!dst) {
        DEBUG_UPDATE("OTAUpdate::performUpdate - error opening autostart.txt\r\n");
        return false;
    }

    dst.seek(0);
    dst.printf("[autostart]\r\nApp=%s\r\n", name);
    dst.close();

    // reset the board
    reset();
    return true;
}
Esempio n. 4
0
boolean OTAUpdateClass::begin(const char* host, const char* port, const char* path) {
    DEBUG_UPDATE("OTAUpdate::begin - %s %s\r\n", host, path);

    // initialize our memory structures
    this->initialized = false;
    memset(this->firmware_name, 0, OTA_MAX_PATH_LEN);
    memset(this->firmware_digest, 0, DIGEST_SIZE_CHAR);
    memset(this->host, 0, OTA_MAX_PATH_LEN);
    memset(this->path, 0, OTA_MAX_PATH_LEN);
    memset(this->port, 0, OTA_MAX_PATH_LEN);
    strncpy(this->host, host, OTA_MAX_PATH_LEN-1);
    strncpy(this->path, path, OTA_MAX_PATH_LEN-1);
    strncpy(this->port, port, OTA_MAX_PATH_LEN-1);

    // read the firmware information
    LFlash.begin();
    LFile cfg = LFlash.open("autostart.txt", FILE_READ);
    if (!cfg) {
        DEBUG_UPDATE("OTAUpdateClass::begin - could not read autostart.txt\r\n");
        return false;
    }

    DEBUG_UPDATE("OTAUpdateClass::begin - reading autostart.txt\r\n");
    while (cfg.available()) {
        String line = "";
        char c = '\n';
        // read the setting part of the line
        while (cfg.available()) {
            c = cfg.read();
            line += c;
            if(c == '\n') {
                break;
            }
        }

        // look for = in the config line
        line.trim();
        int idx = line.indexOf("=");

        if(idx >= 0) {
            String setting = line.substring(0, idx);
            String value = line.substring(idx+1);

            setting.trim();
            value.trim();

            DEBUG_UPDATE("autostart.txt: %s=%s\r\n", setting.c_str(), value.c_str());
            if(setting == "App") {
                value.toCharArray(firmware_name, OTA_MAX_PATH_LEN);
                this->initialized = true;
                break;
            }
        }
    }
    cfg.close();

    if(this->initialized) {
        // we found the app name... calculate the md5 sum
        md5sum(this->firmware_name, this->firmware_digest);
        DEBUG_UPDATE("OTAUpdate::begin - %s [%s]\r\n", this->firmware_name, this->firmware_digest);
    } else {
        DEBUG_UPDATE("OTAUpdate::begin - could not find firmware name\r\n");
        return false;
    }

    return true;
}
Esempio n. 5
0
boolean OTAUpdateClass::downloadFile(const char* name) {
    // make some http requests to check for firmware updates
    LGPRSClient c;
    uint8_t buffer[DIGEST_SIZE_BUFFER];
    int n , size, max_millis;
    char buff[256];
    static char endofheader[5] ;
    boolean HTTPHeaderreached = false;
    char byc;

    //convert string to int
    String sthostport = this->port;
    unsigned int uinthostport = sthostport.toInt();

    // download the firmware
    if(!c.connect(this->host, uinthostport)) {
        DEBUG_UPDATE("OTAUpdate::downloadFile - error connecting to update host\r\n");
        return false;
    }
    // connected... send the get request
    DEBUG_UPDATE("OTAUpdate::downloadFile %s:%d 'GET /%s/%s'\r\n", this->host, uinthostport, this->path, &name[4]);

    sprintf(buff, "GET /%s/%s", this->path, &name[4]);
    c.print(buff);
    //c.printf("GET /%s/%s", this->path, &name[4]);
    c.println(" HTTP/1.1");
    c.print("Host: ");
    c.println(this->host);
    c.println("Connection: close");
    c.println();

    // save the result
    max_millis = millis() + 10000;
    LFlash.begin();
    LFlash.remove((char*) name);

    LFile ota = LFlash.open(name, FILE_WRITE);
    ota.seek(0);
    size = 0;

    // get data content of the file
    while(c.connected()) {
        //skip byte until end of HTTP Header
        if(HTTPHeaderreached == false) {
            // read byte
            byc = c.read();
            if(byc > 0) {
                max_millis = millis() + 2000;
                // if HTTP header is not reached, read until find double CRLF
                Serial.print(byc);

                // proceed a right shift of the  array
                for(int i = 0; i < 3; i++) {
                    endofheader[i] =  endofheader[i+1];
                }
                // add last received char at the end of the array
                endofheader[3] = byc;
                //don't forget null caracter
                endofheader[4] = '\0';
                // compare array with end of HTTP header key (double CRLF)
                if (strcmp("\r\n\r\n", endofheader ) == 0) {
                    // return true
                    DEBUG_UPDATE("OTAUpdate::downloadFile - end of HTTP header reached\r\n");
                    HTTPHeaderreached = true;
                }
                else {
                    HTTPHeaderreached = false;
                }
            }
            else {
                if(millis() > max_millis) {
                    DEBUG_UPDATE("OTAUpdate::downloadFile - timed out!\r\n");
                    c.stop();
                    ota.close();
                    return false;
                } else {
                    delay(100);
                }
            }
        }
        else {
            int n = c.read(buffer, 1024);
            if(n > 0) {
                max_millis = millis() + 2000;
                ota.write(buffer, n);
                size += n;
                DEBUG_UPDATE("size = %d\r", size);
            } else {
                if(millis() > max_millis) {
                    DEBUG_UPDATE("OTAUpdate::downloadFile - timed out!\r\n");
                    c.stop();
                    ota.close();
                    return false;
                } else {
                    delay(100);
                }
            }
        }
    }
    c.stop();
    ota.close();

    DEBUG_UPDATE("\r\nOTAUpdate::downloadFile - done! got %d bytes\r\n", size);
    return size > 0;
}
Esempio n. 6
0
void
PRDocument::DoAESave(
	FSSpec&		inFileSpec,
	OSType		/* inFileType */)
{

	// Validate pointers.
	
	ValidateThis_();
	ValidateObject_(mRFMap);
	ValidateObject_(mWindow);
	
	// Clear any pending actions.
	
	PostAction(nil);

	// Do we have a file already?
	
	OSErr	err;
	Boolean	oldFileIsFlat = false;

	if (mIsSpecified) {
	
		// Yes, cache its location.

		ValidateObject_(mFile);	

		FSSpec documentSpec;
		mFile->GetSpecifier(documentSpec);
				
		// Check if previous file is flat (mIsFlattened is for the new file already)
		err = ::IsFlattenedResourceFile(&documentSpec, &oldFileIsFlat);
		ThrowIfOSErr_(err);

		// First make sure we're not saving in place.
	
		if ((documentSpec.vRefNum == inFileSpec.vRefNum)
		  && (documentSpec.parID == inFileSpec.parID)
		  && (::EqualString(documentSpec.name, inFileSpec.name, false, true))) {

			// Filespecs are the same, just do a normal save.

		  	DoSave();
			return;
		}
		
		// We're saving to a different file, duplicate existing file to new filespec.

		if (mIsFlattened)
		{
			// The new file is a flattened resource file

			if (not mUnflattenedFile)
			{
				LFile	tempNewFile(inFileSpec);
				tempNewFile.CreateNewDataFile(Type_CreatorCode, Type_MacOSDocument, smSystemScript);
				mUnflattenedFile = CreateNewUnflattenedFile(&inFileSpec);
			}
			
			SaveCDEFs();							//* 2.1.2: BUG FIX #370
			
			FSSpec	unflattenedSpec;
			mUnflattenedFile->GetSpecifier(unflattenedSpec);
			
			mFile->CloseResourceFork();				// necessary for copying on some file servers
			mUnflattenedFile->CloseResourceFork();
			
			::FSpDelete(&inFileSpec);
			if (oldFileIsFlat)
			{
				// Moving data from data fork to data fork, so just use FileCopy()
				
				err = ::FileCopy(documentSpec.vRefNum, documentSpec.parID, documentSpec.name,
									inFileSpec.vRefNum, inFileSpec.parID, nil, inFileSpec.name,
									nil, 0, true);

				OpenResourceFile(mUnflattenedFile);	// reopen original file's resource fork
				mRFMap->SetMainFile(mUnflattenedFile);
				if (err)
					Throw_(err);
			}
			else
			{
				// Moving data from resource fork to data fork, so use CopyFork()
				
				LFile	tempNewFile(inFileSpec);
				tempNewFile.CreateNewDataFile(Type_CreatorCode, Type_MacOSDocument, smSystemScript);

				SInt16	srcRefNum;
				SInt16	destRefNum;

				StPointerBlock	buffer(bigCopyBuffSize, false, false);
				if (not buffer.IsValid())
				{
					StPointerBlock	smallBuffer(minCopyBuffSize, true, false);
					buffer.Adopt(smallBuffer.Release());
				}
				
				srcRefNum = mFile->OpenResourceFork(fsRdPerm);
				destRefNum = tempNewFile.OpenDataFork(fsRdWrPerm);
				
				ThrowIfOSErr_(::CopyFork(srcRefNum, destRefNum, buffer, ::GetPtrSize(buffer)));
				
				mUnflattenedFile = CreateNewUnflattenedFile(&inFileSpec);

				OpenResourceFile(mFile);				// reopen original file's resource fork
				mRFMap->SetMainFile(mFile);
			}
		}
		else
		{
			// The new file is a regular resource file

			SaveCDEFs();							//* 2.1.2: BUG FIX #370
			mFile->CloseResourceFork();				// necessary for copying on some file servers
			::FSpDelete(&inFileSpec);

			if (oldFileIsFlat)
			{
				// Copy mUnflattenedFile to new regular resource file
				FSSpec	unflattenedSpec;
				mUnflattenedFile->GetSpecifier(unflattenedSpec);
				mUnflattenedFile->CloseResourceFork();	// necessary for copying on some file servers
				err = ::FileCopy(unflattenedSpec.vRefNum, unflattenedSpec.parID, unflattenedSpec.name,
									inFileSpec.vRefNum, inFileSpec.parID, nil, inFileSpec.name,
									nil, 0, true);

				OpenResourceFile(mUnflattenedFile);		// reopen original file's resource fork
				mRFMap->SetMainFile(mUnflattenedFile);
				if (err)
					Throw_(err);
			}
			else
			{
				// Copy mFile to new regular resource file

				err = ::FileCopy(documentSpec.vRefNum, documentSpec.parID, documentSpec.name,
									inFileSpec.vRefNum, inFileSpec.parID, nil, inFileSpec.name,
									nil, 0, true);

				OpenResourceFile(mFile);				// reopen original file's resource fork
				mRFMap->SetMainFile(mFile);
				if (err)
					Throw_(err);
			}
		}
	}
	else
	{
		// No pre-existing file, make sure we start from an empty document.
	
		err = ::FSpCreate(&inFileSpec, GetCreatorCode(),
									  GetFileTypeCode(), smSystemScript);
		if (err == dupFNErr) {
		
			// File already exists, delete it and try again.
		
			ThrowIfOSErr_(::FSpDelete(&inFileSpec));
			ThrowIfOSErr_(::FSpCreate(&inFileSpec, GetCreatorCode(),
											GetFileTypeCode(), smSystemScript));
		}
		else
			ThrowIfOSErr_(err);
	
		// Add this new file to the recent items menu
		ProcessCommand(cmd_AddFileToRecentItems, &inFileSpec);
	}

	// Make sure there's a resource fork.
	
		// NOTE: This is safe. FSpCreateResFile is defined as a no-op in case the 
		// resource fork already exists.

	// We have already taken care of mUnflattenedFile having a resource fork
	if (not oldFileIsFlat and not mIsFlattened)
	{
		::FSpCreateResFile(&inFileSpec, GetCreatorCode(), GetFileTypeCode(), smSystemScript);
		err = ::ResError();
		if (err != dupFNErr)				// resource fork already exists
			ThrowIfOSErr_(err);
	}

	// Try saving to this file.
	
	LFile* newFile = nil;
	try {
	
		if (mIsFlattened)
		{
			// Create a new file & update resource context.
		
			newFile = new LFile(inFileSpec);
			ValidateObject_((LFile*) newFile);

			mUnflattenedFile = CreateNewUnflattenedFile(&inFileSpec);
			ValidateObject_(mUnflattenedFile);

			OpenResourceFile(mUnflattenedFile);
			mRFMap->SetMainFile(mUnflattenedFile);
		
			// Now save as though we already had the file open.
			
			RawSave(inFileSpec, inFileSpec);
			
			// Set file type/creator for this file.
			
			::FSpChangeCreatorType(&inFileSpec, GetCreatorCode(), GetFileTypeCode());
			
			// Copy the unflattened resource fork over to the flat data fork
			StPointerBlock	buffer(bigCopyBuffSize, false, false);
			if (not buffer.IsValid())
			{
				StPointerBlock	smallBuffer(minCopyBuffSize, true, false);
				buffer.Adopt(smallBuffer.Release());
			}

			SInt16	srcRefNum;
			SInt16	destRefNum;

			srcRefNum = mUnflattenedFile->OpenResourceFork(fsRdPerm);
			destRefNum = newFile->OpenDataFork(fsRdWrPerm);

			err = ::CopyFork(srcRefNum, destRefNum, buffer, ::GetPtrSize(buffer));

		}
		else
		{
			// Create a new file & update resource context.
		
			newFile = new LFile(inFileSpec);
			ValidateObject_((LFile*) newFile);

			OpenResourceFile((LFile*)newFile);
			mRFMap->SetMainFile((LFile*)newFile);
		
			// Now save as though we already had the file open.
			
			RawSave(inFileSpec, inFileSpec);
			
			// Set file type/creator for this file.
			
			::FSpChangeCreatorType(&inFileSpec, GetCreatorCode(), GetFileTypeCode());
		}
	}
	catch(...) {
	
		// Delete new file.
		
		if (newFile != nil) {
			ValidateObject_((LFile*) newFile);
			delete (LFile*)newFile;
		}
		::FSpDelete(&inFileSpec);
		
		// Revert to original resource context.
		
		mRFMap->SetMainFile(mFile);

		// Rethrow the exception.

		#if SKIPOMPARSE
			throw;
		#endif
			
	}

	// Now that we're done, get rid of old file reference.

	if (mFile != nil) {
		ValidateObject_(mFile);
		delete mFile;
	}
	mFile = (LFile*)newFile;
	
	// Update all window titles.
	
	mIsSpecified = true;
	mWindow->SetDescriptor(inFileSpec.name);
	
}
Esempio n. 7
0
HRESULT ProfileInfo::Write(LPCTSTR szFilename) {
    HRESULT hr = S_OK;

    if (szFilename == NULL && m_csFilename.IsEmpty()) {
        HKEY hKey = HKEY_LOCAL_MACHINE;

        bool bIsUserAdmin = LMisc::IsUserAdmin();
        if (!bIsUserAdmin)
            hKey = HKEY_CURRENT_USER;
        // TODO this does not reflect "elevation" on Windows Vista/7 (not admin but can become one)

        CString csProfileDirectory;
        hr = ProfileUtils::GetProfileDirectory(hKey, csProfileDirectory, true);

        ProfileInfo *pInfo = ProfileUtils::GetProfileWithID(m_iProfileID);
        if (pInfo) {
            CString csFileToDelete = pInfo->GetFilename();
            CString csFilePath = csFileToDelete;
            StringManipulation::GetPath(csFilePath);
            if (csFilePath == csProfileDirectory)
                DeleteFile(csFileToDelete);
            else 
                ProfileUtils::GetNewProfileID(m_iProfileID);
            delete pInfo;
        } 

        if (SUCCEEDED(hr))
            m_csFilename.Format(_T("%s\\Profile_%d_%I64u.lpp"), csProfileDirectory, m_iProfileType, m_iProfileID);
    }

    CString csFilename = m_csFilename;
    if (SUCCEEDED(hr) && szFilename != NULL)
        csFilename = szFilename;

    LURESULT lr = S_OK;
    LFile *pProfileFile = NULL;
    if (SUCCEEDED(hr)) {
        pProfileFile = new LFile(csFilename);
        if (pProfileFile == NULL)
            hr = E_PM_FILE_CREATE;
    }

    if (SUCCEEDED(hr)) {
        lr = pProfileFile->Create(LFILE_TYPE_TEXT_UNICODE, TRUE);
        if (lr != S_OK)
            hr = E_PM_FILE_CREATE;
        if (!pProfileFile->Exists())
            hr = E_PM_FILE_NOTEXIST;
    }

    CString csLine;
    if (SUCCEEDED(hr)) {
        csLine.Format(_T("lpp_version=%d\n"), m_iProfileVersion);
        lr = pProfileFile->WriteText(csLine, csLine.GetLength());
        if (lr != S_OK)
            hr = E_PM_FILE_WRITE;
    }

    if (SUCCEEDED(hr)) {
        csLine.Format(_T("lpp_id=%I64d\n"), m_iProfileID);
        lr = pProfileFile->WriteText(csLine, csLine.GetLength());
        if (lr != S_OK)
            hr = E_PM_FILE_WRITE;
    }

    if (SUCCEEDED(hr)) {
        csLine.Format(_T("lpp_title=%s\n"), m_csTitle);
        lr = pProfileFile->WriteText(csLine, csLine.GetLength());
        if (lr != S_OK)
            hr = E_PM_FILE_WRITE;
    }

    if (SUCCEEDED(hr)) {
        csLine.Format(_T("lpp_type=%d\n"), m_iProfileType);
        lr = pProfileFile->WriteText(csLine, csLine.GetLength());
        if (lr != S_OK)
            hr = E_PM_FILE_WRITE;
    }

    if (SUCCEEDED(hr)) {
        for (int i = 0; i < m_aValues.GetSize() && SUCCEEDED(hr); ++i) {
            csLine.Format(_T("%s=%s\n"), m_aKeys[i], m_aValues[i]);
            lr = pProfileFile->WriteText(csLine, csLine.GetLength());
            if (lr != S_OK)
                hr = E_PM_FILE_WRITE;
        }
    }

    if (pProfileFile) {
        pProfileFile->Close();
        delete pProfileFile;
    }

    return hr;
}