/**
 * SetHttpClientError()
 * Set the http client error (5xx) in Funambol client-api.
 */
void CSymbianTransportAgent::SetHttpClientError(TInt aStatus)
{
    switch (aStatus)
    {
        case 401:
        {
            setErrorF(ERR_CREDENTIAL, "HTTP server error: %d. Wrong credential.", aStatus);
        }
        break;
        case 402:
        {
            setErrorF(PAYMENT_REQUIRED,
                      "HTTP server error: %d. Client not authenticated.",
                      aStatus);
        }
        break;
        case 403:
        {
            setErrorF(FORBIDDEN,
                      "HTTP server error: %d. Connection forbidden, client not activated.",
                      aStatus);
        }
        break;
        case 404:
        {
            //setErrorF(ERR_HTTP_NOT_FOUND,
            //          "HTTP request error: resource not found (status %d)",
            //          aStatus);
        }
        break;
        case 408:
        {
            //setErrorF(ERR_HTTP_REQUEST_TIMEOUT,
            //          "HTTP request error: server timed out waiting for request (status %d)",
            //          aStatus);
        }
        break;
        case 420:
        {
            setErrorF(ERR_CLIENT_NOT_NOTIFIABLE,
                      "HTTP server error: %d. Client not notifiable.",
                      aStatus);
        }
        break;
        case 421:
        {
            setErrorF(ERR_CTP_ALLOWED,
                      "HTTP server error: %d. Client not notifiable and CTP Server is available.",
                      aStatus);
        }
        break;
    
        default:
        {
        }
        break;
    }
}
示例#2
0
void SymbianLog::printMessage(const char* level, const char* msg, PLATFORM_VA_LIST argList) 
{
    iSemaphore.Wait();
    
    StringBuffer currentTime = createCurrentTime(true);
    
    TInt err = file.Open(fsSession, iLogName, EFileWrite|EFileShareAny);
    TInt pos = 0;
    
    if (err == KErrNotFound) 
    {
        // First time: file does not exist. Create it.
        err = file.Create(fsSession, iLogName, EFileWrite|EFileShareAny);
        if (err != KErrNone) {
            setErrorF(err, "SymbianLog: could not open log file (code %d)", err);
            goto finally;
        }
        StringBuffer header = createHeader();
        RBuf8 data;
        data.Assign(stringBufferToNewBuf8(header));
        file.Write(data);
        data.Close();
    }
    else 
    {
        err = file.Seek(ESeekEnd, pos);
        if (err != KErrNone) {
            setErrorF(err, "SymbianLog: seek error on log file (code %d)", err);
            goto finally;
        }
    }

    {
        // Write the data
        StringBuffer line, data;
        line.sprintf("%s -%s- %s", currentTime.c_str(), level, msg);
        data.vsprintf(line.c_str(), argList);
        data.append("\n");
        
        RBuf8 buf;
        buf.Assign(stringBufferToNewBuf8(data));
        file.Write(buf);
        buf.Close();
    }
    
finally:
    file.Close();
    // we need closed file to operate on it
    if ( LogSize() > SYMBIAN_LOG_SIZE ){
        // roll log file
        RollLogFile();
    }
    iSemaphore.Signal();
}
USE_NAMESPACE

DataTransformer* DataTransformerFactory::getEncoder(const char* name) {
    DataTransformer* ret = NULL;

    if (isSupportedEncoder(name) == false) {
        //lastErrorCode = ERR_DT_UNKNOWN;
        //sprintf (lastErrorMsg, ERRMSG_DT_UNKNOWN, name);
        setErrorF(ERR_DT_UNKNOWN, ERRMSG_DT_UNKNOWN, name);
        goto exit;
    } else if (strcmp(name, DT_B64) == 0) {
        //
        // base 64 encoder
        //
        ret = new B64Encoder();
    } else if (strcmp(name, DT_DES) == 0) {
        //
        // DES encoder
        //
        ret = new DESEncoder();
    }

exit:

    return ret;
}
示例#4
0
int SyncMLProcessor::getStatusCode(SyncBody* syncBody, SyncSource* source, const char*commandName) {
    int ret = -1;

    ArrayList* list = syncBody->getCommands();
    const char* name = NULL;
    Status* s     = NULL;

    for (int i = 0; i < list->size(); i++) {
        name = ((AbstractCommand*)(list->get(i)))->getName();    // is returned the pointer to the element not a new element
        if (name && strcmp(name, STATUS) == 0) {
            s = (Status*)list->get(i);
            if (strcmp(s->getCmd(), commandName) == 0) {
                if (strcmp(commandName, SYNC_HDR) == 0) {
                    ret = getSyncHeaderStatusCode(s);
                } else if (strcmp(commandName, ALERT) == 0) {
                    ret = getAlertStatusCode(s, (char*)source->getName());
                }
                break;
            }
        }
    }

    if (ret == -1) {
        //sprintf(lastErrorMsg, "Error reading status code of command '%s'", commandName);
        //lastErrorCode = ERR_REPRESENTATION;
        setErrorF(ERR_REPRESENTATION, "Error reading status code of command '%s'", commandName);
    }
    return ret;

}
int DeviceManagementNode::getChildrenMaxCount() {
    HKEY key;
    ULONG howMany = 0;

    RegOpenKeyEx(
            HKEY_DM_ROOT,
            fullContext,
            0,
            KEY_READ,
            &key
            );

    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;
    }

    RegQueryInfoKey(
            key, NULL, NULL, NULL, &howMany, NULL, NULL, NULL, NULL, NULL, NULL, NULL
            );


finally:

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

    return howMany;
}
/*
 * 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);
    }
}
示例#7
0
void SymbianLog::RollLogFile(void)
{
    CFileMan* fileMan = CFileMan::NewL(fsSession);
    CleanupStack::PushL(fileMan);
    //copy the current file into the roll file, file must be open
    TInt err = KErrNone;
    err = file.Open(fsSession, iLogName, EFileWrite|EFileShareAny);
    if (err != KErrNone) {
        setErrorF(err, "SymbianLog: could not open log file (code %d)", err);
    } else {
        err = fileMan->Copy(file,iRollLogName,CFileMan::EOverWrite);
    }
    if (err != KErrNone) {
        setErrorF(err, "SymbianLog: copy error on roll log file (code %d)", err);
    }
    file.Close();
    // reset the current file
    // we don't use reset() method because we don't want 
    // nested semaphores
    err = KErrNone;
    err = file.Replace(fsSession, iLogName, EFileWrite|EFileShareAny);
    if (err != KErrNone) {
        setErrorF(err, "SymbianLog: error resetting the log file (code %d)", err);
        return;
    }
    // Write the Header
    StringBuffer header = createHeader();
    RBuf8 buf;
    buf.Assign(stringBufferToNewBuf8(header));
    file.Write(buf);
    buf.Close();
    file.Close();
    
    CleanupStack::PopAndDestroy(fileMan);

}
示例#8
0
HttpConnection::HttpConnection(const char* user_agent) : 
                              AbstractHttpConnection(user_agent), inet(NULL), connection(NULL), req(NULL)
{
#ifdef _WIN32_WCE
    // used by default. check connection before...
    if (!EstablishConnection()) {
        #ifdef WIN32_PLATFORM_PSPC
        setErrorF(ERR_INTERNET_CONNECTION_MISSING, "%s: %d", "Internet Connection Missing", ERR_INTERNET_CONNECTION_MISSING);
        #else
        LOG.error("Warning: internet connection missing.");
        #endif
    }
#endif   
    numberOfRetryForProxy = 1;
}
/**
 * SetHttpServerError()
 * Set the http server error (5xx) in Funambol client-api.
 */
void CSymbianTransportAgent::SetHttpServerError(TInt aStatus)
{
    switch (aStatus)
    {
        case 500:
        {
            setErrorF(ERR_SERVER_ERROR,
                      "HTTP server error: %d. Server failure.",
                      aStatus);
        }
        break;
        default:
        {
            
        }
        break;
    }
}
示例#10
0
void SymbianLog::reset(const char* title) 
{
    iSemaphore.Wait();
    
    TInt err = file.Replace(fsSession, iLogName, EFileWrite|EFileShareAny);
    if (err != KErrNone) {
        setErrorF(err, "SymbianLog: error resetting the log file (code %d)", err);
        return;
    }
    
    // Write the Header
    StringBuffer header = createHeader(title);
    RBuf8 buf;
    buf.Assign(stringBufferToNewBuf8(header));
    file.Write(buf);
    buf.Close();
    
    file.Close();
    iSemaphore.Signal();
}
示例#11
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;
}
示例#12
0
SymbianLog::SymbianLog(bool resetLog, const char* path, const char* name) 
{
    TInt err = KErrNone;
    
    const char* p = (path)? path : SYMBIAN_LOG_PATH;
    const char* n = (name)? name : SYMBIAN_LOG_NAME;
    
    // assign all the paths and names
    StringBuffer logName(p);
    logName += n;
    iLogName.Assign(charToNewBuf(logName.c_str()));
    
    StringBuffer rollName(logName);
    rollName += ".0";
    iRollLogName.Assign(charToNewBuf(rollName.c_str()));
    
    StringBuffer pathSb(p);
    iLogPathName.Assign(charToNewBuf(pathSb.c_str()));
    
    StringBuffer nameSb(n);
    iLogFileName.Assign(charToNewBuf(nameSb.c_str()));
    
    // try open log
    err = iSemaphore.OpenGlobal(KLogSemaphoreName);

    if (err == KErrNotFound) {
        // Create a semaphore, to avoid accessing the FileSystem at
        // the same time by different threads.
        // The semaphore is global, so that it could be used also by
        // other processes that (in future) will use this Log.
        err = iSemaphore.CreateGlobal(KLogSemaphoreName, 1);
        if (err != KErrNone) {
            setError(ERR_SEMAPHORE_CREATION, ERR_SEMAPHORE_CREATION_MSG);
        }
    }

    iSemaphore.Wait();
    
    // Connect to the file server session.
    fsSession.Connect();
    err = fsSession.ShareAuto();
    if (err != KErrNone) {
        setErrorF(err, "SymbianLog error: unable to share RFs session (code %d)", err);
        return;
    }
    
    // ensure path exists!
    BaflUtils::EnsurePathExistsL(fsSession, iLogPathName);
    
    if (resetLog) {
        err = file.Replace(fsSession, iLogName, EFileWrite|EFileShareAny);
        if (err != KErrNone) {
            setErrorF(err, "SymbianLog: could not open the log file '%ls'", iLogName.Ptr());
            return;
        }
        
        // Write the Header
        StringBuffer header = createHeader();
        RBuf8 data;
        data.Assign(stringBufferToNewBuf8(header));
        file.Write(data);
        data.Close();
        file.Close();
    }
    
    iSemaphore.Signal();
    return;
}
/**
 * CSymbianTransportAgent::sendMessage()
 */
char* CSymbianTransportAgent::sendMessage(const char* msg)
{
    LOG.debug("entering CSymbianTransportAgent::sendMessage"); 
    
    // Check if user aborted current sync.
    if (getLastErrorCode() == KErrCancel) {
        LOG.debug("Leaving sendMessage - lastErrorCode is %d", getLastErrorCode());
        User::Leave(KErrCancel);    // leave is trapped at SyncActiveObject::RunL().
    }
    
    // Just to be sure the response buffer is ok
    //TO BE VERIFIED!!!!
    delete iResponseBody;
    iResponseBody = NULL; 
    
    // Set the POST body
    delete iPostBody;
    iPostBody = NULL;

    if (url.fullURL == NULL) {
        setErrorF(ERR_CONNECT, "Empty URL"); 
        LOG.error("Transport Agent: empty URL");
        return NULL;
    }

    char* response = NULL;
    RStringF method;
    RHTTPHeaders hdr;
    // Parse string to URI (as defined in RFC2396)
    TUriParser8 uri;
    HBufC8* fullUrl = charToNewBuf8(url.fullURL); 
    TInt parseErr = uri.Parse(*fullUrl);
    if (parseErr != KErrNone) {
        setErrorF(ERR_CONNECT, "Malformed URL"); 
        LOG.error("Transport Agent: malformed url");
        goto finally;
    }

    {
        TPtrC8 ptr(reinterpret_cast<const TUint8*>(msg));
        iPostBody = HBufC8::NewL(ptr.Length());
        iPostBody->Des().Copy(ptr);
    }
    
    FConnection* connection = FConnection::getInstance();
    if (connection->isConnected() == false) {
        int res = connection->startConnection();
        if (res) {
            setErrorF(ERR_CONNECT, "Connection error (%d): please check your internet settings.", res); 
            LOG.error("%s", getLastErrorMsg());
            goto finally;
        }
    }

    // Get request method string for HTTP POST
    method = iHttpSession.StringPool().StringF( HTTP::EPOST, RHTTPSession::GetTable());

    // Open transaction with previous method and parsed uri. This class will 
    // receive transaction events in MHFRunL and MHFRunError.
    iHttpTransaction = iHttpSession.OpenTransactionL( uri, *this, method );

    // Set headers for request; user agent, accepted content type and body's 
    // content type.
    hdr = iHttpTransaction.Request().GetHeaderCollection();
    SetHeaderL(hdr, HTTP::EUserAgent, _L8("Funambol Symbian SyncML client"));
    SetHeaderL(hdr, HTTP::EAccept, _L8("*/*"));
    SetHeaderL(hdr, HTTP::EContentType, _L8("application/vnd.syncml+xml"));

    LOG.debug("Sending message:");
    LOG.debug("%s", msg);

    // Set data supplier for POST body
    // Please see  » Symbian OS v9.1 » Symbian OS guide » Using HTTP Client »
    // Handling request body data for explanation on this part
    iDataSupplier = this;
    iHttpTransaction.Request().SetBody(*iDataSupplier);     

    // Submit the transaction. After this the framework will give transaction
    // events via MHFRunL and MHFRunError.
    iHttpTransaction.SubmitL();

    // Start the scheduler, once the transaction completes or is cancelled on an
    // error the scheduler will be stopped in the event handler
    // This is a trick to implement a synchronous method
    LOG.debug("starting ASync scheduler...");
    iASWait->Start();  // TO BE VERIFIED!!!!
    LOG.debug("ASync scheduler stopped");
    
    
    // Check if user aborted current sync.
    if (getLastErrorCode() == KErrCancel) {
        LOG.debug("Leaving sendMessage - lastErrorCode is %d", getLastErrorCode());
        User::Leave(KErrCancel);    // leave is trapped at SyncActiveObject::RunL().
    }
    
    // when all is finished, return char* to be delete []
    if(!iTransFailed) {
        TInt length = iResponseBody->Des().Length();
        response = new char[length+1];
        Mem::Copy(response, iResponseBody->Ptr(), length);
        response[length] = '\0';

        LOG.debug("Message received:");
        LOG.debug("%s", response);
    }
    else {
        LOG.debug("HTTP transaction failed");
        setErrorF(ERR_HTTP, "HTTP request error: request timed out waiting for response");
    }

finally:

    // Transaction can be closed now. It's not needed anymore.
    LOG.debug("closing HTTP transaction");
    iHttpTransaction.Close();

    delete fullUrl;
    LOG.debug("exiting CSymbianTransportAgent::sendMessage");
    return response;
}
示例#14
0
char* DESEncoder::transform(char* data, TransformationInfo& info) {
    BOOL res = FALSE;

    HCRYPTPROV prov = 0;
    HCRYPTKEY key = 0;

    HCRYPTHASH hash=0;

    char* ret = NULL;

    DWORD sizeIn = info.size; // I reassign it to a DWORD
                              // just in case a long is not
                              // of the same size of a DWORD
    DWORD sizeOut = 0;

    DWORD dwParam = 0;

    char* password = stringdup(info.password);

    // -----------------------------------------------------

    res = CryptAcquireContext(
        &prov,
        NULL,
        MS_ENHANCED_PROV,
        PROV_RSA_FULL,
        CRYPT_VERIFYCONTEXT
    );

    if (res == FALSE) {
        //lastErrorCode = ERR_DT_FAILURE;
        //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError());
        setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError());
        goto exit;
    }

    // Create hash object
    res = CryptCreateHash(
        prov,       // CSP handle
        CALG_MD5,   // hash algorith ID
        0,          // Key not used
        0,          // flags not used
        &hash       // handle to the hash object
    );

    if (res == FALSE) {
        //lastErrorCode = ERR_DT_FAILURE;
        //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError());
        setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError());
        goto exit;
    }

    // hash password
    res = CryptHashData(
        hash,                     // hash handle
        (unsigned char*) password,// pointer to the data buffer
        strlen(password),         // data length
        0                         // flags not used
    );

    if (res == FALSE) {
        //lastErrorCode = ERR_DT_FAILURE;
        //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError());
        setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError());
        goto exit;
    }

    // Create key from hash
    res = CryptDeriveKey(
        prov,       // CSP handle
        CALG_DES,   // algorithm id
        hash,       // hash object
        0,          // flags are not used
        &key        // key handle
    );

    if (res == FALSE) {
        //lastErrorCode = ERR_DT_FAILURE;
        //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError());
        setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError());
        goto exit;
    }

    // set encryption mode to ECB
    dwParam=CRYPT_MODE_ECB;
    res = CryptSetKeyParam(
        key,                      // key handle
        KP_MODE,                   // set key mode flag
        (unsigned char*) &dwParam, // new mode value
        0                          // flags not used
    );

    if (res == FALSE) {
        //lastErrorCode = ERR_DT_FAILURE;
        //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError());
        setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError());
        goto exit;
    }

    // set padding mode to PKCS5
    dwParam=PKCS5_PADDING;
    res = CryptSetKeyParam(
        key,                      // key handle
        KP_PADDING,                   // set key mode flag
        (unsigned char*) &dwParam, // new mode value
        0                          // flags not used
    );

    if (res == FALSE) {
        //lastErrorCode = ERR_DT_FAILURE;
        //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError());
        setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError());
        goto exit;
    }

    // create big buffer
    sizeOut = sizeIn;

    // Get the size of the encrypted block
    res = CryptEncrypt(
        key,            // Key obtained earlier
        0,              // No hashing of data
        TRUE,           // Final or only buffer of data
        0,              // Must be zero
        NULL,           // No data this time
        &sizeOut,       // Length of the source data
        0               // Size of block
    );

    if ((res == FALSE) && (GetLastError() != ERROR_MORE_DATA)) {
        //lastErrorCode = ERR_DT_FAILURE;
        //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError());
        setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError());
        goto exit;
    }

    // allocate and intialize the buffer
    ret = new char[sizeOut];
    memcpy(ret, data, sizeIn);

    // Now encrypt the data
    res = CryptEncrypt(
        key,                 // Key obtained earlier
        0,                   // No hashing of data
        TRUE,                // Final or only buffer of data
        0,                   // Must be zero
        (unsigned char*)ret, // Data buffer
        &sizeIn,             // Size of data
        sizeOut              // Size of block
    );

    if (res == FALSE) {
        //lastErrorCode = ERR_DT_FAILURE;
        //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError());
        setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError());
        goto exit;
    }

    info.size = sizeIn;
    info.newReturnedData = true;

 exit:

   // Destroy the session key.
   if (key)
     CryptDestroyKey (key);

   // Destroy the hash object.
   if (hash)
     CryptDestroyHash (hash);

   // Release the provider handle.
   if (prov)
     CryptReleaseContext (prov, 0);

   if (password) {
       delete [] password;
   }

   return ret;

}
/*
 * Sends the given SyncML message to the server specified
 * by the instal property 'url'. Returns the response status code or -1
 * if it was not possible initialize the connection.
 *
 * Use getResponse() to get the server response.
 */
char* CurlTransportAgent::sendMessage(const char* msg) {
    if (!easyhandle) {
        setError(ERR_NETWORK_INIT, "libcurl error init error");
        LOG.error("%s", getLastErrorMsg());
        return NULL;
    }

    size_t size = strlen(msg);


    LOG.debug("Requesting resource %s at %s:%d", url.resource, url.host, url.port);
    POSIX_LOG.setPrefix("data out: ");
    LOG.debug("=== %d bytes ===\n%s", (int)size, msg);
    POSIX_LOG.setPrefix(NULL);

    curl_slist *slist=NULL;
    char *response = NULL;
    CURLcode code;
    char contenttype[256];
    sprintf(contenttype, "Content-Type: %s", SYNCML_CONTENT_TYPE);
    slist = curl_slist_append(slist, contenttype);
    // Disable "Expect: 100": it is usually used to check without
    // transmitting the data that the recipient is willing to accept
    // the POST . With SyncML servers that should be the case, so the
    // check just adds one round-trip and worse, "Expect: 100" is not
    // supported by some proxies, causing a complete failure.
    slist = curl_slist_append(slist, "Expect:");
    responsebuffersize = 64 * 1024;
    responsebuffer = new char[responsebuffersize];
    received = 0;
    responsebuffer[0] = 0;
    // todo? url.resource
    const char *certificates = getSSLServerCertificates();
    if ((code = curl_easy_setopt(easyhandle, CURLOPT_POST, true)) ||
        (code = curl_easy_setopt(easyhandle, CURLOPT_URL, url.fullURL)) ||
        (code = curl_easy_setopt(easyhandle, CURLOPT_POSTFIELDS, msg)) ||
        (code = curl_easy_setopt(easyhandle, CURLOPT_POSTFIELDSIZE, size)) ||
        (code = curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, slist)) ||
        /*
         * slightly cheating here: when CURLOPT_CAINFO was set before, we don't unset it because
         * we don't know what the default is
         */
        (certificates[0] && (code = curl_easy_setopt(easyhandle, CURLOPT_CAINFO, certificates))) ||
        (code = curl_easy_setopt(easyhandle, CURLOPT_SSL_VERIFYPEER, (long)SSLVerifyServer)) ||
        (code = curl_easy_setopt(easyhandle, CURLOPT_SSL_VERIFYHOST, (long)(SSLVerifyHost ? 2 : 0))) ||
        (code = curl_easy_perform(easyhandle))) {
        delete [] responsebuffer;
        setErrorF(ERR_HTTP, "libcurl error %d, %.250s", code, curlerrortxt);
        LOG.error("%s", getLastErrorMsg());
    } else {
        response = responsebuffer;

        POSIX_LOG.setPrefix("data in: ");
        LOG.debug("=== %d bytes ===\n%s",
                  (int)strlen(response),
                  response);
    }
    POSIX_LOG.setPrefix(NULL);


    responsebuffer = NULL;
    responsebuffersize = 0;

    if (slist) {
        curl_slist_free_all(slist);
    }

    return response;
}
/*
 * 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;
}
void DeviceManagementNode::update(bool read) 
{
    if (!read && !modified) {
        // no work to be done
        return;
    }

    StringBuffer fileName(currentDir);
    concatDirs(fileName, configFile.c_str());
    const char* fname = fileName.c_str();
    FILE* file = fopen(fname, "r");
    
    if (!file) {
        // Maybe the file or directory does not exist: create it and try again.
        LOG.debug("Could not open file, create it empty: '%s'", fileName.c_str());
        mkdirAll(currentDir);
        file = fopen(fname, "w+");  // "w+" to create the file and be able to read/write
        
        // Anyway, set the last error so Clients can know the file was not found.
        setErrorF(ERR_DM_TREE_NOT_AVAILABLE, "File not found: '%s'", fileName.c_str());
    }

    if (file) {
        // Open a temp file in writing mode if we must update the config
        if (!read) {
            fclose(file);
            fileName.append(".tmp");
            file = fopen(fileName, "w");
            if (!file) {
                setErrorF(ERR_INVALID_CONTEXT, "Error opening file: '%s'", fileName.c_str());
                LOG.error("%s", getLastErrorMsg());
                return;
            }
        }

        if (read) {
            // Note: don't create local buffers too big, the Symbian stack size is limited!
            char buffer[128];

            lines->clear();
            while (fgets(buffer, sizeof(buffer), file)) {
                char *eol = strchr(buffer, '\r');
                if (!eol) {
                    eol = strchr(buffer, '\n');
                }
                if (eol) {
                    *eol = 0;
                }
                line newline(buffer);
                lines->add(newline);
            }
            fclose(file);
        } 
        else {
            int i = 0;
            while (true) {
                line *curr = (line *)lines->get(i);
                if (!curr) {
                    break;
                }
                fprintf(file, "%s\n", curr->getLine());

                i++;
            }
            fflush(file);
            if (!ferror(file)) {
                StringBuffer tmpConfig(configFile);
                tmpConfig += ".tmp";

                // Both files must be closed for the rename.
                int ret = fclose(file);
                if (ret) {
                    setErrorF(ret, "Error (%d) closing file: '%s'", ret, fileName.c_str());
                    return;
                }

                renameFileInCwd( tmpConfig.c_str(), configFile.c_str());
            }
            else {
                fclose(file);
            }
        }
    }
    else {
        setErrorF(ERR_DM_TREE_NOT_AVAILABLE, "Error opening file: '%s'", fileName.c_str());
        LOG.error("%s", getLastErrorMsg());
        return;
    }
}
示例#18
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;
}