/* Copyright (c) 2021, Grégory Soutadé All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "drmprocessorclientimpl.h" /* Digest interface */ void* DRMProcessorClientImpl::createDigest(const std::string& digestName) { EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); const EVP_MD* md = EVP_get_digestbyname(digestName.c_str()); if (EVP_DigestInit(md_ctx, md) != 1) { EVP_MD_CTX_free(md_ctx); return 0; } return md_ctx; } int DRMProcessorClientImpl::digestUpdate(void* handler, unsigned char* data, unsigned int length) { return (EVP_DigestUpdate((EVP_MD_CTX *)handler, data, length)) ? 0 : -1; } int DRMProcessorClientImpl::digestFinalize(void* handler, unsigned char* digestOut) { int res = EVP_DigestFinal((EVP_MD_CTX *)handler, digestOut, NULL); EVP_MD_CTX_free((EVP_MD_CTX *)handler); return (res == 1) ? 0 : -1; } int DRMProcessorClientImpl::digest(const std::string& digestName, unsigned char* data, unsigned int length, unsigned char* digestOut) { void* handler = createDigest(digestName); if (!handler) return -1; if (digestUpdate(handler, data, length)) return -1; return digestFinalize(handler, digestOut); } /* Random interface */ void DRMProcessorClientImpl::randBytes(unsigned char* bytesOut, unsigned int length) { RAND_bytes(bytesOut, length); } /* HTTP interface */ #define HTTP_REQ_MAX_RETRY 5 #define DISPLAY_THRESHOLD 10*1024 // Threshold to display download progression static unsigned downloadedBytes; static int downloadProgress(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) { // For "big" files only if (dltotal >= DISPLAY_THRESHOLD && gourou::logLevel >= gourou::WARN) { int percent = 0; if (dltotal) percent = (dlnow * 100) / dltotal; std::cout << "\rDownload " << percent << "%" << std::flush; } return 0; } static size_t curlRead(void *data, size_t size, size_t nmemb, void *userp) { gourou::ByteArray* replyData = (gourou::ByteArray*) userp; replyData->append((unsigned char*)data, size*nmemb); return size*nmemb; } static size_t curlReadFd(void *data, size_t size, size_t nmemb, void *userp) { int fd = *(int*) userp; size_t res = write(fd, data, size*nmemb); downloadedBytes += res; return res; } static size_t curlHeaders(char *buffer, size_t size, size_t nitems, void *userdata) { std::map* responseHeaders = (std::map*)userdata; std::string::size_type pos = 0; std::string buf(buffer, size*nitems); pos = buf.find(":", pos); if (pos != std::string::npos) { std::string key = std::string(buffer, pos); std::string value = std::string(&buffer[pos+1], (size*nitems)-(pos+1)); key = gourou::trim(key); value = gourou::trim(value); (*responseHeaders)[key] = value; if (gourou::logLevel >= gourou::DEBUG) std::cout << key << " : " << value << std::endl; } return size*nitems; } std::string DRMProcessorClientImpl::sendHTTPRequest(const std::string& URL, const std::string& POSTData, const std::string& contentType, std::map* responseHeaders, int fd, bool resume) { gourou::ByteArray replyData; std::map localHeaders; if (!responseHeaders) responseHeaders = &localHeaders; GOUROU_LOG(gourou::INFO, "Send request to " << URL); if (POSTData.size()) { GOUROU_LOG(gourou::DEBUG, "<<< " << std::endl << POSTData); } unsigned prevDownloadedBytes; downloadedBytes = 0; if (fd && resume) { struct stat _stat; if (!fstat(fd, &_stat)) { GOUROU_LOG(gourou::WARN, "Resume download @ " << _stat.st_size << " bytes"); downloadedBytes = _stat.st_size; } else GOUROU_LOG(gourou::WARN, "Want to resume, but fstat failed"); } CURL *curl = curl_easy_init(); CURLcode res; curl_easy_setopt(curl, CURLOPT_URL, URL.c_str()); curl_easy_setopt(curl, CURLOPT_USERAGENT, "book2png"); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); struct curl_slist *list = NULL; list = curl_slist_append(list, "Accept: */*"); std::string _contentType; if (contentType.size()) { _contentType = "Content-Type: " + contentType; list = curl_slist_append(list, _contentType.c_str()); } curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list); if (POSTData.size()) { curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, POSTData.size()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, POSTData.data()); } if (fd) { curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlReadFd); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&fd); } else { curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlRead); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&replyData); } curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, curlHeaders); curl_easy_setopt(curl, CURLOPT_HEADERDATA, (void*)responseHeaders); curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, downloadProgress); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0); for (int i=0; i try again without incrementing tries else if (res == CURLE_RECV_ERROR) { if (prevDownloadedBytes != downloadedBytes) { GOUROU_LOG(gourou::WARN, "\nConnection broken, but data received, try again"); i--; } else GOUROU_LOG(gourou::WARN, "\nConnection broken and no data received, attempt " << (i+1) << "/" << HTTP_REQ_MAX_RETRY); } // Other error --> fail else break; // Wait a little bit (250ms * i) usleep((250 * 1000) * (i+1)); } curl_slist_free_all(list); curl_easy_cleanup(curl); if (res != CURLE_OK) EXCEPTION(gourou::CLIENT_NETWORK_ERROR, "Error " << curl_easy_strerror(res)); if ((downloadedBytes >= DISPLAY_THRESHOLD || replyData.size() >= DISPLAY_THRESHOLD) && gourou::logLevel >= gourou::WARN) std::cout << std::endl; if ((*responseHeaders)["Content-Type"] == "application/vnd.adobe.adept+xml") { GOUROU_LOG(gourou::DEBUG, ">>> " << std::endl << replyData.data()); } return std::string((char*)replyData.data(), replyData.length()); } void DRMProcessorClientImpl::RSAPrivateEncrypt(const unsigned char* RSAKey, unsigned int RSAKeyLength, const RSA_KEY_TYPE keyType, const std::string& password, const unsigned char* data, unsigned dataLength, unsigned char* res) { PKCS12 * pkcs12; EVP_PKEY* pkey; X509* cert; STACK_OF(X509)* ca; RSA * rsa; pkcs12 = d2i_PKCS12(NULL, &RSAKey, RSAKeyLength); if (!pkcs12) EXCEPTION(gourou::CLIENT_INVALID_PKCS12, ERR_error_string(ERR_get_error(), NULL)); PKCS12_parse(pkcs12, password.c_str(), &pkey, &cert, &ca); rsa = EVP_PKEY_get1_RSA(pkey); int ret = RSA_private_encrypt(dataLength, data, res, rsa, RSA_PKCS1_PADDING); if (ret < 0) EXCEPTION(gourou::CLIENT_RSA_ERROR, ERR_error_string(ERR_get_error(), NULL)); if (gourou::logLevel >= gourou::DEBUG) { printf("Encrypted : "); for(int i=0; i= gourou::DEBUG) { printf("Decrypted : "); for(int i=0; i