示例#1
0
Status
loginServerUpdatePinPackage(const Login &login,
                            DataSlice DID, DataSlice LPIN1, const std::string &pinPackage,
                            time_t ali)
{
    const auto url = ABC_SERVER_ROOT "/account/pinpackage/update";

    // format the ali
    char szALI[DATETIME_LENGTH];
    strftime(szALI, DATETIME_LENGTH, "%Y-%m-%dT%H:%M:%S", gmtime(&ali));

    // Encode those:
    JsonPtr json(json_pack("{ss, ss, ss, ss, ss, ss}",
                           ABC_SERVER_JSON_L1_FIELD, base64Encode(login.lobby.authId()).c_str(),
                           ABC_SERVER_JSON_LP1_FIELD, base64Encode(login.authKey()).c_str(),
                           ABC_SERVER_JSON_DID_FIELD, base64Encode(DID).c_str(),
                           ABC_SERVER_JSON_LPIN1_FIELD, base64Encode(LPIN1).c_str(),
                           JSON_ACCT_PIN_PACKAGE, pinPackage.c_str(),
                           ABC_SERVER_JSON_ALI_FIELD, szALI));

    HttpReply reply;
    ABC_CHECK(AirbitzRequest().post(reply, url, json.encode()));
    ServerReplyJson replyJson;
    ABC_CHECK(replyJson.decode(reply.body));
    ABC_CHECK(replyJson.ok());

    return Status();
}
示例#2
0
Status
loginServerChangePassword(const Login &login,
                          DataSlice newLP1, DataSlice newLRA1,
                          const CarePackage &carePackage, const LoginPackage &loginPackage)
{
    const auto url = ABC_SERVER_ROOT "/account/password/update";
    JsonPtr json(json_pack("{ss, ss, ss, ss, ss}",
                           ABC_SERVER_JSON_L1_FIELD,      base64Encode(login.lobby.authId()).c_str(),
                           ABC_SERVER_JSON_LP1_FIELD,     base64Encode(login.authKey()).c_str(),
                           ABC_SERVER_JSON_NEW_LP1_FIELD, base64Encode(newLP1).c_str(),
                           ABC_SERVER_JSON_CARE_PACKAGE_FIELD,  carePackage.encode().c_str(),
                           ABC_SERVER_JSON_LOGIN_PACKAGE_FIELD, loginPackage.encode().c_str()));
    if (newLRA1.size())
    {
        json_object_set_new(json.get(), ABC_SERVER_JSON_NEW_LRA1_FIELD,
                            json_string(base64Encode(newLRA1).c_str()));
    }

    HttpReply reply;
    ABC_CHECK(AirbitzRequest().post(reply, url, json.encode()));
    ServerReplyJson replyJson;
    ABC_CHECK(replyJson.decode(reply.body));
    ABC_CHECK(replyJson.ok());

    return Status();
}
示例#3
0
Status
loginServerGetLoginPackage(const Lobby &lobby,
                           DataSlice LP1, DataSlice LRA1, LoginPackage &result, JsonPtr &rootKeyBox)
{
    const auto url = ABC_SERVER_ROOT "/account/loginpackage/get";
    ServerRequestJson json;
    ABC_CHECK(json.setup(lobby));
    if (LP1.size())
        ABC_CHECK(json.authKeySet(base64Encode(LP1)));
    if (LRA1.size())
        ABC_CHECK(json.recoveryAuthKeySet(base64Encode(LRA1)));

    HttpReply reply;
    ABC_CHECK(AirbitzRequest().post(reply, url, json.encode()));
    ServerReplyJson replyJson;
    ABC_CHECK(replyJson.decode(reply.body));
    ABC_CHECK(replyJson.ok());

    struct ResultJson:
        public JsonObject
    {
        ABC_JSON_CONSTRUCTORS(ResultJson, JsonObject)
        ABC_JSON_STRING(package, "login_package", nullptr)
        ABC_JSON_VALUE(rootKeyBox, "rootKeyBox", JsonPtr)
    } resultJson(replyJson.results());

    ABC_CHECK(resultJson.packageOk());
    ABC_CHECK(result.decode(resultJson.package()));
    if (json_is_object(resultJson.rootKeyBox().get()))
        rootKeyBox = resultJson.rootKeyBox();
    return Status();
}
示例#4
0
/**
 * Activate an account on the server.
 *
 * @param LP1  Password hash for the account
 */
tABC_CC ABC_LoginServerActivate(const Lobby &lobby,
                                tABC_U08Buf LP1,
                                tABC_Error *pError)
{

    tABC_CC cc = ABC_CC_Ok;

    HttpReply reply;
    std::string url = ABC_SERVER_ROOT "/" ABC_SERVER_ACCOUNT_ACTIVATE;
    ServerReplyJson replyJson;
    char *szPost    = NULL;
    json_t *pJSON_Root = NULL;

    // create the post data
    pJSON_Root = json_pack("{ssss}",
        ABC_SERVER_JSON_L1_FIELD, base64Encode(lobby.authId()).c_str(),
        ABC_SERVER_JSON_LP1_FIELD, base64Encode(LP1).c_str());
    szPost = ABC_UtilStringFromJSONObject(pJSON_Root, JSON_COMPACT);

    // send the command
    ABC_CHECK_NEW(AirbitzRequest().post(reply, url, szPost));

    // decode the result
    ABC_CHECK_NEW(replyJson.decode(reply.body));
    ABC_CHECK_NEW(replyJson.ok());

exit:
    ABC_FREE_STR(szPost);
    if (pJSON_Root)     json_decref(pJSON_Root);

    return cc;
}
示例#5
0
static
tABC_CC ABC_WalletServerRepoPost(const Lobby &lobby,
                                 DataSlice LP1,
                                 const std::string &szWalletAcctKey,
                                 const char *szPath,
                                 tABC_Error *pError)
{
    tABC_CC cc = ABC_CC_Ok;

    const auto url = ABC_SERVER_ROOT "/" + std::string(szPath);
    HttpReply reply;
    ServerReplyJson replyJson;

    JsonPtr json(json_pack("{ssssss}",
                           ABC_SERVER_JSON_L1_FIELD, base64Encode(lobby.authId()).c_str(),
                           ABC_SERVER_JSON_LP1_FIELD, base64Encode(LP1).c_str(),
                           ABC_SERVER_JSON_REPO_WALLET_FIELD, szWalletAcctKey.c_str()));

    // send the command
    ABC_CHECK_NEW(AirbitzRequest().post(reply, url, json.encode()));

    ABC_CHECK_NEW(replyJson.decode(reply.body));
    ABC_CHECK_NEW(replyJson.ok());

exit:
    return cc;
}
示例#6
0
Status
loginServerGetPinPackage(DataSlice DID, DataSlice LPIN1, std::string &result,
                         AuthError &authError)
{
    const auto url = ABC_SERVER_ROOT "/v1/account/pinpackage/get";
    ServerRequestJson json;
    ABC_CHECK(json.set(ABC_SERVER_JSON_DID_FIELD, base64Encode(DID)));
    ABC_CHECK(json.set(ABC_SERVER_JSON_LPIN1_FIELD, base64Encode(LPIN1)));

    HttpReply reply;
    ABC_CHECK(AirbitzRequest().post(reply, url, json.encode()));
    ServerReplyJson replyJson;
    ABC_CHECK(replyJson.decode(reply, &authError));

    struct ResultJson:
        public JsonObject
    {
        ABC_JSON_CONSTRUCTORS(ResultJson, JsonObject)
        ABC_JSON_STRING(package, "pin_package", nullptr)
    } resultJson(replyJson.results());

    ABC_CHECK(resultJson.packageOk());
    result = resultJson.package();
    return Status();
}
示例#7
0
/**
 * Changes the password for an account on the server.
 *
 * This function sends information to the server to change the password for an account.
 * Either the old LP1 or LRA1 can be used for authentication.
 *
 * @param oldLP1 Old password hash for the account (if this is empty, LRA1 is used instead)
 * @param LRA1   LRA1 for the account (used if oldP1 is empty)
 */
tABC_CC ABC_LoginServerChangePassword(const Lobby &lobby,
                                      tABC_U08Buf oldLP1,
                                      tABC_U08Buf newLP1,
                                      tABC_U08Buf newLRA1,
                                      const CarePackage &carePackage,
                                      const LoginPackage &loginPackage,
                                      tABC_Error *pError)
{
    tABC_CC cc = ABC_CC_Ok;

    HttpReply reply;
    std::string url = ABC_SERVER_ROOT "/" ABC_SERVER_CHANGE_PASSWORD_PATH;
    ServerReplyJson replyJson;
    char *szPost    = NULL;
    std::string carePackageStr;
    std::string loginPackageStr;
    json_t *pJSON_OldLRA1   = NULL;
    json_t *pJSON_NewLRA1   = NULL;
    json_t *pJSON_Root = NULL;

    ABC_CHECK_NULL_BUF(oldLP1);
    ABC_CHECK_NULL_BUF(newLP1);

    ABC_CHECK_NEW(carePackage.encode(carePackageStr));
    ABC_CHECK_NEW(loginPackage.encode(loginPackageStr));

    // Encode those:
    pJSON_Root = json_pack("{ss, ss, ss, ss, ss}",
        ABC_SERVER_JSON_L1_FIELD,      base64Encode(lobby.authId()).c_str(),
        ABC_SERVER_JSON_LP1_FIELD,     base64Encode(oldLP1).c_str(),
        ABC_SERVER_JSON_NEW_LP1_FIELD, base64Encode(newLP1).c_str(),
        ABC_SERVER_JSON_CARE_PACKAGE_FIELD,  carePackageStr.c_str(),
        ABC_SERVER_JSON_LOGIN_PACKAGE_FIELD, loginPackageStr.c_str());

    // set up the recovery, if any:
    if (newLRA1.size())
    {
        pJSON_NewLRA1 = json_string(base64Encode(newLRA1).c_str());
        json_object_set(pJSON_Root, ABC_SERVER_JSON_NEW_LRA1_FIELD, pJSON_NewLRA1);
    }

    // create the post data
    szPost = ABC_UtilStringFromJSONObject(pJSON_Root, JSON_COMPACT);

    // send the command
    ABC_CHECK_NEW(AirbitzRequest().post(reply, url, szPost));

    ABC_CHECK_NEW(replyJson.decode(reply.body));
    ABC_CHECK_NEW(replyJson.ok());

exit:
    ABC_FREE_STR(szPost);
    if (pJSON_OldLRA1)  json_decref(pJSON_OldLRA1);
    if (pJSON_NewLRA1)  json_decref(pJSON_NewLRA1);
    if (pJSON_Root)     json_decref(pJSON_Root);

    return cc;
}
示例#8
0
Status
Login::repoFind(JsonPtr &result, const std::string &type, bool create)
{
    result = JsonPtr();

    // Try 1: Use what we have:
    repoFindLocal(result, type).log(); // Failure is fine
    if (result) return Status();

    // Try 2: Sync with the server:
    ABC_CHECK(update());
    repoFindLocal(result, type).log(); // Failure is fine
    if (result) return Status();

    // Try 3: Make a new repo:
    if (create)
    {
        // Make the keys:
        DataChunk dataKey;
        DataChunk syncKey;
        ABC_CHECK(randomData(dataKey, DATA_KEY_LENGTH));
        ABC_CHECK(randomData(syncKey, SYNC_KEY_LENGTH));
        AccountRepoJson repoJson;
        ABC_CHECK(repoJson.syncKeySet(base64Encode(syncKey)));
        ABC_CHECK(repoJson.dataKeySet(base64Encode(dataKey_)));

        // Make the metadata:
        DataChunk id;
        ABC_CHECK(randomData(id, keyIdLength));
        KeyJson keyJson;
        ABC_CHECK(keyJson.idSet(base64Encode(id)));
        ABC_CHECK(keyJson.typeSet(type));
        ABC_CHECK(keyJson.keysSet(repoJson));

        // Encrypt the metadata:
        JsonBox keyBox;
        ABC_CHECK(keyBox.encrypt(keyJson.encode(), dataKey_));

        // Push the wallet to the server:
        AuthJson authJson;
        ABC_CHECK(authJson.loginSet(*this));
        ABC_CHECK(loginServerKeyAdd(authJson, keyBox, base16Encode(syncKey)));

        // Save to disk:
        LoginStashJson stashJson;
        ABC_CHECK(stashJson.load(paths.stashPath()));
        if (!stashJson.keyBoxes().ok())
            ABC_CHECK(stashJson.keyBoxesSet(JsonArray()));
        ABC_CHECK(stashJson.keyBoxes().append(keyBox));
        ABC_CHECK(stashJson.save(paths.stashPath()));

        result = repoJson;
        return Status();
    }

    return ABC_ERROR(ABC_CC_AccountDoesNotExist, "No such repo");
}
示例#9
0
char const* H264VideoRTPSink::auxSDPLine() {

  liveLogInfo(" H264VideoRTPSink::auxSDPLine \n");
  
  // Generate a new "a=fmtp:" line each time, using our SPS and PPS (if we have them),
  // otherwise parameters from our framer source (in case they've changed since the last time that
  // we were called):
  H264or5VideoStreamFramer* framerSource = NULL;
  u_int8_t* vpsDummy = NULL; unsigned vpsDummySize = 0;
  u_int8_t* sps = fSPS; unsigned spsSize = fSPSSize;
  u_int8_t* pps = fPPS; unsigned ppsSize = fPPSSize;
  if (sps == NULL || pps == NULL) {
    // We need to get SPS and PPS from our framer source:
    if (fOurFragmenter == NULL) return NULL; // we don't yet have a fragmenter (and therefore not a source)
    framerSource = (H264or5VideoStreamFramer*)(fOurFragmenter->inputSource());
    if (framerSource == NULL) return NULL; // we don't yet have a source

    framerSource->getVPSandSPSandPPS(vpsDummy, vpsDummySize, sps, spsSize, pps, ppsSize);
    if (sps == NULL || pps == NULL) return NULL; // our source isn't ready
  }

  // Set up the "a=fmtp:" SDP line for this stream:
  u_int8_t* spsWEB = new u_int8_t[spsSize]; // "WEB" means "Without Emulation Bytes"
  unsigned spsWEBSize = removeH264or5EmulationBytes(spsWEB, spsSize, sps, spsSize);
  if (spsWEBSize < 4) { // Bad SPS size => assume our source isn't ready
    delete[] spsWEB;
    return NULL;
  }
  u_int32_t profileLevelId = (spsWEB[1]<<16) | (spsWEB[2]<<8) | spsWEB[3];
  delete[] spsWEB;

  char* sps_base64 = base64Encode((char*)sps, spsSize);
  char* pps_base64 = base64Encode((char*)pps, ppsSize);

  char const* fmtpFmt =
    "a=fmtp:%d packetization-mode=1"
    ";profile-level-id=%06X"
    ";sprop-parameter-sets=%s,%s\r\n";
  unsigned fmtpFmtSize = strlen(fmtpFmt)
    + 3 /* max char len */
    + 6 /* 3 bytes in hex */
    + strlen(sps_base64) + strlen(pps_base64);
  char* fmtp = new char[fmtpFmtSize];
  sprintf(fmtp, fmtpFmt,
          rtpPayloadType(),
	  profileLevelId,
          sps_base64, pps_base64);

  delete[] sps_base64;
  delete[] pps_base64;

  delete[] fFmtpSDPLine; fFmtpSDPLine = fmtp;
  return fFmtpSDPLine;
}
示例#10
0
Status
loginServerUploadLogs(Account *account)
{
    const auto url = ABC_SERVER_ROOT "/v1/account/debug";
    ServerRequestJson json;

    if (account)
    {
        json.setup(account->login); // Failure is fine

        JsonArray jsonArray;
        auto ids = account->wallets.list();
        for (const auto &id: ids)
        {
            std::shared_ptr<Wallet> wallet = cacheWalletSoft(id);
            if (wallet)
            {
                const auto name = wallet->name();
                logInfo("Wallet '" + name + "' " + id);

                const auto addresses = wallet->addresses.list();
                for (const auto &address: addresses)
                    logInfo(address);
            }

            DataChunk watchData;
            if (fileLoad(watchData, WalletPaths(id).cachePath()))
            {
                jsonArray.append(
                    json_string(base64Encode(watchData).c_str()));
            }
        }
        json.set("watchers", jsonArray); // Failure is fine

        AutoFree<tABC_AccountSettings, accountSettingsFree> settings;
        settings.get() = accountSettingsLoad(*account);
        std::string servers(settings->szOverrideBitcoinServerList);
        std::string strOverride = (settings->bOverrideBitcoinServers ? "true" :
                                   "false");

        logInfo("bOverrideBitcoinServers:" + strOverride);
        logInfo("szOverrideBitcoinServerList:" + servers);
    }

    DataChunk logData = debugLogLoad();
    json.set("log", base64Encode(logData)); // Failure is fine

    HttpReply reply;
    ABC_CHECK(AirbitzRequest().post(reply, url, json.encode()));

    return Status();
}
示例#11
0
error_t smtpSendAuthLogin(SmtpClientContext *context, const SmtpAuthInfo *authInfo)
{
#if (SMTP_LOGIN_AUTH_SUPPORT == ENABLED)
   error_t error;
   uint_t replyCode;

   //Send AUTH LOGIN command
   error = smtpSendCommand(context, "AUTH LOGIN\r\n", &replyCode, NULL);

   //Any communication error to report?
   if(error)
      return error;
   //Check SMTP reply code
   if(!SMTP_REPLY_CODE_3YZ(replyCode))
      return ERROR_AUTHENTICATION_FAILED;

   //Encode the user name with Base64 algorithm
   base64Encode(authInfo->userName, strlen(authInfo->userName), context->buffer, NULL);
   //Add a line feed
   strcat(context->buffer, "\r\n");

   //Send the resulting string
   error = smtpSendCommand(context, context->buffer, &replyCode, NULL);
   //Any communication error to report?
   if(error) return error;

   //Check SMTP reply code
   if(!SMTP_REPLY_CODE_3YZ(replyCode))
      return ERROR_AUTHENTICATION_FAILED;

   //Encode the password with Base64 algorithm
   base64Encode(authInfo->password, strlen(authInfo->password), context->buffer, NULL);
   //Add a line feed
   strcat(context->buffer, "\r\n");

   //Send the resulting string
   error = smtpSendCommand(context, context->buffer, &replyCode, NULL);
   //Any communication error to report?
   if(error) return error;

   //Check SMTP reply code
   if(!SMTP_REPLY_CODE_2YZ(replyCode))
      return ERROR_AUTHENTICATION_FAILED;

   //Successful authentication
   return NO_ERROR;
#else
   //LOGIN authentication is not supported
   return ERROR_AUTHENTICATION_FAILED;
#endif
}
char const *H264VideoRTPSink::auxSDPLine()
{
    // Generate a new "a=fmtp:" line each time, using parameters from
    // our framer source (in case they've changed since the last time that
    // we were called):
    if (fOurFragmenter == NULL) return NULL; // we don't yet have a fragmenter (and therefore not a source)
    H264VideoStreamFramer *framerSource = (H264VideoStreamFramer *)(fOurFragmenter->inputSource());
    if (framerSource == NULL) return NULL; // we don't yet have a source

    u_int8_t *sps;
    unsigned spsSize;
    u_int8_t *pps;
    unsigned ppsSize;
    framerSource->getSPSandPPS(sps, spsSize, pps, ppsSize);
    if (sps == NULL || pps == NULL) return NULL; // our source isn't ready

    u_int32_t profile_level_id;
    if (spsSize < 4)   // sanity check
    {
        profile_level_id = 0;
    }
    else
    {
        profile_level_id = (sps[1] << 16) | (sps[2] << 8) | sps[3]; // profile_idc|constraint_setN_flag|level_idc
    }

    // Set up the "a=fmtp:" SDP line for this stream:
    char *sps_base64 = base64Encode((char *)sps, spsSize);
    char *pps_base64 = base64Encode((char *)pps, ppsSize);
    char const *fmtpFmt =
        "a=fmtp:%d packetization-mode=1"
        ";profile-level-id=%06X"
        ";sprop-parameter-sets=%s,%s\r\n";
    unsigned fmtpFmtSize = strlen(fmtpFmt)
                           + 3 /* max char len */
                           + 6 /* 3 bytes in hex */
                           + strlen(sps_base64) + strlen(pps_base64);
    char *fmtp = new char[fmtpFmtSize];
    sprintf(fmtp, fmtpFmt,
            rtpPayloadType(),
            profile_level_id,
            sps_base64, pps_base64);
    delete[] sps_base64;
    delete[] pps_base64;

    delete[] fFmtpSDPLine;
    fFmtpSDPLine = fmtp;
    return fFmtpSDPLine;
}
示例#13
0
/**
 * Uploads the pin package.
 *
 * @param LP1           Login + Password hash
 * @param DID           Device Id
 * @param LPIN1         Hashed pin
 * @param szPinPackage  Pin package
 * @param szAli         auto-logout interval
 */
tABC_CC ABC_LoginServerUpdatePinPackage(const Lobby &lobby,
                                        tABC_U08Buf LP1,
                                        tABC_U08Buf DID,
                                        tABC_U08Buf LPIN1,
                                        const std::string &pinPackage,
                                        time_t ali,
                                        tABC_Error *pError)
{
    tABC_CC cc = ABC_CC_Ok;

    HttpReply reply;
    std::string url = ABC_SERVER_ROOT "/" ABC_SERVER_PIN_PACK_UPDATE_PATH;
    ServerReplyJson replyJson;
    char *szPost         = NULL;
    json_t *pJSON_Root   = NULL;
    char szALI[DATETIME_LENGTH];

    ABC_CHECK_NULL_BUF(LP1);
    ABC_CHECK_NULL_BUF(DID);
    ABC_CHECK_NULL_BUF(LPIN1);

    // format the ali
    strftime(szALI, DATETIME_LENGTH, "%Y-%m-%dT%H:%M:%S", gmtime(&ali));

    // Encode those:
    pJSON_Root = json_pack("{ss, ss, ss, ss, ss, ss}",
        ABC_SERVER_JSON_L1_FIELD, base64Encode(lobby.authId()).c_str(),
        ABC_SERVER_JSON_LP1_FIELD, base64Encode(LP1).c_str(),
        ABC_SERVER_JSON_DID_FIELD, base64Encode(DID).c_str(),
        ABC_SERVER_JSON_LPIN1_FIELD, base64Encode(LPIN1).c_str(),
        JSON_ACCT_PIN_PACKAGE, pinPackage.c_str(),
        ABC_SERVER_JSON_ALI_FIELD, szALI);

    // create the post data
    szPost = ABC_UtilStringFromJSONObject(pJSON_Root, JSON_COMPACT);

    // send the command
    ABC_CHECK_NEW(AirbitzRequest().post(reply, url, szPost));

    ABC_CHECK_NEW(replyJson.decode(reply.body));
    ABC_CHECK_NEW(replyJson.ok());

exit:
    ABC_FREE_STR(szPost);
    if (pJSON_Root)     json_decref(pJSON_Root);

    return cc;
}
void MHTMLArchive::generateMHTMLPart(
    const String& boundary,
    EncodingPolicy encodingPolicy,
    const SerializedResource& resource,
    SharedBuffer& outputBuffer)
{
    StringBuilder stringBuilder;
    stringBuilder.append("--" + boundary + "\r\n");
    stringBuilder.appendLiteral("Content-Type: ");
    stringBuilder.append(resource.mimeType);

    const char* contentEncoding = 0;
    if (encodingPolicy == UseBinaryEncoding)
        contentEncoding = binary;
    else if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(resource.mimeType) || MIMETypeRegistry::isSupportedNonImageMIMEType(resource.mimeType))
        contentEncoding = quotedPrintable;
    else
        contentEncoding = base64;

    stringBuilder.appendLiteral("\r\nContent-Transfer-Encoding: ");
    stringBuilder.append(contentEncoding);
    stringBuilder.appendLiteral("\r\nContent-Location: ");
    stringBuilder.append(resource.url);
    stringBuilder.appendLiteral("\r\n\r\n");

    CString asciiString = stringBuilder.toString().utf8();
    outputBuffer.append(asciiString.data(), asciiString.length());

    if (!strcmp(contentEncoding, binary)) {
        const char* data;
        size_t position = 0;
        while (size_t length = resource.data->getSomeData(data, position)) {
            outputBuffer.append(data, length);
            position += length;
        }
    } else {
        // FIXME: ideally we would encode the content as a stream without having to fetch it all.
        const char* data = resource.data->data();
        size_t dataLength = resource.data->size();
        Vector<char> encodedData;
        if (!strcmp(contentEncoding, quotedPrintable)) {
            quotedPrintableEncode(data, dataLength, encodedData);
            outputBuffer.append(encodedData.data(), encodedData.size());
            outputBuffer.append("\r\n", 2);
        } else {
            ASSERT(!strcmp(contentEncoding, base64));
            // We are not specifying insertLFs = true below as it would cut the lines with LFs and MHTML requires CRLFs.
            base64Encode(data, dataLength, encodedData);
            const size_t maximumLineLength = 76;
            size_t index = 0;
            size_t encodedDataLength = encodedData.size();
            do {
                size_t lineLength = std::min(encodedDataLength - index, maximumLineLength);
                outputBuffer.append(encodedData.data() + index, lineLength);
                outputBuffer.append("\r\n", 2);
                index += maximumLineLength;
            } while (index < encodedDataLength);
        }
    }
}
示例#15
0
String ImageBuffer::toDataURL(const String& mimeType, Optional<double> quality, CoordinateSystem) const
{
    ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));

    cairo_surface_t* image = cairo_get_target(context().platformContext()->cr());

    Vector<char> encodedImage;

    if (!image)
        return "data:,";

    if (mimeType == "image/png") {
        if (!encodeImagePNG(image, &encodedImage))
            return "data:,";
    }

    if (mimeType == "image/jpeg") {
        int width = cairo_image_surface_get_width(image);
        int height = cairo_image_surface_get_height(image);

        IntSize size(width, height);
        IntRect dataRect(IntPoint(), size);
        RefPtr<Uint8ClampedArray> myData = getPremultipliedImageData(dataRect);

        if (!encodeImageJPEG(myData->data(), size, &encodedImage, quality))
            return "data:,";
    }

    Vector<char> base64Data;
    base64Encode(encodedImage, base64Data);

    return "data:" + mimeType + ";base64," + base64Data;
}
示例#16
0
bool RtspThread::sendCommand( std::string message )
{
	if ( mNeedAuth ) {
	    StringVector parts = split( message, " " );
	    if (parts.size() > 1)
	    	message += mAuthenticator->getAuthHeader(parts[0], parts[1]);
	}
    message += stringtf( "User-Agent: ZoneMinder/%s\r\n", ZM_VERSION );
    message += stringtf( "CSeq: %d\r\n\r\n", ++mSeq );
    Debug( 2, "Sending RTSP message: %s", message.c_str() );
    if ( mMethod == RTP_RTSP_HTTP )
    {
        message = base64Encode( message );
        Debug( 2, "Sending encoded RTSP message: %s", message.c_str() );
        if ( mRtspSocket2.send( message.c_str(), message.size() ) != (int)message.length() )
        {
            Error( "Unable to send message '%s': %s", message.c_str(), strerror(errno) );
            return( false );
        }
    }
    else
    {
        if ( mRtspSocket.send( message.c_str(), message.size() ) != (int)message.length() )
        {
            Error( "Unable to send message '%s': %s", message.c_str(), strerror(errno) );
            return( false );
        }
    }
    return( true );
}
PassOwnPtr<Vector<char>> PictureSnapshot::replay(unsigned fromStep, unsigned toStep, double scale) const
{
    const SkIRect bounds = m_picture->cullRect().roundOut();

    // TODO(fmalita): convert this to SkSurface/SkImage, drop the intermediate SkBitmap.
    SkBitmap bitmap;
    bitmap.allocPixels(SkImageInfo::MakeN32Premul(bounds.width(), bounds.height()));
    bitmap.eraseARGB(0, 0, 0, 0);
    {
        ReplayingCanvas canvas(bitmap, fromStep, toStep);
        canvas.scale(scale, scale);
        canvas.resetStepCount();
        m_picture->playback(&canvas, &canvas);
    }
    OwnPtr<Vector<char>> base64Data = adoptPtr(new Vector<char>());
    Vector<char> encodedImage;

    RefPtr<SkImage> image = adoptRef(SkImage::NewFromBitmap(bitmap));
    if (!image)
        return nullptr;

    ImagePixelLocker pixelLocker(image, kUnpremul_SkAlphaType);
    ImageDataBuffer imageData(IntSize(image->width(), image->height()),
        static_cast<const unsigned char*>(pixelLocker.pixels()));
    if (!PNGImageEncoder::encode(imageData, reinterpret_cast<Vector<unsigned char>*>(&encodedImage)))
        return nullptr;

    base64Encode(encodedImage, *base64Data);
    return base64Data.release();
}
static bool saveArchiveResourceField(xmlTextWriterPtr writer, const xmlChar* tag, const char* data, int size)
{
    int result = xmlTextWriterStartElement(writer, tag);
    if (result < 0) {
        LOGD("saveArchiveResourceField: Failed to start element.");
        return false;
    }

    if (size > 0) {
        Vector<char> base64Data;
        base64Encode(data, size, base64Data, false);
        if (base64Data.isEmpty()) {
            LOGD("saveArchiveResourceField: Failed to base64 encode data.");
            return false;
        }

        result = xmlTextWriterWriteRawLen(writer, BAD_CAST base64Data.data(), base64Data.size());
        if (result < 0) {
            LOGD("saveArchiveResourceField: Failed to write data.");
            return false;
        }
    }

    result = xmlTextWriterEndElement(writer);
    if (result < 0) {
        LOGD("saveArchiveResourceField: Failed to end element.");
        return false;
    }

    return true;
}
示例#19
0
bool RtspThread::sendCommand( std::string message )
{
    if ( !mAuth.empty() )
        message += stringtf( "Authorization: Basic %s\r\n", mAuth64.c_str() );
    message += stringtf( "User-Agent: ZoneMinder/%s\r\n", ZM_VERSION );
    message += stringtf( "CSeq: %d\r\n\r\n", ++mSeq );
    Debug( 2, "Sending RTSP message: %s", message.c_str() );
    if ( mMethod == RTP_RTSP_HTTP )
    {
        message = base64Encode( message );
        Debug( 2, "Sending encoded RTSP message: %s", message.c_str() );
        if ( mRtspSocket2.send( message.c_str(), message.size() ) != (int)message.length() )
        {
            Error( "Unable to send message '%s': %s", message.c_str(), strerror(errno) );
            return( false );
        }
    }
    else
    {
        if ( mRtspSocket.send( message.c_str(), message.size() ) != (int)message.length() )
        {
            Error( "Unable to send message '%s': %s", message.c_str(), strerror(errno) );
            return( false );
        }
    }
    return( true );
}
示例#20
0
Status
ServerRequestJson::setup(const Login &login)
{
    ABC_CHECK(setup(login.lobby));
    ABC_CHECK(authKeySet(base64Encode(login.authKey())));
    return Status();
}
示例#21
0
std::string Authenticator::getAuthHeader(std::string method, std::string uri) 
{
    std::string result = "Authorization: ";
    if (fAuthMethod == AUTH_BASIC) 
    {
        result += "Basic " + base64Encode( username() + ":" + password() );
    }
    else if (fAuthMethod == AUTH_DIGEST)
    {
        result += std::string("Digest ") + 
        		  "username=\"" + quote(username()) + "\", realm=\"" + quote(realm()) + "\", " +
                  "nonce=\"" + quote(nonce()) + "\", uri=\"" + quote(uri) + "\"";
		if ( ! fQop.empty() ) {
			result += ", qop=" + fQop;
			result += ", nc=" + stringtf("%08x",nc);
			result += ", cnonce=\"" + fCnonce + "\"";
		}
		result += ", response=\"" + computeDigestResponse(method, uri) + "\"";
		result += ", algorithm=\"MD5\"";
                  
        //Authorization: Digest username="******",
        //                      realm="NC-336PW-HD-1080P",
        //                      nonce="de8859d97609a6fcc16eaba490dcfd80",
        //                      uri="rtsp://10.192.16.8:554/live/0/h264.sdp",
        //                      response="4092120557d3099a163bd51a0d59744d",
        //                      algorithm=MD5,
        //                      opaque="5ccc069c403ebaf9f0171e9517f40e41",
        //                      qop="auth",
        //                      cnonce="c8051140765877dc",
        //                      nc=00000001
        
    }
    result += "\r\n";
    return result;
}
示例#22
0
String ImageBuffer::toDataURL(const String& mimeType, const double*) const
{
    if (!m_data.m_bitmap->bytes())
        return "data:,";

    Vector<char> output;
    const char* header;
    if (mimeType.lower() == "image/png") {
        if (!compressBitmapToPng(m_data.m_bitmap.get(), output))
            return "data:,";
        header = "data:image/png;base64,";
    } else {
        if (!compressBitmapToJpeg(m_data.m_bitmap.get(), output))
            return "data:,";
        header = "data:image/jpeg;base64,";
    }

    Vector<char> base64;
    base64Encode(output, base64);

    output.clear();

    Vector<char> url;
    url.append(header, strlen(header));
    url.append(base64);

    return String(url.data(), url.size());
}
示例#23
0
Status
ServerRequestJson::setup(const Login &login)
{
    ABC_CHECK(setup(login.store));
    ABC_CHECK(passwordAuthSet(base64Encode(login.passwordAuth())));
    return Status();
}
示例#24
0
static String generateSecWebSocketKey()
{
    static const size_t nonceSize = 16;
    unsigned char key[nonceSize];
    cryptographicallyRandomValues(key, nonceSize);
    return base64Encode(reinterpret_cast<char*>(key), nonceSize);
}
示例#25
0
void RemoteCamera::Initialise()
{
    if( protocol.empty() )
        Fatal( "No protocol specified for remote camera" );

    if( host.empty() )
        Fatal( "No host specified for remote camera" );

    if( port.empty() )
        Fatal( "No port specified for remote camera" );

    //if( path.empty() )
    //Fatal( "No path specified for remote camera" );

    // Cache as much as we can to speed things up
    std::string::size_type authIndex = host.find( '@' );

    if ( authIndex != std::string::npos )
    {
        auth = host.substr( 0, authIndex );
        host.erase( 0, authIndex+1 );
        auth64 = base64Encode( auth );
    }

    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    int ret = getaddrinfo(host.c_str(), port.c_str(), &hints, &hp);
    if ( ret != 0 )
    {
        Fatal( "Can't getaddrinfo(%s port %s): %s", host.c_str(), port.c_str(), gai_strerror(ret) );
    }
}
示例#26
0
void NPDF::writeXMLPacketData(std::ostream& out) const {
    if (! data_) {
        // We have an empty PDF packet.
        out << "  <pdf encoding=\"null\"></pdf>\n";
        return;
    }

    char* base64;
    size_t len64 = base64Encode(data_, size_, &base64);
    if (! base64) {
        out << "  <pdf encoding=\"null\"></pdf>\n";
        return;
    }

    out << "  <pdf encoding=\"base64\">\n";
    const char* pos = base64;
    while (len64 > BASE64_LINE_LEN) {
        out.write(pos, BASE64_LINE_LEN);
        out << std::endl;

        pos += BASE64_LINE_LEN;
        len64 -= BASE64_LINE_LEN;
    }
    if (len64 > 0) {
        out.write(pos, len64);
        out << std::endl;
    }
    out << "  </pdf>\n";

    delete[] base64;
}
示例#27
0
Status
loginServerPasswordSet(AuthJson authJson,
                       DataSlice passwordAuth,
                       JsonPtr passwordKeySnrp,
                       JsonPtr passwordBox,
                       JsonPtr passwordAuthBox)
{
    const auto url = ABC_SERVER_ROOT "/v2/login/password";

    JsonSnrp passwordAuthSnrp;
    ABC_CHECK(passwordAuthSnrp.snrpSet(usernameSnrp()));

    JsonObject dataJson;
    ABC_CHECK(dataJson.set("passwordAuth", base64Encode(passwordAuth)));
    ABC_CHECK(dataJson.set("passwordAuthSnrp", passwordAuthSnrp));
    ABC_CHECK(dataJson.set("passwordKeySnrp", passwordKeySnrp));
    ABC_CHECK(dataJson.set("passwordBox", passwordBox));
    ABC_CHECK(dataJson.set("passwordAuthBox", passwordAuthBox));
    ABC_CHECK(authJson.set("data", dataJson));

    HttpReply reply;
    ABC_CHECK(AirbitzRequest().request(reply, url, "PUT", authJson.encode()));
    ServerReplyJson replyJson;
    ABC_CHECK(replyJson.decode(reply));

    return Status();
}
PassRefPtr<JSONObject> ForensicReceiveDataEvent::serialize(){
	RefPtr<JSONObject> retval = ForensicEvent::serialize("ForensicReceiveDataEvent");
	retval->setString("data", base64Encode(data()));
	retval->setNumber("encodedDataLength", encodedDataLength());

	return retval;
}
示例#29
0
static String CGImageToDataURL(CGImageRef image, const String& mimeType, const double* quality)
{
    RetainPtr<CFMutableDataRef> data(AdoptCF, CFDataCreateMutable(kCFAllocatorDefault, 0));
    if (!data)
        return "data:,";

    RetainPtr<CFStringRef> uti = utiFromMIMEType(mimeType);
    ASSERT(uti);

    RetainPtr<CGImageDestinationRef> destination(AdoptCF, CGImageDestinationCreateWithData(data.get(), uti.get(), 1, 0));
    if (!destination)
        return "data:,";

    RetainPtr<CFDictionaryRef> imageProperties = 0;
    if (CFEqual(uti.get(), jpegUTI()) && quality && *quality >= 0.0 && *quality <= 1.0) {
        // Apply the compression quality to the image destination.
        RetainPtr<CFNumberRef> compressionQuality(AdoptCF, CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, quality));
        const void* key = kCGImageDestinationLossyCompressionQuality;
        const void* value = compressionQuality.get();
        imageProperties.adoptCF(CFDictionaryCreate(0, &key, &value, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
    }

    // Setting kCGImageDestinationBackgroundColor to black in imageProperties would allow saving some math in the
    // calling functions, but it doesn't seem to work.

    CGImageDestinationAddImage(destination.get(), image, imageProperties.get());
    CGImageDestinationFinalize(destination.get());

    Vector<char> out;
    base64Encode(reinterpret_cast<const char*>(CFDataGetBytePtr(data.get())), CFDataGetLength(data.get()), out);

    return "data:" + mimeType + ";base64," + out;
}
示例#30
0
RtspThread::RtspThread( int id, RtspMethod method, const std::string &protocol, const std::string &host, const std::string &port, const std::string &path, const std::string &auth ) :
    mId( id ),
    mMethod( method ),
    mProtocol( protocol ),
    mHost( host ),
    mPort( port ),
    mPath( path ),
    mAuth( auth ),
    mFormatContext( 0 ),
    mSeq( 0 ),
    mSession( 0 ),
    mSsrc( 0 ),
    mDist( UNDEFINED ),
    mRtpTime( 0 ),
    mStop( false )
{
    mUrl = mProtocol+"://"+mHost+":"+mPort;
    if ( !mPath.empty() )
    {
        if ( mPath[0] == '/' )
            mUrl += mPath;
        else
            mUrl += '/'+mPath;
    }

    mSsrc = rand();

    Debug( 2, "RTSP Local SSRC is %x", mSsrc );

    if ( mMethod == RTP_RTSP_HTTP )
        mHttpSession = stringtf( "%d", rand() );

    if ( !mAuth.empty() )
        mAuth64 = base64Encode( mAuth );
}