bool removeFileInDir(const char* d, const char* fname) {

    WIN32_FIND_DATA FileData;
    HANDLE hFind;

    wchar_t toFind    [512];
    wchar_t szNewPath [512];
    bool ret = false;

    DWORD dwAttrs;
    BOOL fFinished = FALSE;

    WCHAR* dir      = toWideChar(d);

    if (fname) {
        WCHAR* filename = toWideChar(fname);
        wsprintf(toFind, TEXT("%s/%s"), dir, filename);
        delete [] filename;
        filename = NULL;
    }
    else {
        wsprintf(toFind, TEXT("%s/*.*"), dir);
    }

    hFind = FindFirstFile(toFind, &FileData);

    if (hFind != INVALID_HANDLE_VALUE) {
        while (!fFinished) {

            wsprintf(szNewPath, TEXT("%s/%s"), dir, FileData.cFileName);
            dwAttrs = GetFileAttributes(szNewPath);
            if (dwAttrs == FILE_ATTRIBUTE_DIRECTORY) { }
            // do anything for subdirectory
            else {
                DeleteFile(szNewPath);
            }

            if (!FindNextFile(hFind, &FileData)) {
                if (GetLastError() == ERROR_NO_MORE_FILES) {
                    fFinished = TRUE;
                }
                else  {
                    goto finally;
                }
            }
        }

        FindClose(hFind);
    }

    ret = true;

finally:
    if (dir) {
        delete [] dir;
    }
    return ret;
}
/*
 * Sets a property value.
 *
 * @param property - the property name
 * @param value - the property value (zero terminated string)
 */
void DeviceManagementNode::setPropertyValue(const char* prop, const char* value) {
    if ((prop == NULL) || (value == NULL)) {
        return;
    }

    HKEY key;
    DWORD res;
    TCHAR *p = NULL;
    TCHAR *v = NULL;

    RegCreateKeyEx(
            HKEY_DM_ROOT,
            fullContext,
            0,
            NULL,
            REG_OPTION_NON_VOLATILE,
            KEY_ALL_ACCESS,
            NULL,
            &key,
            &res
            );


    if (key == 0) {
        //lastErrorCode = ERR_INVALID_CONTEXT;
        //sprintf(lastErrorMsg, "Invalid context path: %s", fullContext);
        setErrorF(ERR_INVALID_CONTEXT, "Invalid context path: %s", fullContext);
        goto finally;
    }

    p = toWideChar(prop);
    v = toWideChar(value);

    RegSetValueEx(
            key,
            p,
            NULL,
            REG_SZ,  // we currently support only strings
            (UCHAR*)v,
            (wcslen(v)+1)*sizeof(WCHAR)
            );

    delete [] p;
    delete [] v;
    RegFlushKey(key);
finally:

    if (key != 0) {
        RegCloseKey(key);
    }
}
示例#3
0
bool saveFile(const char *filename, const char *buffer, size_t len, bool binary) 
{
    bool ret = false;

    // Convert to wide-char to be compatible with international chars.
    // If using char and UTF-8, fopen() is not working correctly and
    // will fail with special chars. (with UTF-8... why?)
    // So we use _wfopen() and a wide-char path.
    const WCHAR* mode = binary ? TEXT("wb") : TEXT("w");
    WCHAR* wpath = toWideChar(filename);

    FILE *f = _wfopen(wpath, mode);
    if(!f) {
        goto finally;
    }

    if (fwrite(buffer, sizeof(char), len, f) != len) {
        fclose(f);
        goto finally;
    }
    fclose(f);
    ret = true;

finally:
    delete [] wpath;
    return ret;
}
    /// Loads data for testing the 'testFileName' file.
    void loadTestFileData(const char* testFileName) {

        fileName = getTestFileFullPath(SAMPLE_FILES_DIR, testFileName);
        const char* fileContent = loadTestFile(SAMPLE_FILES_DIR, testFileName, true);  // must be binary mode!
        int fileSize = (int)fgetsize(fileName.c_str());

        const WCHAR* wtestFileName = toWideChar(testFileName);
        
        FileData fileData;
        fileData.setName(wtestFileName);
        fileData.setSize(fileSize);
        fileData.setBody(fileContent, fileSize);

        unsigned long tstamp = getFileModTime(fileName);
        StringBuffer modTime = unixTimeToString(tstamp, true);  // file's mod time is already in UTC
        WString wmodTime;
        wmodTime = modTime;
        fileData.setModified(wmodTime);

        fileDataContent = fileData.format();
        fileDataSize = (int)strlen(fileDataContent);

        delete [] wtestFileName;
        delete [] fileContent;
    }
示例#5
0
文件: Log.cpp 项目: ruphy/kfunambol
winLog::winLog(bool resetLog, const char* path, const char* name) {

    setLogPath(path);
    setLogName(name);

    // MUST use a wchar_t* logDir to manage correctly international chars.
    // If using char* logDir and UTF-8, fopen() is not working correctly and
    // will fail to open the log file. (with UTF-8... why?)
    // So we use _wfopen() and a wchar_t* logDir.
    StringBuffer logDir;
    logDir.sprintf("%s\\%s", logPath.c_str(), logName.c_str());
    WCHAR* tmp = toWideChar(logDir.c_str());
    wlogDir = tmp;
    delete [] tmp;

    //
    // Test to ensure the log file is writable (only if path is set)
    //
    if (path) {
        logFile = _wfopen(wlogDir.c_str(), TEXT("a+"));
        if (logFile == NULL) {
            WCHAR tmp[512];
            wsprintf(tmp, TEXT("Unable to write log file: \"%s\".\nPlease check your user's permissions."), wlogDir.c_str());
            MessageBox(NULL, tmp, TEXT("Funambol"), MB_SETFOREGROUND | MB_OK);
        }
        else {
            fclose(logFile);

            if (resetLog) {
                reset(FUNAMBOL_HEADER);
            }
        }
    }
}
wstring formatDate(StringBuffer& date) {
    
    wstring dd(TEXT(""));
    wchar_t* wdate = toWideChar(date);
    if (wdate == NULL) {
        return dd;
    }
    wchar_t data[80];
    wchar_t formatDate[80];
    int found = 0;
    SYSTEMTIME timeDest;
    swscanf_s(wdate, L"%4d%2d%2d", &timeDest.wYear, &timeDest.wMonth, &timeDest.wDay);
    
    GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SLONGDATE, data, 80);

    dd = data;            
    if ((found = dd.find(TEXT("dddd, "))) != wstring::npos) {
        dd.replace(found, 6, TEXT(""));
    } else if ((found = dd.find(TEXT("dddd,"))) != wstring::npos) {
        dd.replace(found, 5, TEXT(""));
    }else if ((found = dd.find(TEXT("dddd"))) != wstring::npos) {
        dd.replace(found, 4, TEXT(""));
    }

    trim(dd);            
    GetDateFormat(LOCALE_USER_DEFAULT, NULL, &timeDest, dd.c_str(), formatDate, 80); 
    dd = formatDate;
    return dd;
}
示例#7
0
FILE* fileOpen(const char* filename, const char* mode) {

    if (!filename || !mode) {
        return NULL;
    }

    const WCHAR* wfilename = toWideChar(filename);
    const WCHAR* wmode     = toWideChar(mode);

    // MUST use a wchar_t* to manage correctly international chars.
    // If using char* and UTF-8, fopen() is not working correctly and
    // will fail to open the file, on Windows platform.
    FILE* f = _wfopen(wfilename, wmode);

    delete [] wfilename;
    delete [] wmode;
    return f;
}
END_TEST

/**
* Removed the STATUS from the winevent parser
*/
BEGIN_TEST(WinEventNoSTATUS)
{
    int ret = 0;
    SyncItem* item = NULL;
    WCHAR* internalKey = NULL;
    wstring propValue; 

    WindowsSyncSource* ss = createAppointmentWindowsSyncSource();   
    WIN_ASSERT_NOT_NULL(ss, TEXT("The syncSource is null."));

    StringBuffer VCal;
    VCal.append("BEGIN:VCALENDAR\r\n");
    VCal.append("VERSION:1.0\r\n");
    VCal.append("BEGIN:VEVENT\r\n");
    VCal.append("X-FUNAMBOL-FOLDER:DEFAULT_FOLDER\r\n");
    VCal.append("X-FUNAMBOL-ALLDAY:1\r\n");
    VCal.append("DTSTART:20110407\r\n");
    VCal.append("DTEND:20110408\r\n");
    VCal.append("X-MICROSOFT-CDO-BUSYSTATUS:FREE\r\n");
    VCal.append("CATEGORIES:\r\n");
    VCal.append("DESCRIPTION:\r\n");
    VCal.append("LOCATION:Roma\r\n");
    VCal.append("PRIORITY:1\r\n");
    VCal.append("STATUS:NEED ACTION\r\n");
    VCal.append("X-MICROSOFT-CDO-REPLYTIME:\r\n");
    VCal.append("SUMMARY;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:Da test\r\n");
    VCal.append("CLASS:PUBLIC\r\n");
    VCal.append("AALARM:20110406T060000Z;;0;\r\n");
    VCal.append("RRULE:\r\n");
    VCal.append("X-FUNAMBOL-BILLINGINFO:\r\n");
    VCal.append("X-FUNAMBOL-COMPANIES:\r\n");
    VCal.append("X-FUNAMBOL-MILEAGE:\r\n");
    VCal.append("X-FUNAMBOL-NOAGING:0 \r\n");
    VCal.append("END:VEVENT\r\n");
    VCal.append("END:VCALENDAR");

    item = new SyncItem(TEXT("GUID"));
    item->setData(VCal.c_str(), VCal.length());
    
    WCHAR* tt = toWideChar(VCal.c_str());

    WinEvent d(tt);
    printf("%S", d.toString().c_str());        

    // insert test item
    ret = ss->addItem(*item);
    WIN_ASSERT_EQUAL(ret, 201, TEXT("Adding item is not correct"));    
    internalKey = (WCHAR*)item->getKey();        
    
    delete item;
    delete ss;
}
示例#9
0
文件: Log.cpp 项目: ruphy/kfunambol
void winLog::setLogPath(const char* configLogPath) {

    if (configLogPath != NULL) {
        logPath = configLogPath;
    } else {
        logPath = ".";
    }
    if (logName.length() > 0){
        StringBuffer logDir;
        logDir.sprintf("%s\\%s", logPath.c_str(), logName.c_str());
        WCHAR* tmp = toWideChar(logDir.c_str());
        wlogDir = tmp;
        delete [] tmp;
    }
}
示例#10
0
文件: Log.cpp 项目: ruphy/kfunambol
void winLog::setLogName(const char* configLogName) {

    if (configLogName != NULL) {
        logName = configLogName;
    }
    else {
        logName = LOG_NAME;
    }
    if (logPath){
        StringBuffer logDir;
        logDir.sprintf("%s\\%s", logPath.c_str(), logName.c_str());
        WCHAR* tmp = toWideChar(logDir.c_str());
        wlogDir = tmp;
        delete [] tmp;
    }
}
示例#11
0
int stat(const char* filename, struct stat* Stat) {
    
    int ret = -1;
    DWORD lpFileSizeHigh    = 0;
    DWORD dwSize            = 0;
    WCHAR* wfile            = NULL;

    if (filename == NULL) {
        LOG.error("wm stat: the filename is null");
        goto finally;
    }    
    WIN32_FILE_ATTRIBUTE_DATA wdata;
    wfile = toWideChar(filename);    
    
    BOOL res = GetFileAttributesEx(wfile, GetFileExInfoStandard, &wdata);
    
    if (res == 0) {
        LOG.error("wm error in GetFileAttributesEx: %i", GetLastError());
        goto finally;
    }

    Stat->st_mode =  (unsigned short)wdata.dwFileAttributes;
    Stat->st_mtime = FileTimeToTime_t(wdata.ftLastWriteTime);  // only write: it is the modification
    Stat->st_atime = FileTimeToTime_t(wdata.ftLastAccessTime); // both read/write
    Stat->st_ctime = FileTimeToTime_t(wdata.ftCreationTime); 
    Stat->st_size = wdata.nFileSizeLow;
    if (Stat->st_size == 0xFFFFFFFF) {
        Stat->st_size = 0;
        LOG.info("wm: the filesize low is 0xFFFFFFFF");
    } 

    ret = 0;

finally:
    
    if (ret == -1) {
        Stat->st_atime = 0;
        Stat->st_ctime = 0;
        Stat->st_mode  = 0;
        Stat->st_mtime = 0;
        Stat->st_size = -1;
    }
    
    delete [] wfile;

    return ret;
}
void UpdateManager::startUpgrade(const UpdaterConfig& config) {

    SHELLEXECUTEINFO lpExecInfo;
    memset(&lpExecInfo, 0, sizeof(SHELLEXECUTEINFO));
    lpExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);    
    
    wchar_t* site = toWideChar(config.getUrlUpdate().c_str());
    lpExecInfo.lpFile = site;
    lpExecInfo.nShow = SW_SHOWNORMAL;
    lpExecInfo.lpVerb = TEXT("open");
    ShellExecuteEx(&lpExecInfo);
    
    if (site) { 
        delete [] site; 
        site = NULL; 
    }
}
示例#13
0
    SyncSource *createSource(int source, const char *trackingSuffix) {
        class RawFileSyncSourceWithReport : public RawFileSyncSource {
        public:
            RawFileSyncSourceWithReport(const char* nodeName, const WCHAR* name, SyncSourceConfig* sc) :
                RawFileSyncSource(name, sc),
                fileNode(nodeName) {
                setReport(&report);
                setFileNode(&fileNode);
                /*
                 * Keeping track if changes is done via time() with a resolution of seconds.
                 * Sleep a bit to ensure that enough time passes.
                 */
#ifdef WIN32
        Sleep(1000);
#else
                sleep(1);
#endif
            }
        private:
            SyncSourceReport report;
            DeviceManagementNode fileNode;
        };

        CPPUNIT_ASSERT(source < (int)sources.size());
        ManagementNode *sourceNode = config->getSyncSourceNode(sources[source].c_str());
        CPPUNIT_ASSERT(sourceNode);
        char *fullName = sourceNode->createFullName();
        std::string nodeName = std::string(fullName) + "/changes_" + trackingSuffix;
        std::string dirName = sources[source] + "_" + clientID;
        WCHAR *name = toWideChar(sources[source].c_str());
        delete [] fullName;
        FileSyncSource *ss = new RawFileSyncSourceWithReport(
            nodeName.c_str(),
            name,
            config->getSyncSourceConfig(sources[source].c_str()));
        delete [] name;
#ifdef WIN32
        _mkdir(dirName.c_str());
#else
    mkdir(dirName.c_str(), S_IRWXU);
#endif
        ss->setDir(dirName.c_str());

        return ss;
    }
示例#14
0
/**
 * Return the next SyncItem of updated one. It is used in case of fast sync
 * and retrieve the new data source content.
 */
SyncItem* CacheSyncSource::getNextDeletedItem() {
    
    SyncItem* syncItem = NULL;
    if (deletedKeys && deletedKeys->hasMoreElement()) {
        StringBuffer* s     = (StringBuffer*)deletedKeys->getNextElement();  
        if (!s) {
            return NULL;
        }
        WCHAR* wkey = toWideChar(s->c_str());
        syncItem = new SyncItem(wkey); 
        if (wkey) { delete [] wkey; wkey = NULL; }  
    }
    if (!syncItem) {
        LOG.info("There are no more deleted items to be exchanged. Return NULL");     
    }    
         
    return syncItem;
}
    void testExtSetters(){
	   const WCHAR* accountIdw = NULL;
	   const char* accountId = NULL;
       MailAccount account;

       account.parse(ACCOUNT_FOLDER);
       account.setVisibleName(_VISIBLENAME);
       account.setEmailAddress(_EMAILADDRESS);
       account.setProtocol(_PROTOCOL);
       account.setUsername(_USERNAME);
       account.setPassword(_PASSWORD);
       account.setInServer(_IN_SERVER);
       account.setOutServer(_OUT_SERVER);
       account.setInPort(_IN_PORT);
       account.setOutPort(_OUT_PORT);
       account.setInSSL(_IN_SSL);
       account.setOutSSL(_OUT_SSL);
       account.setSignature(_SIGNATURE);
       account.setDomainName(_DOMAINNAME);

	   accountIdw = toWideChar(_ID);
       account.setID(accountIdw);
	   delete [] accountIdw;

	   accountId = toMultibyte(account.getID());

       CPPUNIT_ASSERT( strcmp(account.getVisibleName(),     _VISIBLENAME)   == 0 );
       CPPUNIT_ASSERT( strcmp(account.getEmailAddress(),    _EMAILADDRESS)  == 0 );
       CPPUNIT_ASSERT( strcmp(account.getProtocol(),        _PROTOCOL)      == 0 );
       CPPUNIT_ASSERT( strcmp(account.getUsername(),        _USERNAME)      == 0 );
       CPPUNIT_ASSERT( strcmp(account.getPassword(),        _PASSWORD)      == 0 );
       CPPUNIT_ASSERT( strcmp(account.getInServer(),        _IN_SERVER)     == 0 );
       CPPUNIT_ASSERT( strcmp(account.getOutServer(),       _OUT_SERVER)    == 0 );
       CPPUNIT_ASSERT( strcmp(account.getInPort(),          _IN_PORT)       == 0 );
       CPPUNIT_ASSERT( strcmp(account.getOutPort(),         _OUT_PORT)      == 0 );
       CPPUNIT_ASSERT( strcmp(account.getInSSL(),           _IN_SSL)        == 0 );
       CPPUNIT_ASSERT( strcmp(account.getOutSSL(),          _OUT_SSL)       == 0 );
       CPPUNIT_ASSERT( strcmp(account.getSignature(),       _SIGNATURE)     == 0 );
       CPPUNIT_ASSERT( strcmp(account.getDomainName(),      _DOMAINNAME)    == 0 );
       CPPUNIT_ASSERT( strcmp(accountId,					_ID)            == 0 );

	   delete [] accountId;
    }
END_TEST


WinContact* updateOutlookItem(WindowsSyncSource* ss, SyncItem* item) {
    
    int ret = ss->updateItem(*item);
    WIN_ASSERT_EQUAL(ret, 200, TEXT("Update item is not correct"));
    wstring keyModified = item->getKey();

    SyncItem* itemTmp = ss->getItemFromId(keyModified.c_str());
    WIN_ASSERT_NOT_NULL(item, TEXT("The item retrieved from the backend is null."));

    WCHAR* wcon = toWideChar((const char*)itemTmp->getData());
    wstring wcontact(wcon);
    delete [] wcon;
   
    WinContact* winC = new WinContact(wcontact);
    return winC;

}
bool readFile(const char* path, char **message, size_t *len, bool binary)
{
    bool ret = false;
    FILE *f;
    size_t msglen=0;
    char *msg=0;

    // Convert to wide-char to be compatible with international chars.
    // If using char and UTF-8, fopen() is not working correctly and
    // will fail with special chars. (with UTF-8... why?)
    // So we use _wfopen() and a wide-char path.
    const WCHAR* mode = binary ? TEXT("rb") : TEXT("r");
    WCHAR* wpath = toWideChar(path);

    f = _wfopen(wpath, mode);
    if ( !f ) {
        goto finally;
    }
    msglen = fgetsize(f);
    msg = new char[msglen+1];

    *len=fread(msg, sizeof(char), msglen, f);
    if(ferror(f)) {
        delete [] msg;
        goto finally;
    }
    fclose(f);

    // Terminate the read msg
    msg[*len] = 0;

    // Set return parameters
    *message= msg ;
    //*len=msglen;
    ret = true;

finally:
    delete [] wpath;
    return ret;
}
示例#18
0
/**
 * Creates a folder, and all needed folders. 
 * @return 0 on success, -1 otherwise.
 */
int createFolder(const char *path) {
    wchar_t *wpath=toWideChar(path);
    wchar_t *tpath=0;
    wchar_t tsep=0;
    int ret = 0;
    BOOL success = 0;

    // Skip C:/
    tpath = wcschr(wpath, ':');
    if(tpath){
        tpath++;
    }
    else {
        tpath = wpath;
    }
    // Create upper folders
    while( (tpath=wcspbrk(tpath+1, TEXT("\\/"))) ) {
        tsep=*tpath;
        *tpath=0;
        success = CreateDirectory(wpath, NULL);
        *tpath=tsep;

        if(!success && GetLastError() != ERROR_ALREADY_EXISTS) {
            LOG.error("createFolder: error creating folder %s", path);
            ret = -1;
            break;
        }
    }
    // Create last folder
    if (ret == 0) {
        success = CreateDirectory(wpath,NULL);
        if(!success && GetLastError() != ERROR_ALREADY_EXISTS) {
            LOG.error("createFolder: error creating folder %s", path);
            ret = -1;
        }
    }
    delete [] wpath;
    return ret;
}
示例#19
0
SyncItem* CacheSyncSource::fillSyncItem(StringBuffer* key) {
    
    SyncItem* syncItem  = NULL;    
    size_t size         = 0;
    void* content       = NULL;
    
    if (!key) {
        return NULL;
    }
    
    LOG.debug("[%s] Filling item with key %s", getName(), key->c_str());
    
    content = getItemContent((*key), &size);
    
    WCHAR* wkey = toWideChar(key->c_str());
    syncItem = new SyncItem(wkey);
    syncItem->setData(content, size);
    
    if (wkey) { delete [] wkey; wkey = NULL; }
    if (content) { delete [] (char*)content; content = NULL; }

    return syncItem;

}
示例#20
0
StringBuffer MailMessage::decodeHeader(StringBuffer line) {

    if (!line || line.empty()) {
        return line;
    }

    size_t startPos = 0;
    StringBuffer ret;
    StringBuffer charset;
    while( (startPos = line.find("=?", startPos)) != StringBuffer::npos) {
        // Skip the '=?'
        startPos += 2;
        // Find the first '?'
        size_t firstMark = line.find("?", startPos);
        if (firstMark == StringBuffer::npos) {
            LOG.error("Invalid encoded header");
            return line;
        }
        // Find the second '?'
        size_t secondMark = line.find("?", firstMark+1);
        if (secondMark == StringBuffer::npos) {
            LOG.error("Invalid encoded header");
            return line;
        }
        // Find the final '?='
        size_t endPos = line.find("?=", secondMark+1);
        if (endPos == StringBuffer::npos) {
            LOG.error("Invalid encoded header");
            return line;
        }

        charset = line.substr(startPos, firstMark - startPos);
        StringBuffer encoding = line.substr(firstMark+1, secondMark - (firstMark + 1));
        StringBuffer text = line.substr(secondMark+1, endPos - (secondMark + 1));

        if (encoding.icmp("Q")) {
            // quoted-printable
            text.replaceAll("_", " ");
            char* dec = qp_decode(text);
            if (startPos >= 2 &&  ret.length() == 0) {
                ret += line.substr(0, startPos - 2);
            }

            ret += dec;
            delete [] dec;
        }
        else if (encoding.icmp("B")){
        // base64
            char* dec = new char[text.length()];
            int len = b64_decode((void *)dec, text);
            dec[len]=0;
            if (startPos >= 2 &&  ret.length() == 0) {
                ret += line.substr(0, startPos - 2);
            }
            ret += dec;
            delete [] dec;
        }

        startPos = endPos;
    }

    if (ret.length() == 0) {
        ret += line;
    }

    WCHAR* wret = toWideChar(ret, charset);
    ret.set(NULL);
    char* t = toMultibyte(wret);
    ret.set(t);
    if (wret) {delete [] wret;}
    if (t) {delete [] t;}
    return ret;
}
示例#21
0
bool VConverter::readFieldBody(WCHAR* buffer, VProperty* vprop) {

    int i      = 0;
    int j      = 0;
    int len    = 0;
    int offset = 0;
    bool ret   = false;
    WCHAR* value     = NULL;
    WCHAR* allValues = NULL;
    WCHAR* c         = NULL;

    // Get length of all values
    while (buffer[i] != '\0') {
        if ((buffer[i] == '\r') || buffer[i] == '\n') {

            // Get offset of next property
            for (j=i+1; buffer[j] != '\0'; j++) {
                if((buffer[j] != '\r') && (buffer[j] != '\n'))
                    break;
            }
            offset = j;
            break;
        }
        i++;
    }
    len = i;


    if (!len) {
        // This field is empty, we MUST consider it adding an empty value
        // so any value on client will be deleted.
        vprop->addValue(TEXT(""));
        ret = true;
        goto finally;
    }

    // This is a string with all values for this property (to parse)
    allValues = new WCHAR[len + 1];
    wcsncpy(allValues, buffer, len);
    allValues[len] = 0;


    //
    // If needed, decode QP string and copy to 'allValues'.
    //
    if(vprop->equalsEncoding(TEXT("QUOTED-PRINTABLE"))) {

        char* buf = toMultibyte(allValues);
        char* dec = qp_decode(buf);
        len = strlen(dec);
        delete [] buf;

        if (dec) {
            char* t = toMultibyte(vprop->getParameterValue(TEXT("CHARSET")));
            WCHAR* wdecoded = toWideChar(dec, t);
            delete [] dec;
            delete [] t;

            if (wdecoded) {
                wcsncpy(allValues, wdecoded, len);
                allValues[len] = 0;
                delete [] wdecoded;
            }
        }
        if (!len) {
            goto finally;
        }
    }

    /*
    --- base64 is not decoded ----
    IT IS NOT POSSIBLE TO DECODE BASE64 PARAMETERS IN A WCHAR
    AND TAKE THE LENGHT OF A BINARY!!
    */

    // This is a buffer for each single value
    value = new WCHAR[len + 1];
    wcscpy(value, TEXT(""));

    //
    // Extract values and add to Vproperty
    //
    j=0;
    c = allValues;
    for (i=0; i<len; i++) {

        // End of value
        if (c[i] == ';') {
            vprop->addValue(value);
            j = 0;
            wcscpy(value, TEXT(""));
        }

        else {
            // Manage escaped chars: jump back-slash
            if (c[i] == '\\') {
                if (c[i+1]=='n') {
                    // none: this is "\n" sequence (formatted line ending for 3.0)
                }
                else {
                    i++;
                    if (c[i] == '\0')
                        break;
                }
            }
            value[j] = c[i];
            j++;
            value[j] = '\0';
        }
    }

    vprop->addValue(value);
    ret = true;

finally:

    // Shift buffer for next property to parse
    //wcscpy(buffer, buffer+offset);
    memmove(buffer, buffer+offset, (wcslen(buffer+offset) + 1)*sizeof(*buffer));

    if (value) {
        delete [] value;     value = NULL;
    }
    if (allValues) {
        delete [] allValues; allValues = NULL;
    }

    return ret;
}
void MailSourceManagementNode::getMailAccounts()
{
    char nname[512];
    char* tmp;
    char* fullcontext = toMultibyte(getFullContext());
    sprintf(nname, "%s/%s", fullcontext , PROPERTY_MAIL_ACCOUNT_ROOT);
    DeviceManagementNode* dmn = new DeviceManagementNode(nname);
    int numchild = dmn->getChildrenMaxCount();
    char** accountNames = dmn->getChildrenNames();

    for ( int p = 0; p<numchild; p++){
        MailAccount ma;
        char valname[512];
        char fullname[512];
        sprintf(fullname, "%s/%s",  fullcontext, PROPERTY_MAIL_ACCOUNT_ROOT);
        const char* name = stringdup(accountNames[p]);
        DeviceManagementNode* mn = new DeviceManagementNode(fullname,name);

        ma.setName(name);

        sprintf(valname,PROPERTY_MAIL_ACCOUNT_VISIBLE_NAME,name);
        tmp = mn->readPropertyValue(valname);
        ma.setVisibleName(tmp); safeDel(&tmp);
        sprintf(valname,PROPERTY_MAIL_ACCOUNT_EMAILADDRESS,name);
        tmp = mn->readPropertyValue(valname);
        ma.setEmailAddress(tmp); safeDel(&tmp);
        sprintf(valname,PROPERTY_MAIL_ACCOUNT_PROTOCOL,name);
        tmp = mn->readPropertyValue(valname);
        ma.setProtocol(tmp); safeDel(&tmp);
        sprintf(valname,PROPERTY_MAIL_ACCOUNT_USERNAME,name);
        tmp = mn->readPropertyValue(valname);
        ma.setUsername(tmp); safeDel(&tmp);
        sprintf(valname,PROPERTY_MAIL_ACCOUNT_PASSWORD,name);
        tmp = mn->readPropertyValue(valname);
        ma.setPassword(tmp); safeDel(&tmp);
        sprintf(valname,PROPERTY_MAIL_ACCOUNT_IN_SERVER,name);
        tmp = mn->readPropertyValue(valname);
        ma.setInServer(tmp); safeDel(&tmp);
        sprintf(valname,PROPERTY_MAIL_ACCOUNT_OUT_SERVER,name);
        tmp = mn->readPropertyValue(valname);
        ma.setOutServer(tmp); safeDel(&tmp);
        sprintf(valname,PROPERTY_MAIL_ACCOUNT_IN_PORT,name);
        tmp = mn->readPropertyValue(valname);
        ma.setInPort(tmp); safeDel(&tmp);
        sprintf(valname,PROPERTY_MAIL_ACCOUNT_OUT_PORT,name);
        tmp = mn->readPropertyValue(valname);
        ma.setOutPort(tmp); safeDel(&tmp);
        sprintf(valname,PROPERTY_MAIL_ACCOUNT_IN_SSL,name);
        tmp = mn->readPropertyValue(valname);
        ma.setInSSL(tmp); safeDel(&tmp);
        sprintf(valname,PROPERTY_MAIL_ACCOUNT_OUT_SSL,name);
        tmp = mn->readPropertyValue(valname);
        ma.setOutSSL(tmp); safeDel(&tmp);
        sprintf(valname,PROPERTY_MAIL_ACCOUNT_SIGNATURE,name);
        tmp = mn->readPropertyValue(valname);
        ma.setSignature(tmp); safeDel(&tmp);
        sprintf(valname,PROPERTY_MAIL_ACCOUNT_DOMAINNAME,name);
        tmp = mn->readPropertyValue(valname);
        ma.setDomainName(tmp); safeDel(&tmp);

        sprintf(valname,PROPERTY_MAIL_ACCOUNT_TO_BE_CLEANED,name);
        tmp = mn->readPropertyValue(valname);
        if(strcmp(tmp, "1") == 0){
            ma.setToBeCleaned(true);
        }

        sprintf(valname,PROPERTY_MAIL_ACCOUNT_ID,name);
        tmp = mn->readPropertyValue(valname);
        WCHAR* idW = toWideChar(tmp); safeDel(&tmp);
        ma.setID(idW);
        if (idW) { delete [] idW; }

        config.addMailAccount(ma);

        delete [] name;
    }

    delete [] fullcontext;
}
示例#23
0
int HttpConnection::open(const URL& url, RequestMethod method, bool log_request) 
{
    WCHAR* wurlHost      = NULL;
    WCHAR* wurlResource  = NULL;
    WString headers;
    const WCHAR* http_verb = METHOD_POST;
    WCHAR* ua = NULL;
    DWORD flags = INTERNET_FLAG_RELOAD |
        INTERNET_FLAG_NO_CACHE_WRITE |
        INTERNET_FLAG_KEEP_CONNECTION |           // This is necessary if authentication is required.
        INTERNET_FLAG_NO_COOKIES;                 // This is used to avoid possible server errors on successive sessions.

    LPCWSTR acceptTypes[2] = {TEXT("*/*"), NULL};
    int ret = 0;
    this->url = url;

    // A non-null UserAgent is required
    if (userAgent.empty()) {
        userAgent = USER_AGENT;
    }

    setURL(url);  // set the url in the main AbstractHttpConnection

    if ((url.fullURL == NULL) || (strlen(url.fullURL) == 0)) {
        setErrorF(ERR_HOST_NOT_FOUND, "%s: %s.", __FUNCTION__, ERRMSG_HOST_NOT_FOUND);
        return StatusInternalError;
    }
    
    if (url.isSecure()) {
        if (getSSLVerifyServer() == false) {
            flags = flags| INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID
                | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_REVOCATION 
                | SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_WRONG_USAGE;
        } else {
             flags = flags| INTERNET_FLAG_SECURE;
        }
    }  

    ua = toWideChar(userAgent);

    // open connection.
    inet = InternetOpen (ua, INTERNET_OPEN_TYPE_PRECONFIG, NULL, 0, 0);

    if (ua) {
        delete [] ua; 
        ua = NULL; 
    }

    if (!inet) {
        DWORD code = GetLastError();
        char* tmp = createHttpErrorMessage(code);
        setErrorF(ERR_NETWORK_INIT, "InternetOpen Error: %d - %s", code, tmp);
        delete [] tmp;
        close();
        return StatusNetworkError;
    }

    LOG.debug("Connecting to %s", url.host);
    //
    // Open an HTTP session for a specified site by using lpszServer.
    //
    wurlHost = toWideChar(url.host);
    if (!(connection = InternetConnect (inet,
                                        wurlHost,
                                        url.port,
                                        NULL, // username
                                        NULL, // password
                                        INTERNET_SERVICE_HTTP,
                                        0,
                                        0))) {
        DWORD code = GetLastError();
        char* tmp = createHttpErrorMessage(code);
        setErrorF(ERR_CONNECT, "InternetConnect Error: %d - %s", code, tmp);
        delete [] tmp;
        close();
        return StatusNetworkError;
    }
    //
    // Open an HTTP request handle. By default it uses the POST method (see constructor).
    // it could be set the GET if someone would use it. The api doesn't use
    // GET at all.
    //    
    switch (method) {
        case MethodGet:   
            http_verb = METHOD_GET;
            break;
        case MethodPost:  
            http_verb = METHOD_POST;
            break;
        default:
            // HTTP method not supported...
            LOG.error("%s: unsupported HTTP request type", __FUNCTION__);
            close();
            return StatusInternalError;
    }

    LOG.debug("%s: HTTP verb type: %S", __FUNCTION__, http_verb);
    wurlResource = toWideChar(url.resource);

    // just to avoid printing passwords in the log
    if (log_request) {
        LOG.debug("%s: HTTP url resource: %S", __FUNCTION__, wurlResource);
    }

    if (!(req = HttpOpenRequest(connection, http_verb, wurlResource, HTTP_VERSION,
        NULL, acceptTypes, flags, 0))) {
            DWORD code = GetLastError();
            char* tmp = createHttpErrorMessage(code);
            setErrorF(ERR_CONNECT, "HttpOpenRequest Error: %d - %s", code, tmp);
            delete [] tmp;
            close();
            ret = StatusNetworkError;
    }
   
    // save static handles
    lastInet = inet;
    lastConnection = connection;
    lastReq = req;

    delete [] wurlResource;
    return ret;
}
void MailSourceManagementNode::setMailAccounts(MailSyncSourceConfig& c){
    char t[512];
    ArrayList mailAccounts = config.getMailAccounts();
    int accountNum = mailAccounts.size();

	if (accountNum) {
        char* fullcontext = toMultibyte(getFullContext());
        DeviceManagementNode* mn = new DeviceManagementNode(fullcontext, PROPERTY_MAIL_ACCOUNT_ROOT);
 
        for (int i = 0; i < accountNum; i ++) { 
            if (((MailAccount*)mailAccounts[i])->getDeleted()){
                WCHAR* wname = toWideChar(((MailAccount*)mailAccounts[i])->getName());
                WCHAR* node = new WCHAR[wcslen(getFullContext()) + wcslen(wname) + wcslen(TEXT("\\mailAccounts\\")) +1];
                wsprintf(node, TEXT("%s\\mailAccounts\\%s"), getFullContext(), wname);
                deletePropertyNode(node);
                config.delMailAccount(((MailAccount*)mailAccounts[i])->getName());

                delete [] wname;
                delete [] node;
            }
        }

        delete mn;
        mailAccounts = config.getMailAccounts();
	    c.setMailAccounts(mailAccounts);
        accountNum = mailAccounts.size();
	    for (int i = 0; i < accountNum; i++) {
	        MailAccount* account = static_cast<MailAccount*>(mailAccounts[i]);
		    char valname[512];
            const char* name = stringdup(((StringBuffer)account->getName()).c_str());
            char fullname[512];
            sprintf(fullname, "%s/%s", fullcontext, PROPERTY_MAIL_ACCOUNT_ROOT);
            
	        DeviceManagementNode* mn = new DeviceManagementNode(fullname,name);
			
	        sprintf(valname, PROPERTY_MAIL_ACCOUNT_VISIBLE_NAME, name);
		    sprintf(t, "%s", account->getVisibleName());
		    mn->setPropertyValue(valname, t);

	        sprintf(valname, PROPERTY_MAIL_ACCOUNT_EMAILADDRESS, name);
		    sprintf(t, "%s", account->getEmailAddress());
		    mn->setPropertyValue(valname, t);

		    sprintf(valname, PROPERTY_MAIL_ACCOUNT_PROTOCOL, name);
		    sprintf(t, "%s", account->getProtocol());
		    mn->setPropertyValue(valname, t);

		    sprintf(valname, PROPERTY_MAIL_ACCOUNT_USERNAME, name);
		    sprintf(t, "%s", account->getUsername());
		    mn->setPropertyValue(valname, t);

		    sprintf(valname, PROPERTY_MAIL_ACCOUNT_PASSWORD, name);
		    sprintf(t, "%s", account->getPassword());
		    mn->setPropertyValue(valname, t);

		    sprintf(valname, PROPERTY_MAIL_ACCOUNT_IN_SERVER, name);
		    sprintf(t, "%s", account->getInServer());
		    mn->setPropertyValue(valname, t);

		    sprintf(valname, PROPERTY_MAIL_ACCOUNT_OUT_SERVER, name);
		    sprintf(t, "%s", account->getOutServer());
		    mn->setPropertyValue(valname, t);

		    sprintf(valname, PROPERTY_MAIL_ACCOUNT_IN_PORT, name);
		    sprintf(t, "%s", account->getInPort());
		    mn->setPropertyValue(valname, t);

		    sprintf(valname, PROPERTY_MAIL_ACCOUNT_OUT_PORT, name);
		    sprintf(t, "%s", account->getOutPort());
		    mn->setPropertyValue(valname, t);

		    sprintf(valname, PROPERTY_MAIL_ACCOUNT_IN_SSL, name);
		    sprintf(t, "%s", account->getInSSL());
		    mn->setPropertyValue(valname, t);

	    	sprintf(valname, PROPERTY_MAIL_ACCOUNT_OUT_SSL, name);
		    sprintf(t, "%s", account->getOutSSL());
		    mn->setPropertyValue(valname, t);

		    sprintf(valname, PROPERTY_MAIL_ACCOUNT_SIGNATURE, name);
		    sprintf(t, "%s", account->getSignature());
		    mn->setPropertyValue(valname, t);

	    	sprintf(valname, PROPERTY_MAIL_ACCOUNT_DOMAINNAME, name);
		    sprintf(t, "%s", account->getDomainName());
		    mn->setPropertyValue(valname, t);

            sprintf(valname, PROPERTY_MAIL_ACCOUNT_TO_BE_CLEANED, name);
            
            int toBeCleaned = 0;
            if (account->getToBeCleaned()){
                toBeCleaned = 1;
            }
            sprintf(t, "%d", toBeCleaned);
            mn->setPropertyValue(valname, t);

            sprintf(valname, PROPERTY_MAIL_ACCOUNT_ID, name);			
		    const WCHAR* accountIdw = account->getID();
	        const char *accountId = toMultibyte(accountIdw);
		    sprintf(t, "%s", accountId);
		    delete [] accountId;

		    mn->setPropertyValue(valname, t);
            delete mn;
            delete [] name;
		}

        delete [] fullcontext;
	}
}
BOOL CProxySettings::OnInitDialog() {
    CString s1, s2;
    s1.LoadString(IDS_PROXY_SETTINGS2);
    SetWindowText(s1);
    CDialog::OnInitDialog();

    const char* proxyUser = NULL;
    const char* proxyPass = NULL;


    editUser.SetLimitText(EDIT_TEXT_MAXLENGTH);
    editPass.SetLimitText(EDIT_TEXT_MAXLENGTH);

    s1.LoadString(IDS_ACCOUNT_USEPROXY);
    SetDlgItemText(IDC_PROXY_ENABLE, s1);
    s1.LoadString(IDS_ACCOUNT_PROXY_AUTH);
    SetDlgItemText(IDC_PROXY_AUTH, s1);
    s1.LoadString(IDS_ACCOUNT_PROXY_USER);
    SetDlgItemText(IDC_PROXY_STATIC_USER, s1);
    s1.LoadString(IDS_ACCOUNT_PROXY_PASS);
    SetDlgItemText(IDC_PROXY_STATIC_PASSWORD, s1);

    // read config from Registry
    OutlookConfig* conf = (OutlookConfig*)getConfig();

    proxyUser = conf->getAccessConfig().getProxyUsername();
    proxyPass = conf->getAccessConfig().getProxyPassword();

    // proxy authentication
    if( (strcmp(proxyUser,"")) && (strcmp(proxyPass,"")) ) {
        // proxy authentication required
        checkAuth.SetCheck(BST_CHECKED);
        editUser.EnableWindow(TRUE);
        editPass.EnableWindow(TRUE);
        GetDlgItem(IDC_PROXY_STATIC_USER)->EnableWindow(TRUE);
        GetDlgItem(IDC_PROXY_STATIC_PASSWORD)->EnableWindow(TRUE);

        // Note: use 'toWideChar' because we need UTF-8 conversion.
        WCHAR* tmp = toWideChar(proxyUser);
        s2 = tmp;
        SetDlgItemText(IDC_PROXY_EDIT_USER, s2);
        delete [] tmp;

        // Note: use 'toWideChar' because we need UTF-8 conversion.
        tmp = toWideChar(proxyUser);
        s2 = tmp;
        SetDlgItemText(IDC_PROXY_EDIT_PASS, s2);
        delete [] tmp;
    }
    else {
        checkAuth.SetCheck(BST_UNCHECKED);
        editUser.EnableWindow(FALSE);
        editPass.EnableWindow(FALSE);
        GetDlgItem(IDC_PROXY_STATIC_USER)->EnableWindow(FALSE);
        GetDlgItem(IDC_PROXY_STATIC_PASSWORD)->EnableWindow(FALSE);
    }

    // use proxy
    if(conf->getAccessConfig().getUseProxy()) {
        checkEnable.SetCheck(BST_CHECKED);
    }
    else {
        checkEnable.SetCheck(BST_UNCHECKED);
        checkAuth.EnableWindow(FALSE);
        editUser.EnableWindow(FALSE);
        editPass.EnableWindow(FALSE);
        GetDlgItem(IDC_PROXY_STATIC_USER)->EnableWindow(FALSE);
        GetDlgItem(IDC_PROXY_STATIC_PASSWORD)->EnableWindow(FALSE);
    }

    checkEnable.SetFocus();
    return FALSE;
}
示例#26
0
int SyncMLProcessor::processItemStatus(SyncSource& source, SyncBody* syncBody) {

    ArrayList* items = NULL;
    Item* item       = NULL;
    SourceRef* sourceRef = NULL;
    Status* s = NULL;
    const char* name = NULL;
    Data* data = NULL;
    int ret = 0;

    ArrayList* list = getCommands(syncBody, STATUS);

    for (int i = 0; i < list->size(); i++) {
        s = (Status*)list->get(i);
        name = s->getCmd();
        data = s->getData();
        if (strcmp(name, SYNC) == 0){
            char *srcname = toMultibyte(source.getName());
            int alertStatus = getAlertStatusCode(s, srcname);
            delete [] srcname;

            /*
            * Try to find if the server send a message together the error code if any
            * The items in the status message should be always one...
            */
            char *statusMessage = NULL;
            items = s->getItems();
			for (int k = 0; k < items->size(); k++) {
                item = (Item*)items->get(k);
                if (item) {
                    ComplexData* cd = item->getData();
                    if (cd) {
                        statusMessage = stringdup(cd->getData());
                    }
                }
            }
            // Fire Sync Status Event: sync status from server
            fireSyncStatusEvent(SYNC, s->getStatusCode(), source.getConfig().getName(), source.getConfig().getURI(), NULL, SERVER_STATUS);

            if(alertStatus < 0 || alertStatus >=300){
                if (statusMessage) {
                    //strcpy(lastErrorMsg, statusMessage);
                    setError( alertStatus, statusMessage);
                } else {
                    //strcpy(lastErrorMsg, "Error in sync status sent by server.");
                    setError( alertStatus, "Error in sync status sent by server.");
                }
                if ((ret = alertStatus) < 0)
                    LOG.error("processItemStatus: status not found in SYNC");
                else
                    LOG.error("processItemStatus: server sent status %d in SYNC", alertStatus);
                break;
            }
            if (statusMessage) {
                delete [] statusMessage;
            }
        }

        else if (strcmp(name, ADD) == 0 ||
            strcmp(name, REPLACE) == 0 ||
            strcmp(name, DEL) == 0) {

            int k;

            items = s->getItems();
            long val = strtol(data->getData() , NULL, 10);
            for (k = 0; k < items->size(); k++) {
                item = (Item*)items->get(k);
                if (item) {
                    Source* itemSource = item->getSource();
                    if (itemSource) {
                        WCHAR *uri = toWideChar(itemSource->getLocURI());

                        ComplexData* cd = item->getData();
                        WCHAR *statusMessage = NULL;
                        if (cd) {
                            statusMessage = toWideChar(cd->getData());
                        }

                        // Fire Sync Status Event: item status from server
                        fireSyncStatusEvent(s->getCmd(), s->getStatusCode(), source.getConfig().getName(), source.getConfig().getURI(), uri, SERVER_STATUS);
                        // Update SyncReport
                        source.getReport()->addItem(SERVER, s->getCmd(), uri, s->getStatusCode(), statusMessage);

                        source.setItemStatus(uri, val, name);
                        delete [] uri;
                        if (statusMessage)
                            delete [] statusMessage;
                    } else {
                        // the item might consist of additional information, as in:
                        // <SourceRef>pas-id-44B544A600000092</SourceRef>
                        // <Data>200</Data>
                        // <Item><Data>Conflict resolved by server</Data></Item>
                    }
                }
            }
            items = s->getSourceRef();
            for (k = 0; k < items->size(); k++) {
                sourceRef = (SourceRef*)items->get(k);
                if (sourceRef) {
                    WCHAR *srcref = toWideChar(sourceRef->getValue());
			        // Fire Sync Status Event: item status from server
                    fireSyncStatusEvent(s->getCmd(), s->getStatusCode(), source.getConfig().getName(), source.getConfig().getURI(), srcref, SERVER_STATUS);
                    // Update SyncReport
                    source.getReport()->addItem(SERVER, s->getCmd(), srcref, s->getStatusCode(), NULL);

                    source.setItemStatus(srcref, val, name);
                    delete [] srcref;
                }
            }
        }
    }

    //deleteArrayList(&list);
    if (list){
        delete list;
        list = NULL;
    }
    return ret;
}
示例#27
0
文件: String.cpp 项目: tixsys/esteid
std::string digidoc::util::String::convertUTF8(const std::string &in, bool to_UTF)
{
    int inFormat = to_UTF ? CP_ACP : CP_UTF8;
    int outFormat = to_UTF ? CP_UTF8 : CP_ACP;
    return toMultiByte(outFormat, toWideChar(inFormat, in));
}
示例#28
0
int HttpConnection::sendData(const char* data, int data_len)
{
    int totalBytesRead = 0;
    int ret = 0;
    DWORD bytesWritten = 0;
    DWORD errorCode = 0;

    if (!InternetWriteFile(req, data, data_len, &bytesWritten)) {
        errorCode = GetLastError();

        char* tmp = createHttpErrorMessage(errorCode);
        setErrorF(errorCode, "InternetWriteFile error %d: %s", errorCode, tmp);
        LOG.info("%s", getLastErrorMsg());
        delete [] tmp; tmp = NULL;
        //
        // The certificate is not trusted. Send the right error code to the
        // client
        //
        if (errorCode == ERROR_INTERNET_INVALID_CA) {
            setError(ERR_HTTPS_INVALID_CA, "The certificate is invalid");
            LOG.error("%s", getLastErrorMsg());

            // try to understand a bit more on the certificate
            INTERNET_CERTIFICATE_INFO   certificateInfo;
            DWORD                       certInfoLength = sizeof(INTERNET_CERTIFICATE_INFO);                
            if (TRUE == InternetQueryOption(req, INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT, 
                &certificateInfo, &certInfoLength)) {

                    char* subj   = (char*)certificateInfo.lpszSubjectInfo;
                    char* issuer = (char*)certificateInfo.lpszIssuerInfo;    
                    LOG.debug("Cert Subject %s", subj);
                    LOG.debug("Cert Issuer %s",  issuer);

            } else {                        
                LOG.debug("Cannot retrieve info about the certificate");
            }     
        } else if (errorCode == ERROR_INTERNET_OFFLINE_MODE) {                     // 00002 -> retry
            LOG.debug("Offline mode detected: go-online and retry...");
            WCHAR* wurl = toWideChar(url.fullURL);
            InternetGoOnline(wurl, NULL, NULL);
            delete [] wurl;
        } else if (errorCode == ERROR_INTERNET_TIMEOUT ||                     // 12002 -> out code 2007
            errorCode == ERROR_INTERNET_INCORRECT_HANDLE_STATE) {      // 12019 -> out code 2007
                setError(ERR_HTTP_TIME_OUT, "Network error: the request has timed out -> exit.");
                LOG.debug("%s", getLastErrorMsg());
        } else if (errorCode == ERROR_INTERNET_CANNOT_CONNECT) {              // 12029 -> out code 2001
            setError(ERR_CONNECT, "Network error: the attempt to connect to the server failed -> exit"); 
            LOG.debug("%s", getLastErrorMsg());
        }
        // Other network error: retry.
        LOG.info("Network error writing data from client");
        resetError();
    }

    if (bytesWritten != data_len) {
        LOG.error("[%s] Warning: possible loss of data: %d bytes read, %d bytes written", 
            __FUNCTION__, data_len, bytesWritten);
    }

    return errorCode;
}
/*
 * Returns the value of the given property
 * the value is returned as a new char array and must be free'd by the user
 *
 * @param property - the property name
 */
char* DeviceManagementNode::readPropertyValue(const char* prop) {
    HKEY key = NULL;
    DWORD res;
    long err = 0;
    char *ret=NULL;
    TCHAR *p = toWideChar(prop);
    ULONG dim = 0;

    RegCreateKeyEx(
            HKEY_DM_ROOT,
            fullContext,
            0,
            NULL,
            REG_OPTION_NON_VOLATILE,
            KEY_ALL_ACCESS,
            NULL,
            &key,
            &res
            );

    if (key == 0) {
        //lastErrorCode = ERR_INVALID_CONTEXT;
        //sprintf(lastErrorMsg, "Invalid context path: %ls", fullContext);
        setErrorF(ERR_INVALID_CONTEXT, "Invalid context path: %ls", fullContext);
        goto finally;
    }

    // Get value length
    err = RegQueryValueEx(
            key,
            p,
            NULL,
            NULL,  // we currently support only strings
            NULL,
            &dim
            );

    if (err == ERROR_SUCCESS) {
		if (dim > 0) {
            TCHAR *buf = new TCHAR[dim + 1];

			err = RegQueryValueEx(
					key,
					p,
					NULL,
					NULL,  // we currently support only strings
					(UCHAR*)buf,
					&dim
					);
            if (err == ERROR_SUCCESS)
                ret = toMultibyte(buf);
            delete [] buf;
		}
    }
    //else MessageBox(NULL,  "Error", "getConfigParameter", MB_OK);

    if (!ret)
        ret = stringdup("");

finally:

    if (p)
        delete [] p;

    if (key != 0) {
        RegCloseKey(key);
    }

    return ret;
}
示例#30
0
int HttpConnection::checkResponseStatus()
{
    DWORD status, size;
    size = sizeof(status);

    HttpQueryInfo (req,
        HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
        (LPDWORD)&status,
        (LPDWORD)&size,
        NULL);

    // data sent OK
    if (isErrorStatus(status) == false) {
        if (status == HTTP_STATUS_OK) {
            LOG.debug("data sent successfully: server responds OK");
        } else if (status == HTTP_RESUME_INCOMPLETE) {
            LOG.debug("HTTP 308 (Resume Incomplete)");
        } 
    }

#if defined(WIN32) && !defined(_WIN32_WCE)
    //
    // Proxy Authentication Required (407) / Server Authentication Required (401).
    // Need to set username/password.
    //
    else if (status == HTTP_STATUS_DENIED) {
        LOG.info("%s: received status 401 from server", __FUNCTION__);
        return HTTP_UNAUTHORIZED;
    }
    else if(status == HTTP_STATUS_PROXY_AUTH_REQ) {
        LOG.debug("%s: HTTP Proxy Authentication required.", __FUNCTION__);

        // http://support.microsoft.com/kb/249594/it
        DWORD dwSize, dwCode;
        CHAR szData[1024];
        dwSize = sizeof (DWORD);  
        do {
            InternetReadFile (req, (LPVOID)szData, 1023, &dwSize);
        } while (dwSize != 0);
        //////////////////

        // Automatic authentication (user/pass stored in win reg key).
        if (strcmp(proxy.user, "") && strcmp(proxy.password, "") && !auth && (numberOfRetryForProxy == MAX_PROXY_RETRY)) {
            LOG.debug("%s: using proxy username and password store in config", __FUNCTION__);
            WCHAR* wUser = toWideChar(proxy.user);
            WCHAR* wPwd  = toWideChar(proxy.password);

            InternetSetOption(req, INTERNET_OPTION_PROXY_USERNAME, wUser, wcslen(wUser)+1);
            InternetSetOption(req, INTERNET_OPTION_PROXY_PASSWORD, wPwd,  wcslen(wPwd)+1);

            delete [] wUser;
            delete [] wPwd;
            status = ERROR_INTERNET_FORCE_RETRY;
            numberOfRetryForProxy++;
            
        } else {
            LOG.debug("%s: return proxy auth required error", __FUNCTION__);
            numberOfRetryForProxy = 1; // reset the value
        }
    }
#endif  // #if defined(WIN32) && !defined(_WIN32_WCE)

    else {
        LOG.error("[HttpConnection]: server returned HTTP status code %d", status);
    }

    return status;
}