Esempio n. 1
0
void MemberExpr::print(StringBuilder& buffer, unsigned indent) const {
    buffer.indent(indent);
    buffer.setColor(COL_EXPR);
    buffer << "MemberExpr";
    buffer.setColor(COL_ATTR);
    if (isModulePrefix()) buffer << " mod-prefix";
    buffer << ' ';
    Expr::print(buffer, 0);
    buffer << '\n';
    buffer.indent(indent + INDENT);
    buffer.setColor(COL_ATTR);
    buffer << "LHS=\n";
    Base->print(buffer, indent + INDENT);
    buffer.indent(indent + INDENT);
    buffer.setColor(COL_ATTR);
    buffer << "RHS=";
    buffer.setColor(COL_VALUE);
    buffer << member << '\n';
    buffer.indent(indent);
    buffer.setColor(COL_ATTR);
    buffer << "decl=";
    if (decl) {
        buffer << decl->getName();
    } else {
        buffer.setColor(ANSI_RED);
        buffer << "NULL";
    }
    buffer << '\n';
}
void InbandTextTrackPrivateAVF::processCueAttributes(CFAttributedStringRef attributedString, GenericCueData* cueData)
{
    // Some of the attributes we translate into per-cue WebVTT settings are are repeated on each part of an attributed string so only
    // process the first instance of each.
    enum AttributeFlags {
        Line = 1 << 0,
        Position = 1 << 1,
        Size = 1 << 2,
        Vertical = 1 << 3,
        Align = 1 << 4,
        FontName = 1 << 5
    };
    unsigned processed = 0;

    StringBuilder content;
    String attributedStringValue = CFAttributedStringGetString(attributedString);
    CFIndex length = attributedStringValue.length();
    if (!length)
        return;

    CFRange effectiveRange = CFRangeMake(0, 0);
    while ((effectiveRange.location + effectiveRange.length) < length) {

        CFDictionaryRef attributes = CFAttributedStringGetAttributes(attributedString, effectiveRange.location + effectiveRange.length, &effectiveRange);
        if (!attributes)
            continue;

        StringBuilder tagStart;
        CFStringRef valueString;
        String tagEnd;
        CFIndex attributeCount = CFDictionaryGetCount(attributes);
        Vector<const void*> keys(attributeCount);
        Vector<const void*> values(attributeCount);
        CFDictionaryGetKeysAndValues(attributes, keys.data(), values.data());

        for (CFIndex i = 0; i < attributeCount; ++i) {
            CFStringRef key = static_cast<CFStringRef>(keys[i]);
            CFTypeRef value = values[i];
            if (CFGetTypeID(key) != CFStringGetTypeID() || !CFStringGetLength(key))
                continue;

            if (CFStringCompare(key, kCMTextMarkupAttribute_Alignment, 0) == kCFCompareEqualTo) {
                valueString = static_cast<CFStringRef>(value);
                if (CFGetTypeID(valueString) != CFStringGetTypeID() || !CFStringGetLength(valueString))
                    continue;
                if (processed & Align)
                    continue;
                processed |= Align;

                if (CFStringCompare(valueString, kCMTextMarkupAlignmentType_Start, 0) == kCFCompareEqualTo)
                    cueData->setAlign(GenericCueData::Start);
                else if (CFStringCompare(valueString, kCMTextMarkupAlignmentType_Middle, 0) == kCFCompareEqualTo)
                    cueData->setAlign(GenericCueData::Middle);
                else if (CFStringCompare(valueString, kCMTextMarkupAlignmentType_End, 0) == kCFCompareEqualTo)
                    cueData->setAlign(GenericCueData::End);
                else
                    ASSERT_NOT_REACHED();

                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_BoldStyle, 0) == kCFCompareEqualTo) {
                if (static_cast<CFBooleanRef>(value) != kCFBooleanTrue)
                    continue;

                tagStart.append("<b>");
                tagEnd.insert("</b>", 0);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_ItalicStyle, 0) == kCFCompareEqualTo) {
                if (static_cast<CFBooleanRef>(value) != kCFBooleanTrue)
                    continue;

                tagStart.append("<i>");
                tagEnd.insert("</i>", 0);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_UnderlineStyle, 0) == kCFCompareEqualTo) {
                if (static_cast<CFBooleanRef>(value) != kCFBooleanTrue)
                    continue;

                tagStart.append("<u>");
                tagEnd.insert("</u>", 0);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_OrthogonalLinePositionPercentageRelativeToWritingDirection, 0) == kCFCompareEqualTo) {
                if (CFGetTypeID(value) != CFNumberGetTypeID())
                    continue;
                if (processed & Line)
                    continue;
                processed |= Line;

                CFNumberRef valueNumber = static_cast<CFNumberRef>(value);
                double line;
                CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &line);
                cueData->setLine(line);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_TextPositionPercentageRelativeToWritingDirection, 0) == kCFCompareEqualTo) {
                if (CFGetTypeID(value) != CFNumberGetTypeID())
                    continue;
                if (processed & Position)
                    continue;
                processed |= Position;

                CFNumberRef valueNumber = static_cast<CFNumberRef>(value);
                double position;
                CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &position);
                cueData->setPosition(position);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_WritingDirectionSizePercentage, 0) == kCFCompareEqualTo) {
                if (CFGetTypeID(value) != CFNumberGetTypeID())
                    continue;
                if (processed & Size)
                    continue;
                processed |= Size;

                CFNumberRef valueNumber = static_cast<CFNumberRef>(value);
                double size;
                CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &size);
                cueData->setSize(size);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_VerticalLayout, 0) == kCFCompareEqualTo) {
                valueString = static_cast<CFStringRef>(value);
                if (CFGetTypeID(valueString) != CFStringGetTypeID() || !CFStringGetLength(valueString))
                    continue;

                if (CFStringCompare(valueString, kCMTextVerticalLayout_LeftToRight, 0) == kCFCompareEqualTo)
                    tagStart.append(leftToRightMark);
                else if (CFStringCompare(valueString, kCMTextVerticalLayout_RightToLeft, 0) == kCFCompareEqualTo)
                    tagStart.append(rightToLeftMark);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_BaseFontSizePercentageRelativeToVideoHeight, 0) == kCFCompareEqualTo) {
                if (CFGetTypeID(value) != CFNumberGetTypeID())
                    continue;

                CFNumberRef valueNumber = static_cast<CFNumberRef>(value);
                double baseFontSize;
                CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &baseFontSize);
                cueData->setBaseFontSize(baseFontSize);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_RelativeFontSize, 0) == kCFCompareEqualTo) {
                if (CFGetTypeID(value) != CFNumberGetTypeID())
                    continue;

                CFNumberRef valueNumber = static_cast<CFNumberRef>(value);
                double relativeFontSize;
                CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &relativeFontSize);
                cueData->setRelativeFontSize(relativeFontSize);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_FontFamilyName, 0) == kCFCompareEqualTo) {
                valueString = static_cast<CFStringRef>(value);
                if (CFGetTypeID(valueString) != CFStringGetTypeID() || !CFStringGetLength(valueString))
                    continue;
                if (processed & FontName)
                    continue;
                processed |= FontName;

                cueData->setFontName(valueString);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_ForegroundColorARGB, 0) == kCFCompareEqualTo) {
                CFArrayRef arrayValue = static_cast<CFArrayRef>(value);
                if (CFGetTypeID(arrayValue) != CFArrayGetTypeID())
                    continue;

                RGBA32 color;
                if (!makeRGBA32FromARGBCFArray(arrayValue, color))
                    continue;
                cueData->setForegroundColor(color);
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_BackgroundColorARGB, 0) == kCFCompareEqualTo) {
                CFArrayRef arrayValue = static_cast<CFArrayRef>(value);
                if (CFGetTypeID(arrayValue) != CFArrayGetTypeID())
                    continue;

                RGBA32 color;
                if (!makeRGBA32FromARGBCFArray(arrayValue, color))
                    continue;
                cueData->setBackgroundColor(color);
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_CharacterBackgroundColorARGB, 0) == kCFCompareEqualTo) {
                CFArrayRef arrayValue = static_cast<CFArrayRef>(value);
                if (CFGetTypeID(arrayValue) != CFArrayGetTypeID())
                    continue;

                RGBA32 color;
                if (!makeRGBA32FromARGBCFArray(arrayValue, color))
                    continue;
                cueData->setHighlightColor(color);
            }
        }

        content.append(tagStart);
        content.append(attributedStringValue.substring(effectiveRange.location, effectiveRange.length));
        content.append(tagEnd);
    }

    if (content.length())
        cueData->setContent(content.toString());
}
Esempio n. 3
0
String ParsedCookie::toString() const
{
    StringBuilder builder;
    builder.append(name());
    builder.append(" = ");
    builder.append(value());
    builder.append("; Domain = ");
    builder.append(domain());
    builder.append("; Path = ");
    builder.append(path());
    builder.append("; Protocol = ");
    builder.append(protocol());
    return builder.toString();
}
    Status RecordStoreV1Base::validate( OperationContext* txn,
                                        bool full, bool scanData,
                                        ValidateAdaptor* adaptor,
                                        ValidateResults* results, BSONObjBuilder* output ) const {

        // 1) basic status that require no iteration
        // 2) extent level info
        // 3) check extent start and end
        // 4) check each non-deleted record
        // 5) check deleted list

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

        // 1111111111111111111
        if ( isCapped() ){
            output->appendBool("capped", true);
            output->appendNumber("max", _details->maxCappedDocs());
        }

        output->appendNumber("datasize", _details->dataSize());
        output->appendNumber("nrecords", _details->numRecords());
        output->appendNumber("lastExtentSize", _details->lastExtentSize(txn));
        output->appendNumber("padding", _details->paddingFactor());

        if ( _details->firstExtent(txn).isNull() )
            output->append( "firstExtent", "null" );
        else
            output->append( "firstExtent",
                            str::stream() << _details->firstExtent(txn).toString()
                            << " ns:"
                            << _getExtent( txn, _details->firstExtent(txn) )->nsDiagnostic.toString());
        if ( _details->lastExtent(txn).isNull() )
            output->append( "lastExtent", "null" );
        else
            output->append( "lastExtent", str::stream() << _details->lastExtent(txn).toString()
                            << " ns:"
                            << _getExtent( txn, _details->lastExtent(txn) )->nsDiagnostic.toString());

        // 22222222222222222222222222
        { // validate extent basics
            BSONArrayBuilder extentData;
            int extentCount = 0;
            DiskLoc extentDiskLoc;
            try {
                if ( !_details->firstExtent(txn).isNull() ) {
                    _getExtent( txn, _details->firstExtent(txn) )->assertOk();
                    _getExtent( txn, _details->lastExtent(txn) )->assertOk();
                }

                extentDiskLoc = _details->firstExtent(txn);
                while (!extentDiskLoc.isNull()) {
                    Extent* thisExtent = _getExtent( txn, extentDiskLoc );
                    if (full) {
                        extentData << thisExtent->dump();
                    }
                    if (!thisExtent->validates(extentDiskLoc, &results->errors)) {
                        results->valid = false;
                    }
                    DiskLoc nextDiskLoc = thisExtent->xnext;
                    
                    if (extentCount > 0 && !nextDiskLoc.isNull()
                        &&  _getExtent( txn, nextDiskLoc )->xprev != extentDiskLoc) {
                        StringBuilder sb;
                        sb << "'xprev' pointer " << _getExtent( txn, nextDiskLoc )->xprev.toString()
                           << " in extent " << nextDiskLoc.toString()
                           << " does not point to extent " << extentDiskLoc.toString();
                        results->errors.push_back( sb.str() );
                        results->valid = false;
                    }
                    if (nextDiskLoc.isNull() && extentDiskLoc != _details->lastExtent(txn)) {
                        StringBuilder sb;
                        sb << "'lastExtent' pointer " << _details->lastExtent(txn).toString()
                           << " does not point to last extent in list " << extentDiskLoc.toString();
                        results->errors.push_back( sb.str() );
                        results->valid = false;
                    }
                    extentDiskLoc = nextDiskLoc;
                    extentCount++;
                    txn->checkForInterrupt();
                }
            }
            catch (const DBException& e) {
                StringBuilder sb;
                sb << "exception validating extent " << extentCount
                   << ": " << e.what();
                results->errors.push_back( sb.str() );
                results->valid = false;
                return Status::OK();
            }
            output->append("extentCount", extentCount);

            if ( full )
                output->appendArray( "extents" , extentData.arr() );

        }

        try {
            // 333333333333333333333333333
            bool testingLastExtent = false;
            try {
                DiskLoc firstExtentLoc = _details->firstExtent(txn);
                if (firstExtentLoc.isNull()) {
                    // this is ok
                }
                else {
                    output->append("firstExtentDetails", _getExtent(txn, firstExtentLoc)->dump());
                    if (!_getExtent(txn, firstExtentLoc)->xprev.isNull()) {
                        StringBuilder sb;
                        sb << "'xprev' pointer in 'firstExtent' " << _details->firstExtent(txn).toString()
                           << " is " << _getExtent(txn, firstExtentLoc)->xprev.toString()
                           << ", should be null";
                        results->errors.push_back( sb.str() );
                        results->valid = false;
                    }
                }
                testingLastExtent = true;
                DiskLoc lastExtentLoc = _details->lastExtent(txn);
                if (lastExtentLoc.isNull()) {
                    // this is ok
                }
                else {
                    if (firstExtentLoc != lastExtentLoc) {
                        output->append("lastExtentDetails", _getExtent(txn, lastExtentLoc)->dump());
                        if (!_getExtent(txn, lastExtentLoc)->xnext.isNull()) {
                            StringBuilder sb;
                            sb << "'xnext' pointer in 'lastExtent' " << lastExtentLoc.toString()
                               << " is " << _getExtent(txn, lastExtentLoc)->xnext.toString()
                               << ", should be null";
                            results->errors.push_back( sb.str() );
                            results->valid = false;
                        }
                    }
                }
            }
            catch (const DBException& e) {
                StringBuilder sb;
                sb << "exception processing '"
                   << (testingLastExtent ? "lastExtent" : "firstExtent")
                   << "': " << e.what();
                results->errors.push_back( sb.str() );
                results->valid = false;
            }

            // 4444444444444444444444444

            set<DiskLoc> recs;
            if( scanData ) {
                int n = 0;
                int nInvalid = 0;
                long long nQuantizedSize = 0;
                long long nPowerOf2QuantizedSize = 0;
                long long len = 0;
                long long nlen = 0;
                long long bsonLen = 0;
                int outOfOrder = 0;
                DiskLoc cl_last;

                scoped_ptr<RecordIterator> iterator( getIterator( txn,
                                                                  DiskLoc(),
                                                                  false,
                                                                  CollectionScanParams::FORWARD ) );
                DiskLoc cl;
                while ( !( cl = iterator->getNext() ).isNull() ) {
                    n++;

                    if ( n < 1000000 )
                        recs.insert(cl);
                    if ( isCapped() ) {
                        if ( cl < cl_last )
                            outOfOrder++;
                        cl_last = cl;
                    }

                    Record *r = recordFor(cl);
                    len += r->lengthWithHeaders();
                    nlen += r->netLength();

                    if ( r->lengthWithHeaders() ==
                         quantizeAllocationSpace( r->lengthWithHeaders() ) ) {
                        // Count the number of records having a size consistent with
                        // the quantizeAllocationSpace quantization implementation.
                        ++nQuantizedSize;
                    }

                    if ( r->lengthWithHeaders() ==
                         quantizePowerOf2AllocationSpace( r->lengthWithHeaders() ) ) {
                        // Count the number of records having a size consistent with the
                        // quantizePowerOf2AllocationSpace quantization implementation.
                        ++nPowerOf2QuantizedSize;
                    }

                    if (full){
                        size_t dataSize = 0;
                        const Status status = adaptor->validate( r->toRecordData(), &dataSize );
                        if (!status.isOK()) {
                            results->valid = false;
                            if (nInvalid == 0) // only log once;
                                results->errors.push_back( "invalid object detected (see logs)" );

                            nInvalid++;
                            log() << "Invalid object detected in " << _ns
                                  << ": " << status.reason();
                        }
                        else {
                            bsonLen += dataSize;
                        }
                    }
                }

                if ( isCapped() && !_details->capLooped() ) {
                    output->append("cappedOutOfOrder", outOfOrder);
                    if ( outOfOrder > 1 ) {
                        results->valid = false;
                        results->errors.push_back( "too many out of order records" );
                    }
                }
                output->append("objectsFound", n);

                if (full) {
                    output->append("invalidObjects", nInvalid);
                }

                output->appendNumber("nQuantizedSize", nQuantizedSize);
                output->appendNumber("nPowerOf2QuantizedSize", nPowerOf2QuantizedSize);
                output->appendNumber("bytesWithHeaders", len);
                output->appendNumber("bytesWithoutHeaders", nlen);

                if (full) {
                    output->appendNumber("bytesBson", bsonLen);
                }
            } // end scanData

            // 55555555555555555555555555
            BSONArrayBuilder deletedListArray;
            for ( int i = 0; i < Buckets; i++ ) {
                deletedListArray << _details->deletedListEntry(i).isNull();
            }

            int ndel = 0;
            long long delSize = 0;
            BSONArrayBuilder delBucketSizes;
            int incorrect = 0;
            for ( int i = 0; i < Buckets; i++ ) {
                DiskLoc loc = _details->deletedListEntry(i);
                try {
                    int k = 0;
                    while ( !loc.isNull() ) {
                        if ( recs.count(loc) )
                            incorrect++;
                        ndel++;

                        if ( loc.questionable() ) {
                            if( isCapped() && !loc.isValid() && i == 1 ) {
                                /* the constructor for NamespaceDetails intentionally sets deletedList[1] to invalid
                                   see comments in namespace.h
                                */
                                break;
                            }

                            string err( str::stream() << "bad pointer in deleted record list: "
                                        << loc.toString()
                                        << " bucket: " << i
                                        << " k: " << k );
                            results->errors.push_back( err );
                            results->valid = false;
                            break;
                        }

                        const DeletedRecord* d = deletedRecordFor(loc);
                        delSize += d->lengthWithHeaders();
                        loc = d->nextDeleted();
                        k++;
                        txn->checkForInterrupt();
                    }
                    delBucketSizes << k;
                }
                catch (...) {
                    results->errors.push_back( (string)"exception in deleted chain for bucket " +
                                               BSONObjBuilder::numStr(i) );
                    results->valid = false;
                }
            }
            output->appendNumber("deletedCount", ndel);
            output->appendNumber("deletedSize", delSize);
            if ( full ) {
                output->append( "delBucketSizes", delBucketSizes.arr() );
            }

            if ( incorrect ) {
                results->errors.push_back( BSONObjBuilder::numStr(incorrect) +
                                           " records from datafile are in deleted list" );
                results->valid = false;
            }

        }
        catch (AssertionException) {
            results->errors.push_back( "exception during validate" );
            results->valid = false;
        }

        return Status::OK();
    }
static void appendFloat(StringBuilder& stringBuilder, float value)
{
    stringBuilder.append(' ');
    stringBuilder.appendNumber(value);
}
Esempio n. 6
0
static String attributesOfElement(AccessibilityUIElement* element)
{
    StringBuilder builder;

    builder.append(String::format("%s\n", element->role()->string().utf8().data()));

    // For the parent we print its role and its name, if available.
    builder.append("AXParent: ");
    AccessibilityUIElement parent = element->parentElement();
    if (AtkObject* atkParent = parent.platformUIElement()) {
        builder.append(roleToString(atk_object_get_role(atkParent)));
        const char* parentName = atk_object_get_name(atkParent);
        if (parentName && g_utf8_strlen(parentName, -1))
            builder.append(String::format(": %s", parentName));
    } else
        builder.append("(null)");
    builder.append("\n");

    builder.append(String::format("AXChildren: %d\n", element->childrenCount()));
    builder.append(String::format("AXPosition: { %f, %f }\n", element->x(), element->y()));
    builder.append(String::format("AXSize: { %f, %f }\n", element->width(), element->height()));

    String title = element->title()->string();
    if (!title.isEmpty())
        builder.append(String::format("%s\n", title.utf8().data()));

    String description = element->description()->string();
    if (!description.isEmpty())
        builder.append(String::format("%s\n", description.utf8().data()));

    String value = element->stringValue()->string();
    if (!value.isEmpty())
        builder.append(String::format("%s\n", value.utf8().data()));

    builder.append(String::format("AXFocusable: %d\n", element->isFocusable()));
    builder.append(String::format("AXFocused: %d\n", element->isFocused()));
    builder.append(String::format("AXSelectable: %d\n", element->isSelectable()));
    builder.append(String::format("AXSelected: %d\n", element->isSelected()));
    builder.append(String::format("AXMultiSelectable: %d\n", element->isMultiSelectable()));
    builder.append(String::format("AXEnabled: %d\n", element->isEnabled()));
    builder.append(String::format("AXExpanded: %d\n", element->isExpanded()));
    builder.append(String::format("AXRequired: %d\n", element->isRequired()));
    builder.append(String::format("AXChecked: %d\n", element->isChecked()));

    // We append the ATK specific attributes as a single line at the end.
    builder.append("AXPlatformAttributes: ");
    builder.append(getAtkAttributeSetAsString(element->platformUIElement()));

    return builder.toString();
}
Esempio n. 7
0
static void edit(const string& var){
    static const char * editor = getenv("EDITOR");
    if (!editor) {
        cout << "please define the EDITOR environment variable" << endl;
        return;
    }

    for (const char* p=var.data(); *p ; p++){
        if (! (isalnum(*p) || *p == '_' || *p == '.')){
            cout << "can only edit variable or property" << endl;
            return;
        }
    }

    if (!shellMainScope->exec("__jsout__ = tojson("+var+")", "tojs", false, false, false))
        return; // Error already printed

    const string js = shellMainScope->getString("__jsout__");

    if (strstr(js.c_str(), "[native code]")) {
        cout << "Can't edit native functions" << endl;
        return;
    }

    string filename;
    int fd;
    for (int i=0; i < 10; i++){
        StringBuilder sb;
        sb << "/tmp/mongo_edit" << time(0)+i << ".js";
        filename = sb.str();
        fd = open(filename.c_str(), O_RDWR|O_CREAT|O_EXCL, 0600);
        if (fd > 0)
            break;

        if (errno != EEXIST) {
            cout << "couldn't open temp file: " << errnoWithDescription() << endl;
            return;
        }
    }

    if (fd == -1){
        cout << "couldn't create unique temp file after 10 attempts" << endl;
        return;
    }

    // just to make sure this gets closed no matter what
    File holder;
    holder.fd = fd;

    if (write(fd, js.data(), js.size()) != (int)js.size()){
        cout << "failed to write to temp file: " << errnoWithDescription() << endl;
        return;
    }

    StringBuilder sb;
    sb << editor << " " << filename;
    int ret = ::system(sb.str().c_str());
    int systemErrno = errno;
    remove(filename.c_str()); // file already open, deleted on close
    if (ret){
        if (ret == -1) {
            cout << "failed to launch $EDITOR (" << editor << "): " << errnoWithDescription(systemErrno) << endl;
            return;
        }

        cout << "editor exited with error, not applying changes" << endl;
        return;

    }

    lseek(fd, 0, SEEK_SET);

    sb.reset();
    sb << var << " = ";
    int bytes;
    do {
        char buf[1024];
        bytes = read(fd, buf, sizeof(buf));
        if (bytes < 0) {
            cout << "failed to read temp file: " << errnoWithDescription() << endl;
            return;
        }
        sb.append( StringData(buf, bytes) );
    }while (bytes);

    const string code = sb.str();
    if (!shellMainScope->exec(code, "tojs", false, false, false))
        return; // Error already printed

}
Esempio n. 8
0
void Entry::asJSON(StringBuilder& json, const Storage::RecordInfo& info) const
{
    json.appendLiteral("{\n");
    json.appendLiteral("\"hash\": ");
    json.appendQuotedJSONString(m_key.hashAsString());
    json.appendLiteral(",\n");
    json.appendLiteral("\"bodySize\": ");
    json.appendNumber(info.bodySize);
    json.appendLiteral(",\n");
    json.appendLiteral("\"worth\": ");
    json.appendNumber(info.worth);
    json.appendLiteral(",\n");
    json.appendLiteral("\"partition\": ");
    json.appendQuotedJSONString(m_key.partition());
    json.appendLiteral(",\n");
    json.appendLiteral("\"timestamp\": ");
    json.appendNumber(std::chrono::duration_cast<std::chrono::milliseconds>(m_timeStamp.time_since_epoch()).count());
    json.appendLiteral(",\n");
    json.appendLiteral("\"URL\": ");
    json.appendQuotedJSONString(m_response.url().string());
    json.appendLiteral(",\n");
    json.appendLiteral("\"bodyHash\": ");
    json.appendQuotedJSONString(info.bodyHash);
    json.appendLiteral(",\n");
    json.appendLiteral("\"bodyShareCount\": ");
    json.appendNumber(info.bodyShareCount);
    json.appendLiteral(",\n");
    json.appendLiteral("\"headers\": {\n");
    bool firstHeader = true;
    for (auto& header : m_response.httpHeaderFields()) {
        if (!firstHeader)
            json.appendLiteral(",\n");
        firstHeader = false;
        json.appendLiteral("    ");
        json.appendQuotedJSONString(header.key);
        json.appendLiteral(": ");
        json.appendQuotedJSONString(header.value);
    }
    json.appendLiteral("\n}\n");
    json.appendLiteral("}");
}
Esempio n. 9
0
void SelectPopupClient::generateHTML(bool multiple, int size, const ScopeArray<BlackBerry::Platform::String>& labels, bool* enableds,
    const int* itemType, bool* selecteds)
{
    StringBuilder source;
    source.appendLiteral("<style>\n");
    // Include CSS file.
    source.append(popupControlBlackBerryCss,
            sizeof(popupControlBlackBerryCss));
    source.appendLiteral("</style>\n<style>");
    source.append(selectControlBlackBerryCss,
            sizeof(selectControlBlackBerryCss));
    source.appendLiteral("</style></head><body>\n"
                         "<script>\n"
                         "window.addEventListener('load', function () {");
    if (m_multiple)
        source.appendLiteral("window.select.show(true, ");
    else
        source.appendLiteral("window.select.show(false, ");
    // Add labels.
    source.append('[');
    for (int i = 0; i < size; i++) {
        source.append("'" + String(labels[i]).replace('\\', "\\\\").replace('\'', "\\'") + "'");
        // Don't append ',' to last element.
        if (i != size - 1)
            source.appendLiteral(", ");
    }
    source.appendLiteral("], ");
    // Add enables.
    source.append('[');
    for (int i = 0; i < size; i++) {
        if (enableds[i])
            source.appendLiteral("true");
        else
            source.appendLiteral("false");
        // Don't append ',' to last element.
        if (i != size - 1)
            source.appendLiteral(", ");
    }
    source.appendLiteral("], ");
    // Add itemType.
    source.append('[');
    for (int i = 0; i < size; i++) {
        source.appendNumber(itemType[i]);
        // Don't append ',' to last element.
        if (i != size - 1)
            source.appendLiteral(", ");
    }
    source.appendLiteral("], ");
    // Add selecteds
    source.append('[');
    for (int i = 0; i < size; i++) {
        if (selecteds[i])
            source.appendLiteral("true");
        else
            source.appendLiteral("false");
        // Don't append ',' to last element.
        if (i != size - 1)
            source.appendLiteral(", ");
    }
    source.appendLiteral("] "
                         ", 'Cancel'");
    // If multi-select, add OK button for confirm.
    if (m_multiple)
        source.appendLiteral(", 'OK'");
    source.appendLiteral("); \n }); \n");
    source.append(selectControlBlackBerryJs, sizeof(selectControlBlackBerryJs));
    source.appendLiteral("</script>\n"
                         "</body> </html>\n");
    m_source = source.toString();
}
Esempio n. 10
0
bool DateTimeFormat::parse(const String& source, TokenHandler& tokenHandler)
{
    enum State {
        StateInQuote,
        StateInQuoteQuote,
        StateLiteral,
        StateQuote,
        StateSymbol,
    } state = StateLiteral;

    FieldType fieldType = FieldTypeLiteral;
    StringBuilder literalBuffer;
    int fieldCounter = 0;

    for (unsigned index = 0; index < source.length(); ++index) {
        const UChar ch = source[index];
        switch (state) {
        case StateInQuote:
            if (ch == '\'') {
                state = StateInQuoteQuote;
                break;
            }

            literalBuffer.append(ch);
            break;

        case StateInQuoteQuote:
            if (ch == '\'') {
                literalBuffer.append('\'');
                state = StateInQuote;
                break;
            }

            fieldType = mapCharacterToFieldType(ch);
            if (fieldType == FieldTypeInvalid)
                return false;

            if (fieldType == FieldTypeLiteral) {
                literalBuffer.append(ch);
                state = StateLiteral;
                break;
            }

            if (literalBuffer.length()) {
                tokenHandler.visitLiteral(literalBuffer.toString());
                literalBuffer.clear();
            }

            fieldCounter = 1;
            state = StateSymbol;
            break;

        case StateLiteral:
            if (ch == '\'') {
                state = StateQuote;
                break;
            }

            fieldType = mapCharacterToFieldType(ch);
            if (fieldType == FieldTypeInvalid)
                return false;

            if (fieldType == FieldTypeLiteral) {
                literalBuffer.append(ch);
                break;
            }

            if (literalBuffer.length()) {
                tokenHandler.visitLiteral(literalBuffer.toString());
                literalBuffer.clear();
            }

            fieldCounter = 1;
            state = StateSymbol;
            break;

        case StateQuote:
            literalBuffer.append(ch);
            state = ch == '\'' ? StateLiteral : StateInQuote;
            break;

        case StateSymbol: {
            ASSERT(fieldType != FieldTypeInvalid);
            ASSERT(fieldType != FieldTypeLiteral);
            ASSERT(literalBuffer.isEmpty());

            FieldType fieldType2 = mapCharacterToFieldType(ch);
            if (fieldType2 == FieldTypeInvalid)
                return false;

            if (fieldType == fieldType2) {
                ++fieldCounter;
                break;
            }

            tokenHandler.visitField(fieldType, fieldCounter);

            if (fieldType2 == FieldTypeLiteral) {
                if (ch == '\'') {
                    state = StateQuote;
                } else {
                    literalBuffer.append(ch);
                    state = StateLiteral;
                }
                break;
            }

            fieldCounter = 1;
            fieldType = fieldType2;
            break;
        }
        }
    }

    ASSERT(fieldType != FieldTypeInvalid);

    switch (state) {
    case StateLiteral:
    case StateInQuoteQuote:
        if (literalBuffer.length())
            tokenHandler.visitLiteral(literalBuffer.toString());
        return true;

    case StateQuote:
    case StateInQuote:
        if (literalBuffer.length())
            tokenHandler.visitLiteral(literalBuffer.toString());
        return false;

    case StateSymbol:
        ASSERT(fieldType != FieldTypeLiteral);
        ASSERT(!literalBuffer.length());
        tokenHandler.visitField(fieldType, fieldCounter);
        return true;
    }

    ASSERT_NOT_REACHED();
    return false;
}
Esempio n. 11
0
void ListMarkerPainter::paint(const PaintInfo& paintInfo,
                              const LayoutPoint& paintOffset) {
  if (paintInfo.phase != PaintPhaseForeground)
    return;

  if (m_layoutListMarker.style()->visibility() != EVisibility::Visible)
    return;

  if (LayoutObjectDrawingRecorder::useCachedDrawingIfPossible(
          paintInfo.context, m_layoutListMarker, paintInfo.phase))
    return;

  LayoutPoint boxOrigin(paintOffset + m_layoutListMarker.location());
  LayoutRect overflowRect(m_layoutListMarker.visualOverflowRect());
  overflowRect.moveBy(boxOrigin);

  IntRect pixelSnappedOverflowRect = pixelSnappedIntRect(overflowRect);
  if (!paintInfo.cullRect().intersectsCullRect(overflowRect))
    return;

  LayoutObjectDrawingRecorder recorder(paintInfo.context, m_layoutListMarker,
                                       paintInfo.phase,
                                       pixelSnappedOverflowRect);

  LayoutRect box(boxOrigin, m_layoutListMarker.size());

  IntRect marker = m_layoutListMarker.getRelativeMarkerRect();
  marker.moveBy(roundedIntPoint(boxOrigin));

  GraphicsContext& context = paintInfo.context;

  if (m_layoutListMarker.isImage()) {
    context.drawImage(m_layoutListMarker.image()
                          ->image(m_layoutListMarker, marker.size(),
                                  m_layoutListMarker.styleRef().effectiveZoom())
                          .get(),
                      marker);
    if (m_layoutListMarker.getSelectionState() != SelectionNone) {
      LayoutRect selRect = m_layoutListMarker.localSelectionRect();
      selRect.moveBy(boxOrigin);
      context.fillRect(
          pixelSnappedIntRect(selRect),
          m_layoutListMarker.listItem()->selectionBackgroundColor());
    }
    return;
  }

  LayoutListMarker::ListStyleCategory styleCategory =
      m_layoutListMarker.getListStyleCategory();
  if (styleCategory == LayoutListMarker::ListStyleCategory::None)
    return;

  Color color(m_layoutListMarker.resolveColor(CSSPropertyColor));

  if (BoxPainter::shouldForceWhiteBackgroundForPrintEconomy(
          m_layoutListMarker.styleRef(),
          m_layoutListMarker.listItem()->document()))
    color = TextPainter::textColorForWhiteBackground(color);

  // Apply the color to the list marker text.
  context.setFillColor(color);

  const EListStyleType listStyle = m_layoutListMarker.style()->listStyleType();
  if (styleCategory == LayoutListMarker::ListStyleCategory::Symbol) {
    paintSymbol(context, color, marker, listStyle);
    return;
  }

  if (m_layoutListMarker.text().isEmpty())
    return;

  const Font& font = m_layoutListMarker.style()->font();
  TextRun textRun = constructTextRun(font, m_layoutListMarker.text(),
                                     m_layoutListMarker.styleRef());

  GraphicsContextStateSaver stateSaver(context, false);
  if (!m_layoutListMarker.style()->isHorizontalWritingMode()) {
    marker.moveBy(roundedIntPoint(-boxOrigin));
    marker = marker.transposedRect();
    marker.moveBy(
        IntPoint(roundToInt(box.x()),
                 roundToInt(box.y() - m_layoutListMarker.logicalHeight())));
    stateSaver.save();
    context.translate(marker.x(), marker.maxY());
    context.rotate(static_cast<float>(deg2rad(90.)));
    context.translate(-marker.x(), -marker.maxY());
  }

  TextRunPaintInfo textRunPaintInfo(textRun);
  textRunPaintInfo.bounds = marker;
  const SimpleFontData* fontData =
      m_layoutListMarker.style()->font().primaryFont();
  IntPoint textOrigin = IntPoint(
      marker.x(),
      marker.y() + (fontData ? fontData->getFontMetrics().ascent() : 0));

  // Text is not arbitrary. We can judge whether it's RTL from the first
  // character, and we only need to handle the direction RightToLeft for now.
  bool textNeedsReversing =
      WTF::Unicode::direction(m_layoutListMarker.text()[0]) ==
      WTF::Unicode::RightToLeft;
  StringBuilder reversedText;
  if (textNeedsReversing) {
    unsigned length = m_layoutListMarker.text().length();
    reversedText.reserveCapacity(length);
    for (int i = length - 1; i >= 0; --i)
      reversedText.append(m_layoutListMarker.text()[i]);
    DCHECK(reversedText.length() == length);
    textRun.setText(reversedText.toString());
  }

  const UChar suffix =
      ListMarkerText::suffix(listStyle, m_layoutListMarker.listItem()->value());
  UChar suffixStr[2] = {suffix, static_cast<UChar>(' ')};
  TextRun suffixRun =
      constructTextRun(font, suffixStr, 2, m_layoutListMarker.styleRef(),
                       m_layoutListMarker.style()->direction());
  TextRunPaintInfo suffixRunInfo(suffixRun);
  suffixRunInfo.bounds = marker;

  if (m_layoutListMarker.style()->isLeftToRightDirection()) {
    context.drawText(font, textRunPaintInfo, textOrigin);
    context.drawText(font, suffixRunInfo,
                     textOrigin + IntSize(font.width(textRun), 0));
  } else {
    context.drawText(font, suffixRunInfo, textOrigin);
    context.drawText(font, textRunPaintInfo,
                     textOrigin + IntSize(font.width(suffixRun), 0));
  }
}
Esempio n. 12
0
    /**
     * Returns all the IP addresses bound to the network interfaces of this machine.
     * This requires a syscall. If the ipv6enabled parameter is true, both IPv6 AND IPv4
     * addresses will be returned.
     */
    std::vector<std::string> getBoundAddrs(const bool ipv6enabled) {
        std::vector<std::string> out;
#ifdef FASTPATH_UNIX

        ifaddrs* addrs;

        int err = getifaddrs(&addrs);
        if (err) {
            warning() << "getifaddrs failure: " << errnoWithDescription(err) << std::endl;
            return out;
        }
        ON_BLOCK_EXIT(freeifaddrs, addrs);

        // based on example code from linux getifaddrs manpage
        for (ifaddrs* addr = addrs; addr != NULL; addr = addr->ifa_next) {
            if (addr->ifa_addr == NULL) continue;
            int family = addr->ifa_addr->sa_family;
            char host[NI_MAXHOST];

            if (family == AF_INET || (ipv6enabled && (family == AF_INET6))) {
                err = getnameinfo(addr->ifa_addr,
                                  (family == AF_INET ? sizeof(struct sockaddr_in)
                                                     : sizeof(struct sockaddr_in6)),
                                    host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
                if (err) {
                    warning() << "getnameinfo() failed: " << gai_strerror(err) << std::endl;
                    continue;
                }
                out.push_back(host);
            }
        }

#elif defined(_WIN32)

        // Start with the MS recommended 15KB buffer. Use multiple attempts
        // for the rare case that the adapter config changes between calls

        ULONG adaptersLen = 15 * 1024;
        boost::scoped_array<char> buf(new char[adaptersLen]);
        IP_ADAPTER_ADDRESSES* adapters = reinterpret_cast<IP_ADAPTER_ADDRESSES*>(buf.get());
        DWORD err;

        ULONG family = ipv6enabled ? AF_UNSPEC : AF_INET;

        for (int tries = 0; tries < 3; ++tries) {
            err = GetAdaptersAddresses(family,
                                       GAA_FLAG_SKIP_ANYCAST |  // only want unicast addrs
                                       GAA_FLAG_SKIP_MULTICAST |
                                       GAA_FLAG_SKIP_DNS_SERVER,
                                       NULL,
                                       adapters,
                                       &adaptersLen);

            if (err == ERROR_BUFFER_OVERFLOW) {
                // in this case, adaptersLen will be set to the size we need to allocate
                buf.reset(new char[adaptersLen]);
                adapters = reinterpret_cast<IP_ADAPTER_ADDRESSES*>(buf.get());
            }
            else {
                break;  // only retry for incorrectly sized buffer
            }
        }

        if (err != NO_ERROR) {
            warning() << "GetAdaptersAddresses() failed: " << errnoWithDescription(err)
                      << std::endl;
            return out;
        }

        for (IP_ADAPTER_ADDRESSES* adapter = adapters;
             adapter != NULL; adapter = adapter->Next) {
            for (IP_ADAPTER_UNICAST_ADDRESS* addr = adapter->FirstUnicastAddress;
                 addr != NULL; addr = addr->Next) {

                short family =
                    reinterpret_cast<SOCKADDR_STORAGE*>(addr->Address.lpSockaddr)->ss_family;

                if (family == AF_INET) {
                    // IPv4
                    SOCKADDR_IN* sock = reinterpret_cast<SOCKADDR_IN*>(addr->Address.lpSockaddr);
                    char addrstr[INET_ADDRSTRLEN] = {0};
                    boost::system::error_code ec;
                    // Not all windows versions have inet_ntop
                    boost::asio::detail::socket_ops::inet_ntop(AF_INET,
                                                               &(sock->sin_addr),
                                                               addrstr,
                                                               INET_ADDRSTRLEN,
                                                               0,
                                                               ec);
                    if (ec) {
                        warning() << "inet_ntop failed during IPv4 address conversion: "
                                  << ec.message() << std::endl;
                        continue;
                    }
                    out.push_back(addrstr);
                }
                else if (family == AF_INET6) {
                    // IPv6
                    SOCKADDR_IN6* sock = reinterpret_cast<SOCKADDR_IN6*>(addr->Address.lpSockaddr);
                    char addrstr[INET6_ADDRSTRLEN] = {0};
                    boost::system::error_code ec;
                    boost::asio::detail::socket_ops::inet_ntop(AF_INET6,
                                                               &(sock->sin6_addr),
                                                               addrstr,
                                                               INET6_ADDRSTRLEN,
                                                               0,
                                                               ec);
                    if (ec) {
                        warning() << "inet_ntop failed during IPv6 address conversion: "
                                  << ec.message() << std::endl;
                        continue;
                    }
                    out.push_back(addrstr);
                }
            }
        }

#endif  // defined(_WIN32)

        if (shouldLog(logger::LogSeverity::Debug(2))) {
            StringBuilder builder;
            builder << "getBoundAddrs():";
            for (std::vector<std::string>::const_iterator o = out.begin(); o != out.end(); ++o) {
                builder << " [ " << *o << "]";
            }
            LOG(2) << builder.str();
        }
        return out;
    }
Esempio n. 13
0
// See http://tools.ietf.org/html/rfc2822#section-3.3 for more information.
String makeRFC2822DateString(unsigned dayOfWeek, unsigned day, unsigned month, unsigned year, unsigned hours, unsigned minutes, unsigned seconds, int utcOffset)
{
    StringBuilder stringBuilder;
    stringBuilder.append(weekdayName[dayOfWeek]);
    stringBuilder.appendLiteral(", ");
    stringBuilder.appendNumber(day);
    stringBuilder.append(' ');
    stringBuilder.append(monthName[month]);
    stringBuilder.append(' ');
    stringBuilder.appendNumber(year);
    stringBuilder.append(' ');

    appendTwoDigitNumber(stringBuilder, hours);
    stringBuilder.append(':');
    appendTwoDigitNumber(stringBuilder, minutes);
    stringBuilder.append(':');
    appendTwoDigitNumber(stringBuilder, seconds);
    stringBuilder.append(' ');

    stringBuilder.append(utcOffset > 0 ? '+' : '-');
    int absoluteUTCOffset = abs(utcOffset);
    appendTwoDigitNumber(stringBuilder, absoluteUTCOffset / 60);
    appendTwoDigitNumber(stringBuilder, absoluteUTCOffset % 60);

    return stringBuilder.toString();
}
Esempio n. 14
0
string ChunkRange::toString() const {
    StringBuilder sb;
    sb << "ChunkRange(min=" << _min << ", max=" << _max << ", shard=" << _shardId << ")";

    return sb.str();
}
Esempio n. 15
0
    void CmdLine::addGlobalOptions( boost::program_options::options_description& general ,
                                    boost::program_options::options_description& hidden ,
                                    boost::program_options::options_description& ssl_options ) {
        /* support for -vv -vvvv etc. */
        for (string s = "vv"; s.length() <= 12; s.append("v")) {
            hidden.add_options()(s.c_str(), "verbose");
        }

        StringBuilder portInfoBuilder;
        StringBuilder maxConnInfoBuilder;

        portInfoBuilder << "specify port number - " << DefaultDBPort << " by default";
        maxConnInfoBuilder << "max number of simultaneous connections - " << DEFAULT_MAX_CONN << " by default";

        general.add_options()
        ("help,h", "show this usage information")
        ("version", "show version information")
        ("config,f", po::value<string>(), "configuration file specifying additional options")
        ("verbose,v", "be more verbose (include multiple times for more verbosity e.g. -vvvvv)")
        ("quiet", "quieter output")
        ("port", po::value<int>(&cmdLine.port), portInfoBuilder.str().c_str())
        ("bind_ip", po::value<string>(&cmdLine.bind_ip), "comma separated list of ip addresses to listen on - all local ips by default")
        ("maxConns",po::value<int>(), maxConnInfoBuilder.str().c_str())
        ("logpath", po::value<string>() , "log file to send write to instead of stdout - has to be a file, not directory" )
        ("logappend" , "append to logpath instead of over-writing" )
        ("pidfilepath", po::value<string>(), "full path to pidfile (if not set, no pidfile is created)")
        ("keyFile", po::value<string>(), "private key for cluster authentication")
        ("setParameter", po::value< std::vector<std::string> >()->composing(),
                "Set a configurable parameter")
#ifndef _WIN32
        ("nounixsocket", "disable listening on unix sockets")
        ("unixSocketPrefix", po::value<string>(), "alternative directory for UNIX domain sockets (defaults to /tmp)")
        ("fork" , "fork server process" )
        ("syslog" , "log to system's syslog facility instead of file or stdout" )
#endif
        ;
        

#ifdef MONGO_SSL
        ssl_options.add_options()
        ("sslOnNormalPorts" , "use ssl on configured ports" )
        ("sslPEMKeyFile" , po::value<string>(&cmdLine.sslPEMKeyFile), "PEM file for ssl" )
        ("sslPEMKeyPassword" , new PasswordValue(&cmdLine.sslPEMKeyPassword) , "PEM file password" )
        ("sslCAFile", po::value<std::string>(&cmdLine.sslCAFile), 
         "Certificate Authority file for SSL")
        ("sslCRLFile", po::value<std::string>(&cmdLine.sslCRLFile),
         "Certificate Revocation List file for SSL")
        ("sslWeakCertificateValidation", "allow client to connect without presenting a certificate")
#endif
        ;
        
        // Extra hidden options
        hidden.add_options()
        ("objcheck", "inspect client data for validity on receipt (DEFAULT)")
        ("noobjcheck", "do NOT inspect client data for validity on receipt")
        ("traceExceptions", "log stack traces for every exception")
        ("enableExperimentalIndexStatsCmd", po::bool_switch(&cmdLine.experimental.indexStatsCmdEnabled),
                "EXPERIMENTAL (UNSUPPORTED). Enable command computing aggregate statistics on indexes.")
        ("enableExperimentalStorageDetailsCmd", po::bool_switch(&cmdLine.experimental.storageDetailsCmdEnabled),
                "EXPERIMENTAL (UNSUPPORTED). Enable command computing aggregate statistics on storage.")
        ;
    }
Esempio n. 16
0
static String buildEllipseString(const String& radiusX, const String& radiusY, const String& centerX, const String& centerY, const String& box)
{
    char opening[] = "ellipse(";
    char at[] = "at";
    char separator[] = " ";
    StringBuilder result;
    result.appendLiteral(opening);
    bool needsSeparator = false;
    if (!radiusX.isNull()) {
        result.append(radiusX);
        needsSeparator = true;
    }
    if (!radiusY.isNull()) {
        if (needsSeparator)
            result.appendLiteral(separator);
        result.append(radiusY);
        needsSeparator = true;
    }

    if (!centerX.isNull() || !centerY.isNull()) {
        if (needsSeparator)
            result.appendLiteral(separator);
        result.appendLiteral(at);
        result.appendLiteral(separator);
        result.append(centerX);
        result.appendLiteral(separator);
        result.append(centerY);
    }
    result.appendLiteral(")");
    if (box.length()) {
        result.appendLiteral(separator);
        result.append(box);
    }
    return result.toString();
}
Esempio n. 17
0
CString WebSocketHandshake::clientHandshakeMessage() const
{
    // Keep the following consistent with clientHandshakeRequest().
    StringBuilder builder;

    builder.append("GET ");
    builder.append(resourceName(m_url));
    builder.append(" HTTP/1.1\r\n");
    builder.append("Upgrade: WebSocket\r\n");
    builder.append("Connection: Upgrade\r\n");
    builder.append("Host: ");
    builder.append(m_url.host().lower());
    if (m_url.port() && ((!m_secure && m_url.port() != 80) || (m_secure && m_url.port() != 443))) {
        builder.append(":");
        builder.append(String::number(m_url.port()));
    }
    builder.append("\r\n");
    builder.append("Origin: ");
    builder.append(clientOrigin());
    builder.append("\r\n");
    if (!m_clientProtocol.isEmpty()) {
        builder.append("WebSocket-Protocol: ");
        builder.append(m_clientProtocol);
        builder.append("\r\n");
    }

    KURL url = httpURLForAuthenticationAndCookies();
    if (m_context->isDocument()) {
        Document* document = static_cast<Document*>(m_context);
        String cookie = cookieRequestHeaderFieldValue(document, url);
        if (!cookie.isEmpty()) {
            builder.append("Cookie: ");
            builder.append(cookie);
            builder.append("\r\n");
        }
        // Set "Cookie2: <cookie>" if cookies 2 exists for url?
    }

    builder.append("\r\n");
    return builder.toString().utf8();
}
Esempio n. 18
0
static String buildPolygonString(const WindRule& windRule, const Vector<String>& points, const String& box)
{
    ASSERT(!(points.size() % 2));

    StringBuilder result;
    char evenOddOpening[] = "polygon(evenodd, ";
    char nonZeroOpening[] = "polygon(";
    char commaSeparator[] = ", ";
    COMPILE_ASSERT(sizeof(evenOddOpening) >= sizeof(nonZeroOpening), polygon_evenodd_is_longest_string_opening);

    // Compute the required capacity in advance to reduce allocations.
    size_t length = sizeof(evenOddOpening) - 1;
    for (size_t i = 0; i < points.size(); i += 2) {
        if (i)
            length += (sizeof(commaSeparator) - 1);
        // add length of two strings, plus one for the space separator.
        length += points[i].length() + 1 + points[i + 1].length();
    }

    if (box.length())
        length += box.length() + 1;

    result.reserveCapacity(length);

    if (windRule == RULE_EVENODD)
        result.appendLiteral(evenOddOpening);
    else
        result.appendLiteral(nonZeroOpening);

    for (size_t i = 0; i < points.size(); i += 2) {
        if (i)
            result.appendLiteral(commaSeparator);
        result.append(points[i]);
        result.append(' ');
        result.append(points[i + 1]);
    }

    result.append(')');

    if (box.length()) {
        result.append(' ');
        result.append(box);
    }

    return result.toString();
}
Esempio n. 19
0
void NntpProcessor::SendSegment()
{
	detail("[%i] Sending segment %s (%i=%" PRIi64 ":%i)", m_id, *m_filename, m_part, m_offset, m_size);

	if (m_speed > 0)
	{
		m_start = Util::CurrentTicks();
	}

	BString<1024> fullFilename("%s/%s", m_dataDir, *m_filename);
	BString<1024> cacheFileDir("%s/%s", m_cacheDir, *m_filename);
	BString<1024> cacheFileName("%i=%" PRIi64 "-%i", m_part, m_offset, m_size);
	BString<1024> cacheFullFilename("%s/%s", *cacheFileDir, *cacheFileName);
	BString<1024> cacheKey("%s/%s", *m_filename, *cacheFileName);

	const char* cachedData = nullptr;
	int cachedSize;
	if (m_cache)
	{
		m_cache->Find(cacheKey, cachedData, cachedSize);
	}

	DiskFile cacheFile;
	bool readCache = !cachedData && m_cacheDir && cacheFile.Open(cacheFullFilename, DiskFile::omRead);
	bool writeCache = !cachedData && m_cacheDir && !readCache;
	StringBuilder cacheMem;
	if (m_cache && !cachedData)
	{
		cacheMem.Reserve((int)(m_size * 1.1));
	}

	CString errmsg;
	if (writeCache && !FileSystem::ForceDirectories(cacheFileDir, errmsg))
	{
		error("Could not create directory %s: %s", *cacheFileDir, *errmsg);
	}

	if (writeCache && !cacheFile.Open(cacheFullFilename, DiskFile::omWrite))
	{
		error("Could not create file %s: %s", *cacheFullFilename, *FileSystem::GetLastErrorMessage());
	}

	if (!cachedData && !readCache && !FileSystem::FileExists(fullFilename))
	{
		m_connection->WriteLine(CString::FormatStr("430 Article not found\r\n"));
		return;
	}

	YEncoder encoder(fullFilename, m_part, m_offset, m_size, 
		[proc = this, writeCache, &cacheFile, &cacheMem](const char* buf, int size)
		{
			if (proc->m_cache)
			{
				cacheMem.Append(buf);
			}
			if (writeCache)
			{
				cacheFile.Write(buf, size);
			}
			proc->SendData(buf, size);
		});

	if (!cachedData && !readCache && !encoder.OpenFile(errmsg))
	{
		m_connection->WriteLine(CString::FormatStr("403 %s\r\n", *errmsg));
		return;
	}

	m_connection->WriteLine(CString::FormatStr("%i, 0 %s\r\n", m_sendHeaders ? 222 : 220, m_messageid));
	if (m_sendHeaders)
	{
		m_connection->WriteLine(CString::FormatStr("Message-ID: %s\r\n", m_messageid));
		m_connection->WriteLine(CString::FormatStr("Subject: \"%s\"\r\n", FileSystem::BaseFileName(m_filename)));
		m_connection->WriteLine("\r\n");
	}

	if (cachedData)
	{
		SendData(cachedData, cachedSize);
	}
	else if (readCache)
	{
		cacheFile.Seek(0, DiskFile::soEnd);
		int size = (int)cacheFile.Position();
		CharBuffer buf(size);
		cacheFile.Seek(0);
		if (cacheFile.Read((char*)buf, size) != size)
		{
			error("Could not read file %s: %s", *cacheFullFilename, *FileSystem::GetLastErrorMessage());
		}
		if (m_cache)
		{
			cacheMem.Append(buf, size);
		}
		SendData(buf, size);
	}
	else
	{
		encoder.WriteSegment();
	}

	if (!cachedData && cacheMem.Length() > 0)
	{
		m_cache->Append(cacheKey, cacheMem, cacheMem.Length());
	}

	m_connection->WriteLine(".\r\n");
}
Esempio n. 20
0
static String buildInsetString(const String& top, const String& right, const String& bottom, const String& left,
    const String& topLeftRadiusWidth, const String& topLeftRadiusHeight,
    const String& topRightRadiusWidth, const String& topRightRadiusHeight,
    const String& bottomRightRadiusWidth, const String& bottomRightRadiusHeight,
    const String& bottomLeftRadiusWidth, const String& bottomLeftRadiusHeight,
    const String& box)
{
    char opening[] = "inset(";
    char separator[] = " ";
    char cornersSeparator[] = "round";
    StringBuilder result;
    result.appendLiteral(opening);
    result.append(top);

    bool showLeftArg = !left.isNull() && left != right;
    bool showBottomArg = !bottom.isNull() && (bottom != top || showLeftArg);
    bool showRightArg = !right.isNull() && (right != top || showBottomArg);
    if (showRightArg) {
        result.appendLiteral(separator);
        result.append(right);
    }
    if (showBottomArg) {
        result.appendLiteral(separator);
        result.append(bottom);
    }
    if (showLeftArg) {
        result.appendLiteral(separator);
        result.append(left);
    }

    if (!topLeftRadiusWidth.isNull() && !topLeftRadiusHeight.isNull()) {
        Vector<String> horizontalRadii;
        bool areDefaultCornerRadii = buildInsetRadii(horizontalRadii, topLeftRadiusWidth, topRightRadiusWidth, bottomRightRadiusWidth, bottomLeftRadiusWidth);

        Vector<String> verticalRadii;
        areDefaultCornerRadii &= buildInsetRadii(verticalRadii, topLeftRadiusHeight, topRightRadiusHeight, bottomRightRadiusHeight, bottomLeftRadiusHeight);

        if (!areDefaultCornerRadii) {
            result.appendLiteral(separator);
            result.appendLiteral(cornersSeparator);

            for (size_t i = 0; i < horizontalRadii.size(); ++i) {
                result.appendLiteral(separator);
                result.append(horizontalRadii[i]);
            }

            if (verticalRadii.size() != horizontalRadii.size()
                || !VectorComparer<false, String>::compare(verticalRadii.data(), horizontalRadii.data(), verticalRadii.size())) {
                result.appendLiteral(separator);
                result.appendLiteral("/");

                for (size_t i = 0; i < verticalRadii.size(); ++i) {
                    result.appendLiteral(separator);
                    result.append(verticalRadii[i]);
                }
            }
        }
    }
    result.append(')');
    if (box.length()) {
        result.append(' ');
        result.append(box);
    }
    return result.toString();
}
Esempio n. 21
0
/**
 * Edit a variable or input buffer text in an external editor -- EDITOR must be defined
 *
 * @param whatToEdit Name of JavaScript variable to be edited, or any text string
 */
static void edit( const string& whatToEdit ) {

    // EDITOR may be defined in the JavaScript scope or in the environment
    string editor;
    if ( shellMainScope->type( "EDITOR" ) == String ) {
        editor = shellMainScope->getString( "EDITOR" );
    }
    else {
        static const char * editorFromEnv = getenv( "EDITOR" );
        if ( editorFromEnv ) {
            editor = editorFromEnv;
        }
    }
    if ( editor.empty() ) {
        cout << "please define EDITOR as a JavaScript string or as an environment variable" << endl;
        return;
    }

    // "whatToEdit" might look like a variable/property name
    bool editingVariable = true;
    for ( const char* p = whatToEdit.c_str(); *p; ++p ) {
        if ( ! ( isalnum( *p ) || *p == '_' || *p == '.' ) ) {
            editingVariable = false;
            break;
        }
    }

    string js;
    if ( editingVariable ) {
        // If "whatToEdit" is undeclared or uninitialized, declare 
        int varType = shellMainScope->type( whatToEdit.c_str() );
        if ( varType == Undefined ) {
            shellMainScope->exec( "var " + whatToEdit , "(shell)", false, true, false );
        }

        // Convert "whatToEdit" to JavaScript (JSON) text
        if ( !shellMainScope->exec( "__jsout__ = tojson(" + whatToEdit + ")", "tojs", false, false, false ) )
            return; // Error already printed

        js = shellMainScope->getString( "__jsout__" );

        if ( strstr( js.c_str(), "[native code]" ) ) {
            cout << "can't edit native functions" << endl;
            return;
        }
    }
    else {
        js = whatToEdit;
    }

    // Pick a name to use for the temp file
    string filename;
    const int maxAttempts = 10;
    int i;
    for ( i = 0; i < maxAttempts; ++i ) {
        StringBuilder sb;
#ifdef _WIN32
        char tempFolder[MAX_PATH];
        GetTempPathA( sizeof tempFolder, tempFolder );
        sb << tempFolder << "mongo_edit" << time( 0 ) + i << ".js";
#else
        sb << "/tmp/mongo_edit" << time( 0 ) + i << ".js";
#endif
        filename = sb.str();
        if ( ! fileExists( filename ) )
            break;
    }
    if ( i == maxAttempts ) {
        cout << "couldn't create unique temp file after " << maxAttempts << " attempts" << endl;
        return;
    }

    // Create the temp file
    FILE * tempFileStream;
    tempFileStream = fopen( filename.c_str(), "wt" );
    if ( ! tempFileStream ) {
        cout << "couldn't create temp file (" << filename << "): " << errnoWithDescription() << endl;
        return;
    }

    // Write JSON into the temp file
    size_t fileSize = js.size();
    if ( fwrite( js.data(), sizeof( char ), fileSize, tempFileStream ) != fileSize ) {
        int systemErrno = errno;
        cout << "failed to write to temp file: " << errnoWithDescription( systemErrno ) << endl;
        fclose( tempFileStream );
        remove( filename.c_str() );
        return;
    }
    fclose( tempFileStream );

    // Pass file to editor
    StringBuilder sb;
    sb << editor << " " << filename;
    int ret = ::system( sb.str().c_str() );
    if ( ret ) {
        if ( ret == -1 ) {
            int systemErrno = errno;
            cout << "failed to launch $EDITOR (" << editor << "): " << errnoWithDescription( systemErrno ) << endl;
        }
        else
            cout << "editor exited with error (" << ret << "), not applying changes" << endl;
        remove( filename.c_str() );
        return;
    }

    // The editor gave return code zero, so read the file back in
    tempFileStream = fopen( filename.c_str(), "rt" );
    if ( ! tempFileStream ) {
        cout << "couldn't open temp file on return from editor: " << errnoWithDescription() << endl;
        remove( filename.c_str() );
        return;
    }
    sb.reset();
    int bytes;
    do {
        char buf[1024];
        bytes = fread( buf, sizeof( char ), sizeof buf, tempFileStream );
        if ( ferror( tempFileStream ) ) {
            cout << "failed to read temp file: " << errnoWithDescription() << endl;
            fclose( tempFileStream );
            remove( filename.c_str() );
            return;
        }
        sb.append( StringData( buf, bytes ) );
    } while ( bytes );

    // Done with temp file, close and delete it
    fclose( tempFileStream );
    remove( filename.c_str() );

    if ( editingVariable ) {
        // Try to execute assignment to copy edited value back into the variable
        const string code = whatToEdit + string( " = " ) + sb.str();
        if ( !shellMainScope->exec( code, "tojs", false, true, false ) ) {
            cout << "error executing assignment: " << code << endl;
        }
    }
    else {
        linenoisePreloadBuffer( sb.str().c_str() );
    }
}
Esempio n. 22
0
static String buildCircleString(const String& radius, const String& centerX, const String& centerY, const String& box)
{
    char opening[] = "circle(";
    char at[] = "at";
    char separator[] = " ";
    StringBuilder result;
    result.appendLiteral(opening);
    if (!radius.isNull())
        result.append(radius);

    if (!centerX.isNull() || !centerY.isNull()) {
        if (!radius.isNull())
            result.appendLiteral(separator);
        result.appendLiteral(at);
        result.appendLiteral(separator);
        result.append(centerX);
        result.appendLiteral(separator);
        result.append(centerY);
    }
    result.appendLiteral(")");
    if (box.length()) {
        result.appendLiteral(separator);
        result.append(box);
    }
    return result.toString();
}
Esempio n. 23
0
JSStringRef JSContextCreateBacktrace(JSContextRef ctx, unsigned maxStackSize)
{
    ExecState* exec = toJS(ctx);
    JSLockHolder lock(exec);
    StringBuilder builder;
    Vector<StackFrame> stackTrace;
    Interpreter::getStackTrace(&exec->vm(), stackTrace, maxStackSize);

    for (size_t i = 0; i < stackTrace.size(); i++) {
        String urlString;
        String functionName;
        StackFrame& frame = stackTrace[i];
        JSValue function = frame.callee.get();
        if (frame.callee)
            functionName = frame.friendlyFunctionName(exec);
        else {
            // Caller is unknown, but if frame is empty we should still add the frame, because
            // something called us, and gave us arguments.
            if (i)
                break;
        }
        unsigned lineNumber = frame.line();
        if (!builder.isEmpty())
            builder.append('\n');
        builder.append('#');
        builder.appendNumber(i);
        builder.append(' ');
        builder.append(functionName);
        builder.appendLiteral("() at ");
        builder.append(urlString);
        if (frame.codeType != StackFrameNativeCode) {
            builder.append(':');
            builder.appendNumber(lineNumber);
        }
        if (!function)
            break;
    }
    return OpaqueJSString::create(builder.toString()).leakRef();
}
Esempio n. 24
0
 std::string HostAndPort::toString() const {
     StringBuilder ss;
     append( ss );
     return ss.str();
 }
static void appendBool(StringBuilder& stringBuilder, bool value)
{
    stringBuilder.append(' ');
    stringBuilder.appendNumber(value);
}
Esempio n. 26
0
    Status storeServerOptions(const moe::Environment& params,
                              const std::vector<std::string>& args) {

        Status ret = setupBinaryName(args);
        if (!ret.isOK()) {
            return ret;
        }

        ret = setupCwd();
        if (!ret.isOK()) {
            return ret;
        }

        ret = setArgvArray(args);
        if (!ret.isOK()) {
            return ret;
        }

        ret = setParsedOpts(params);
        if (!ret.isOK()) {
            return ret;
        }

        if (params.count("verbose")) {
            std::string verbosity = params["verbose"].as<std::string>();
            for (std::string::iterator iterator = verbosity.begin();
                 iterator != verbosity.end(); iterator++) {
                if (*iterator != 'v') {
                    return Status(ErrorCodes::BadValue,
                                  "The \"verbose\" option string cannot contain any characters "
                                  "other than \"v\"");
                }
            }
        }

        // Handle both the "--verbose" string argument and the "-vvvv" arguments at the same time so
        // that we ensure that we set the log level to the maximum of the options provided
        for (string s = ""; s.length() <= 14; s.append("v")) {
            if (!s.empty() && params.count(s)) {
                logger::globalLogDomain()->setMinimumLoggedSeverity(
                        logger::LogSeverity::Debug(s.length()));
            }

            if (params.count("verbose")) {
                std::string verbosity = params["verbose"].as<std::string>();
                if (s == verbosity) {
                    logger::globalLogDomain()->setMinimumLoggedSeverity(
                            logger::LogSeverity::Debug(s.length()));
                }
            }
        }

        if (params.count("enableExperimentalIndexStatsCmd")) {
            serverGlobalParams.experimental.indexStatsCmdEnabled = true;
        }
        if (params.count("enableExperimentalStorageDetailsCmd")) {
            serverGlobalParams.experimental.storageDetailsCmdEnabled = true;
        }

        if (params.count("port")) {
            serverGlobalParams.port = params["port"].as<int>();
        }

        if (params.count("bind_ip")) {
            serverGlobalParams.bind_ip = params["bind_ip"].as<std::string>();
        }

        if (params.count("clusterAuthMode")) {
            serverGlobalParams.clusterAuthMode = params["clusterAuthMode"].as<std::string>();
        }

        if (params.count("quiet")) {
            serverGlobalParams.quiet = true;
        }

        if (params.count("traceExceptions")) {
            DBException::traceExceptions = true;
        }

        if (params.count("maxConns")) {
            serverGlobalParams.maxConns = params["maxConns"].as<int>();

            if (serverGlobalParams.maxConns < 5) {
                return Status(ErrorCodes::BadValue, "maxConns has to be at least 5");
            }
        }

        if (params.count("objcheck")) {
            serverGlobalParams.objcheck = true;
        }
        if (params.count("noobjcheck")) {
            if (params.count("objcheck")) {
                return Status(ErrorCodes::BadValue, "can't have both --objcheck and --noobjcheck");
            }
            serverGlobalParams.objcheck = false;
        }

        if (params.count("bind_ip")) {
            // passing in wildcard is the same as default behavior; remove and warn
            if (serverGlobalParams.bind_ip ==  "0.0.0.0") {
                std::cout << "warning: bind_ip of 0.0.0.0 is unnecessary; "
                          << "listens on all ips by default" << endl;
                serverGlobalParams.bind_ip = "";
            }
        }

#ifndef _WIN32
        if (params.count("unixSocketPrefix")) {
            serverGlobalParams.socket = params["unixSocketPrefix"].as<string>();
        }

        if (params.count("nounixsocket")) {
            serverGlobalParams.noUnixSocket = true;
        }

        if (params.count("fork") && !params.count("shutdown")) {
            serverGlobalParams.doFork = true;
        }
#endif  // _WIN32

        if (params.count("logTimestampFormat")) {
            using logger::MessageEventDetailsEncoder;
            std::string formatterName = params["logTimestampFormat"].as<string>();
            if (formatterName == "ctime") {
                MessageEventDetailsEncoder::setDateFormatter(dateToCtimeString);
            }
            else if (formatterName == "iso8601-utc") {
                MessageEventDetailsEncoder::setDateFormatter(dateToISOStringUTC);
            }
            else if (formatterName == "iso8601-local") {
                MessageEventDetailsEncoder::setDateFormatter(dateToISOStringLocal);
            }
            else {
                StringBuilder sb;
                sb << "Value of logTimestampFormat must be one of ctime, iso8601-utc " <<
                      "or iso8601-local; not \"" << formatterName << "\".";
                return Status(ErrorCodes::BadValue, sb.str());
            }
        }
        if (params.count("logpath")) {
            serverGlobalParams.logpath = params["logpath"].as<string>();
            if (serverGlobalParams.logpath.empty()) {
                return Status(ErrorCodes::BadValue, "logpath cannot be empty if supplied");
            }
        }

        serverGlobalParams.logWithSyslog = params.count("syslog");

#ifndef _WIN32
        if (params.count("syslogFacility")) {
            std::string facility = params["syslogFacility"].as<string>();
            bool set = false;
            // match facility string to facility value
            for (unsigned long i = 0; i < sizeof(facilitynames)/sizeof(facilitynames[0]); i++) {
                if (!facility.compare(facilitynames[i].c_name)) {
                    serverGlobalParams.syslogFacility = facilitynames[i].c_val;
                    set = true;
                }
            }
            if (!set) {
                StringBuilder sb;
                sb << "ERROR: syslogFacility must be set to a string representing one of the "
                   << "possible syslog facilities";
                return Status(ErrorCodes::BadValue, sb.str());
            }
        }
        else {
            serverGlobalParams.syslogFacility = LOG_USER;
        }
#endif // _WIN32

        serverGlobalParams.logAppend = params.count("logappend");
        if (!serverGlobalParams.logpath.empty() && serverGlobalParams.logWithSyslog) {
            return Status(ErrorCodes::BadValue, "Cant use both a logpath and syslog ");
        }

        if (serverGlobalParams.doFork && serverGlobalParams.logpath.empty() &&
            !serverGlobalParams.logWithSyslog) {
            return Status(ErrorCodes::BadValue, "--fork has to be used with --logpath or --syslog");
        }

        if (params.count("keyFile")) {
            serverGlobalParams.keyFile = params["keyFile"].as<string>();
        }

        if ( params.count("pidfilepath")) {
            serverGlobalParams.pidFile = params["pidfilepath"].as<string>();
        }

        if (params.count("setParameter")) {
            std::vector<std::string> parameters =
                params["setParameter"].as<std::vector<std::string> >();
            for (size_t i = 0, length = parameters.size(); i < length; ++i) {
                std::string name;
                std::string value;
                if (!mongoutils::str::splitOn(parameters[i], '=', name, value)) {
                    StringBuilder sb;
                    sb << "Illegal option assignment: \"" << parameters[i] << "\"";
                    return Status(ErrorCodes::BadValue, sb.str());
                }
                ServerParameter* parameter = mapFindWithDefault(
                        ServerParameterSet::getGlobal()->getMap(),
                        name,
                        static_cast<ServerParameter*>(NULL));
                if (NULL == parameter) {
                    StringBuilder sb;
                    sb << "Illegal --setParameter parameter: \"" << name << "\"";
                    return Status(ErrorCodes::BadValue, sb.str());
                }
                if (!parameter->allowedToChangeAtStartup()) {
                    StringBuilder sb;
                    sb << "Cannot use --setParameter to set \"" << name << "\" at startup";
                    return Status(ErrorCodes::BadValue, sb.str());
                }
                Status status = parameter->setFromString(value);
                if (!status.isOK()) {
                    StringBuilder sb;
                    sb << "Bad value for parameter \"" << name << "\": " << status.reason();
                    return Status(ErrorCodes::BadValue, sb.str());
                }
            }
        }
        if (!params.count("clusterAuthMode") && params.count("keyFile")){
            serverGlobalParams.clusterAuthMode = "keyfile";
        }

#ifdef MONGO_SSL
        ret = storeSSLServerOptions(params);
        if (!ret.isOK()) {
            return ret;
        }
#else // ifdef MONGO_SSL
        // Keyfile is currently the only supported value if not using SSL
        if (params.count("clusterAuthMode") && serverGlobalParams.clusterAuthMode != "keyfile") {
            StringBuilder sb;
            sb << "unsupported value for clusterAuthMode " << serverGlobalParams.clusterAuthMode;
            return Status(ErrorCodes::BadValue, sb.str());
        }
#endif

        return Status::OK();
    }
    bool initializeServerGlobalState(bool isMongodShutdownSpecialCase) {

        Listener::globalTicketHolder.resize( cmdLine.maxConns );

#ifndef _WIN32
        if (!fs::is_directory(cmdLine.socket)) {
            cout << cmdLine.socket << " must be a directory" << endl;
            return false;
        }

        if (cmdLine.doFork) {
            fassert(16447, !cmdLine.logpath.empty() || cmdLine.logWithSyslog);

            cout.flush();
            cerr.flush();

            cmdLine.parentProc = getpid();

            // facilitate clean exit when child starts successfully
            setupLaunchSignals();

            pid_t c = fork();
            if ( c ) {
                int pstat;
                waitpid(c, &pstat, 0);

                if ( WIFEXITED(pstat) ) {
                    if ( ! WEXITSTATUS(pstat) ) {
                        cout << "child process started successfully, parent exiting" << endl;
                    }

                    _exit( WEXITSTATUS(pstat) );
                }

                _exit(50);
            }

            if ( chdir("/") < 0 ) {
                cout << "Cant chdir() while forking server process: " << strerror(errno) << endl;
                ::_exit(-1);
            }
            setsid();

            cmdLine.leaderProc = getpid();

            pid_t c2 = fork();
            if ( c2 ) {
                int pstat;
                cout << "forked process: " << c2 << endl;
                waitpid(c2, &pstat, 0);

                if ( WIFEXITED(pstat) ) {
                    _exit( WEXITSTATUS(pstat) );
                }

                _exit(51);
            }

            // stdout handled in initLogging
            //fclose(stdout);
            //freopen("/dev/null", "w", stdout);

            fclose(stderr);
            fclose(stdin);

            FILE* f = freopen("/dev/null", "w", stderr);
            if ( f == NULL ) {
                cout << "Cant reassign stderr while forking server process: " << strerror(errno) << endl;
                return false;
            }

            f = freopen("/dev/null", "r", stdin);
            if ( f == NULL ) {
                cout << "Cant reassign stdin while forking server process: " << strerror(errno) << endl;
                return false;
            }

            setupCoreSignals();
            setupSignals( true );
        }

        if (cmdLine.logWithSyslog) {
            StringBuilder sb;
            sb << cmdLine.binaryName << "." << cmdLine.port;
            Logstream::useSyslog( sb.str().c_str() );
        }
#endif
        if (!cmdLine.logpath.empty() && !isMongodShutdownSpecialCase) {
            fassert(16448, !cmdLine.logWithSyslog);
            string absoluteLogpath = boost::filesystem::absolute(
                    cmdLine.logpath, cmdLine.cwd).string();
            if (!initLogging(absoluteLogpath, cmdLine.logAppend)) {
                cout << "Bad logpath value: \"" << absoluteLogpath << "\"; terminating." << endl;
                return false;
            }
        }

        if (!cmdLine.pidFile.empty()) {
            writePidFile(cmdLine.pidFile);
        }

        if (!cmdLine.keyFile.empty()) {

            if (!setUpSecurityKey(cmdLine.keyFile)) {
                // error message printed in setUpPrivateKey
                return false;
            }

            noauth = false;
        }

#ifdef MONGO_SSL
        if (cmdLine.sslOnNormalPorts) {

            if ( cmdLine.sslPEMKeyPassword.size() == 0 ) {
                log() << "need sslPEMKeyPassword" << endl;
                return false;
            }

            if ( cmdLine.sslPEMKeyFile.size() == 0 ) {
                log() << "need sslPEMKeyFile" << endl;
                return false;
            }

            cmdLine.sslServerManager = new SSLManager( false );
            if ( ! cmdLine.sslServerManager->setupPEM( cmdLine.sslPEMKeyFile , cmdLine.sslPEMKeyPassword ) ) {
                return false;
            }
        }
        else if ( cmdLine.sslPEMKeyFile.size() || cmdLine.sslPEMKeyPassword.size() ) {
            log() << "need to enable sslOnNormalPorts" << endl;
            return false;
        }
#endif

        return true;
    }
Esempio n. 28
0
    Status addGeneralServerOptions(moe::OptionSection* options) {
        StringBuilder portInfoBuilder;
        StringBuilder maxConnInfoBuilder;

        portInfoBuilder << "specify port number - " << ServerGlobalParams::DefaultDBPort << " by default";
        maxConnInfoBuilder << "max number of simultaneous connections - "
                           << DEFAULT_MAX_CONN << " by default";

        Status ret = options->addOption(OD("help", "help,h", moe::Switch,
                    "show this usage information", true));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("version", "version", moe::Switch, "show version information",
                    true));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("config", "config,f", moe::String,
                    "configuration file specifying additional options", true));
        if (!ret.isOK()) {
            return ret;
        }
        // The verbosity level can be set at startup in the following ways.  Note that if multiple
        // methods for setting the verbosity are specified simultaneously, the verbosity will be set
        // based on the whichever option specifies the highest level
        //
        // Command Line Option | Resulting Verbosity
        // _________________________________________
        // (none)              | 0
        // --verbose ""        | 0
        // --verbose           | 1
        // --verbose v         | 1
        // --verbose vv        | 2 (etc.)
        // -v                  | 1
        // -vv                 | 2 (etc.)
        //
        // INI Config Option   | Resulting Verbosity
        // _________________________________________
        // verbose=            | 0
        // verbose=v           | 1
        // verbose=vv          | 2 (etc.)
        // v=true              | 1
        // vv=true             | 2 (etc.)
        //
        // JSON Config Option  | Resulting Verbosity
        // _________________________________________
        // { "verbose" : "" }  | 0
        // { "verbose" : "v" } | 1
        // { "verbose" : "vv" }| 2 (etc.)
        // { "v" : true }      | 1
        // { "vv" : true }     | 2 (etc.)
        ret = options->addOption(OD("verbose", "verbose,v", moe::String,
                    "be more verbose (include multiple times for more verbosity e.g. -vvvvv)",
                    true, moe::Value(),
                    moe::Value(std::string("v"))));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("quiet", "quiet", moe::Switch, "quieter output", true));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("port", "port", moe::Int, portInfoBuilder.str().c_str(), true));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("bind_ip", "bind_ip", moe::String,
                    "comma separated list of ip addresses to listen on - all local ips by default",
                    true));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("maxConns", "maxConns", moe::Int,
                    maxConnInfoBuilder.str().c_str(), true));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("logpath", "logpath", moe::String,
                    "log file to send write to instead of stdout - has to be a file, not directory",
                    true));
        if (!ret.isOK()) {
            return ret;
        }
#ifndef _WIN32
        ret = options->addOption(OD("syslogFacility", "syslogFacility", moe::String,
                    "syslog facility used for monogdb syslog message",
                    true));
        if (!ret.isOK()) {
            return ret;
        }
#endif // _WIN32
        ret = options->addOption(OD("logappend", "logappend", moe::Switch,
                    "append to logpath instead of over-writing", true));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("logTimestampFormat", "logTimestampFormat", moe::String,
                    "Desired format for timestamps in log messages. One of ctime, "
                    "iso8601-utc or iso8601-local", true));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("pidfilepath", "pidfilepath", moe::String,
                    "full path to pidfile (if not set, no pidfile is created)", true));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("keyFile", "keyFile", moe::String,
                    "private key for cluster authentication", true));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("setParameter", "setParameter", moe::StringVector,
                    "Set a configurable parameter", true, moe::Value(), moe::Value(), true));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("httpinterface", "httpinterface", moe::Switch,
                    "enable http interface", true));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("clusterAuthMode", "clusterAuthMode", moe::String,
                    "Authentication mode used for cluster authentication. Alternatives are "
                    "(keyfile|sendKeyfile|sendX509|x509)", true));
        if (!ret.isOK()) {
            return ret;
        }
#ifndef _WIN32
        ret = options->addOption(OD("nounixsocket", "nounixsocket", moe::Switch,
                    "disable listening on unix sockets", true));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("unixSocketPrefix", "unixSocketPrefix", moe::String,
                    "alternative directory for UNIX domain sockets (defaults to /tmp)", true));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("fork", "fork", moe::Switch, "fork server process", true));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("syslog", "syslog", moe::Switch,
                    "log to system's syslog facility instead of file or stdout", true));
        if (!ret.isOK()) {
            return ret;
        }
#endif

        /* support for -vv -vvvv etc. */
        for (string s = "vv"; s.length() <= 12; s.append("v")) {
            ret = options->addOption(OD(s.c_str(), s.c_str(), moe::Switch, "verbose", false));
            if(!ret.isOK()) {
                return ret;
            }
        }

        // Extra hidden options
        ret = options->addOption(OD("nohttpinterface", "nohttpinterface", moe::Switch,
                    "disable http interface", false));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("objcheck", "objcheck", moe::Switch,
                    "inspect client data for validity on receipt (DEFAULT)", false));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("noobjcheck", "noobjcheck", moe::Switch,
                    "do NOT inspect client data for validity on receipt", false));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("traceExceptions", "traceExceptions", moe::Switch,
                    "log stack traces for every exception", false));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("enableExperimentalIndexStatsCmd",
                    "enableExperimentalIndexStatsCmd", moe::Switch,
                    "EXPERIMENTAL (UNSUPPORTED). "
                    "Enable command computing aggregate statistics on indexes.", false));
        if (!ret.isOK()) {
            return ret;
        }
        ret = options->addOption(OD("enableExperimentalStorageDetailsCmd",
                    "enableExperimentalStorageDetailsCmd", moe::Switch,
                    "EXPERIMENTAL (UNSUPPORTED). "
                    "Enable command computing aggregate statistics on storage.", false));
        if (!ret.isOK()) {
            return ret;
        }

        return Status::OK();
    }
    /**
     * Parse server-first-message on the form:
     * r=client-nonce|server-nonce,s=user-salt,i=iteration-count
     *
     * Generate client-final-message of the form:
     * c=channel-binding(base64),r=client-nonce|server-nonce,p=ClientProof
     *
     **/
    StatusWith<bool> SaslSCRAMSHA1ClientConversation::_secondStep(const std::vector<string>& input,
                                                                  std::string* outputData) {
        if (input.size() != 3) {
            return StatusWith<bool>(ErrorCodes::BadValue, mongoutils::str::stream() <<
                "Incorrect number of arguments for first SCRAM-SHA-1 server message, got " <<
                input.size() << " expected 3");
        }
        else if (!str::startsWith(input[0], "r=") || input[0].size() < 2) {
            return StatusWith<bool>(ErrorCodes::BadValue, mongoutils::str::stream() <<
                "Incorrect SCRAM-SHA-1 client|server nonce: " << input[0]);
        }
        else if (!str::startsWith(input[1], "s=") || input[1].size() < 6) {
            return StatusWith<bool>(ErrorCodes::BadValue, mongoutils::str::stream() <<
                "Incorrect SCRAM-SHA-1 salt: " << input[1]);
        }
        else if(!str::startsWith(input[2], "i=") || input[2].size() < 3) {
            return StatusWith<bool>(ErrorCodes::BadValue, mongoutils::str::stream() <<
                "Incorrect SCRAM-SHA-1 iteration count: " << input[2]);
        }

        std::string nonce = input[0].substr(2);
        if(!str::startsWith(nonce, _clientNonce)) {
            return StatusWith<bool>(ErrorCodes::BadValue, mongoutils::str::stream() <<
                "Server SCRAM-SHA-1 nonce does not match client nonce" << input[2]);
        }

        std::string salt = input[1].substr(2);
        int iterationCount;

        Status status = parseNumberFromStringWithBase(input[2].substr(2), 10, &iterationCount);
        if (status != Status::OK()) {
            return StatusWith<bool>(ErrorCodes::BadValue, mongoutils::str::stream() <<
                "Failed to parse SCRAM-SHA-1 iteration count: " << input[2]);
        }

        // Append client-final-message-without-proof to _authMessage
        _authMessage += "c=biws,r=" + nonce;

        std::string decodedSalt;
        try {
            decodedSalt = base64::decode(salt);
        }
        catch (const DBException& ex) {
            return StatusWith<bool>(ex.toStatus());
        }

        scram::generateSaltedPassword(
                            _saslClientSession->getParameter(SaslClientSession::parameterPassword),
                            reinterpret_cast<const unsigned char*>(decodedSalt.c_str()),
                            decodedSalt.size(),
                            iterationCount,
                            _saltedPassword);

        std::string clientProof = scram::generateClientProof(_saltedPassword, _authMessage);

        StringBuilder sb;
        sb << "c=biws,r=" << nonce << ",p=" << clientProof;
        *outputData = sb.str();

        return StatusWith<bool>(false);
    }
Esempio n. 30
0
void TypeExpr::print(StringBuilder& buffer, unsigned indent) const {
    buffer.indent(indent);
    buffer.setColor(COL_EXPR);
    buffer << "TypeExpr ";
    getType().print(buffer);
}