Example #1
0
 int compareItems(QCollection::Item item1, QCollection::Item item2)
 {
   return qstricmp(((IndexField *)item1)->name,((IndexField *)item2)->name);
 }
Example #2
0
result_t JsonRpcHandler::invoke(object_base *v, obj_ptr<Handler_base> &retVal,
                                AsyncEvent *ac)
{
    if (ac)
        return CHECK_ERROR(CALL_E_NOASYNC);

    obj_ptr<Message_base> msg = Message_base::getInstance(v);
    if (msg == NULL)
        return CHECK_ERROR(CALL_E_BADVARTYPE);

    Isolate* isolate = Isolate::now();
    obj_ptr<HttpRequest_base> htreq = HttpRequest_base::getInstance(v);
    obj_ptr<SeekableStream_base> body;
    obj_ptr<Buffer_base> buf;
    v8::Local<v8::Value> jsval;
    v8::Local<v8::Object> o;
    Variant result;
    std::string str;
    int64_t len;
    int32_t sz, i;
    result_t hr;
    bool bFormReq = false;
    obj_ptr<List_base> params;

    if (htreq != NULL)
    {
        if (htreq->firstHeader("Content-Type", result) == CALL_RETURN_NULL)
            return CHECK_ERROR(Runtime::setError("jsonrpc: Content-Type is missing."));

        str = result.string();
        if (!qstricmp(str.c_str(), "application/x-www-form-urlencoded", 33))
        {
            obj_ptr<HttpCollection_base> form;
            htreq->get_form(form);
            if (form->first("jsonrpc", result) == CALL_RETURN_NULL)
                return CHECK_ERROR(Runtime::setError("jsonrpc: Invalid form data."));
            str = result.string();
            bFormReq = true;
        }
        else if (qstricmp(str.c_str(), "application/json", 16))
            return CHECK_ERROR(Runtime::setError("jsonrpc: Invalid Content-Type."));
    }

    if (!bFormReq)
    {
        msg->get_body(body);

        body->size(len);
        sz = (int32_t) len;

        body->rewind();
        hr = body->ac_read(sz, buf);
        if (hr < 0)
            return hr;
        if (hr == CALL_RETURN_NULL)
            return CHECK_ERROR(Runtime::setError("jsonrpc: request body is empty."));
        body.Release();

        buf->toString(str);
        buf.Release();
    }

    hr = encoding_base::jsonDecode(str.c_str(), jsval);
    if (hr < 0)
        return hr;

    if (!jsval->IsObject())
        return CHECK_ERROR(Runtime::setError("jsonrpc: Invalid rpc request."));

    o = v8::Local<v8::Object>::Cast(jsval);

    jsval = o->Get(v8::String::NewFromUtf8(isolate->m_isolate, "method",
                                           v8::String::kNormalString, 6));
    if (IsEmpty(jsval))
        return CHECK_ERROR(Runtime::setError("jsonrpc: method is missing."));

    msg->get_value(str);
    str += '/';
    str.append(*v8::String::Utf8Value(jsval));
    msg->set_value(str.c_str());

    jsval = o->Get(v8::String::NewFromUtf8(isolate->m_isolate, "params",
                                           v8::String::kNormalString, 6));
    if (!jsval.IsEmpty() && jsval->IsArray())
    {
        v8::Local<v8::Array> jsparams = v8::Local<v8::Array>::Cast(jsval);

        sz = jsparams->Length();
        msg->get_params(params);
        params->resize(sz);

        for (i = 0; i < sz; i++)
            params->_indexed_setter(i, jsparams->Get(i));
    }

    obj_ptr<Handler_base> hdlr1;
    hr = JSHandler::js_invoke(m_handler, v, hdlr1, NULL);
    if (hr >= 0 && hr != CALL_RETURN_NULL)
        hr = mq_base::ac_invoke(hdlr1, v);

    v8::Local<v8::String> strId = v8::String::NewFromUtf8(isolate->m_isolate, "id",
                                  v8::String::kNormalString, 2);
    jsval = o->Get(strId);

    o = v8::Object::New(isolate->m_isolate);
    o->Set(strId, jsval);

    if (hr < 0)
    {
        asyncLog(console_base::_ERROR, "JsonRpcHandler: " + getResultMessage(hr));

        result_t hr1 = encoding_base::jsonEncode(o, str);
        if (hr1 < 0)
            return hr1;

        if (str.length() <= 2)
            str.assign("{", 1);
        else
        {
            str.resize(str.length() - 1);
            str += ',';
        }

        if (hr == CALL_E_INVALID_CALL)
            str.append(
                "\"error\": {\"code\": -32601, \"message\": \"Method not found.\"}}");
        else
            str.append(
                "\"error\": {\"code\": -32603, \"message\": \"Internal error.\"}}");
    }
    else
    {
        msg->get_result(result);
        o->Set(v8::String::NewFromUtf8(isolate->m_isolate, "result",
                                       v8::String::kNormalString, 6), result);

        hr = encoding_base::jsonEncode(o, str);

        if (hr < 0)
            return hr;
    }

    body = new MemoryStream();

    if (bFormReq)
    {
        std::string strTemp;

        strTemp.assign(
            "<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><script>window.name=\"",
            94);

        encoding_base::jsstr(str.c_str(), false, str);
        strTemp.append(str);

        strTemp.append("\";</script></html>", 18);

        str = strTemp;
    }

    buf = new Buffer(str);
    hr = body->ac_write(buf);
    if (hr < 0)
        return hr;


    obj_ptr<Message_base> rep;
    hr = msg->get_response(rep);
    if (hr < 0)
        return hr;

    rep->set_body(body);

    if (htreq)
        ((HttpMessage_base *)(Message_base *)rep)->setHeader("Content-Type",
                bFormReq ? "text/html" : "application/json");

    return CALL_RETURN_NULL;
}
Example #3
0
bool QHttpNetworkReplyPrivate::isGzipped()
{
    QByteArray encoding = headerField("content-encoding");
    return qstricmp(encoding.constData(), "gzip") == 0;
}
Example #4
0
result_t XmlDocument::load(Buffer_base *source)
{
    std::string strBuf;
    result_t hr;

    source->toString(strBuf);

    if (!m_isXml)
    {
        _parser p(strBuf);
        const char *ptr;

        while ((ptr = qstristr(p.now(), "<meta")) != NULL && qisspace(ptr[5]))
        {
            bool bContentType = false;
            std::string content;

            p.pos = (int32_t)(ptr - p.string + 5);
            while (true)
            {
                std::string key, value;

                p.skipSpace();
                p.getWord(key, '=', '>');

                if (key.empty())
                    break;

                if (p.want('='))
                {
                    if (p.want('\"'))
                    {
                        p.getString(value, '\"', '>');
                        p.want('\"');
                    }
                    else
                        p.getWord(value, '>');
                }

                if (!qstricmp(key.c_str(), "charset"))
                {
                    m_encoding = value;
                    break;
                }
                else if (!qstricmp(key.c_str(), "content"))
                    content = value;
                else if (!qstricmp(key.c_str(), "http-equiv") &&
                         !qstricmp(value.c_str(), "Content-Type"))
                    bContentType = true;
            }

            if (bContentType && !content.empty())
            {
                _parser p1(content);

                while (true)
                {
                    std::string key, value;

                    p1.skipSpace();
                    p1.getWord(key, ';', '=');

                    if (key.empty())
                        break;

                    if (p1.want('='))
                        p1.getWord(value, ';');

                    p1.want(';');

                    if (!qstricmp(key.c_str(), "charset"))
                    {
                        m_encoding = value;
                        break;
                    }
                }
            }

            if (!m_encoding.empty())
                break;
        }

        if (!m_encoding.empty())
        {
            encoding_iconv conv(m_encoding.c_str());
            conv.decode(strBuf, strBuf);
        }
    }

    hr = load(strBuf.c_str());
    if (hr < 0)
        return hr;

    return 0;
}
static int rgb_cmp( const void *d1, const void *d2 )
{
    return qstricmp( ((RGBData *)d1)->name, ((RGBData *)d2)->name );
}
Example #6
0
static int32_t mt_cmp(const void* p, const void* q)
{
    return qstricmp(*(const char**)p, *(const char**)q);
}
Example #7
0
static int getToken()
{
    const char tab[] = "abfnrtv";
    const char backTab[] = "\a\b\f\n\r\t\v";
    uint n;

    yyIdentLen = 0;
    yyCommentLen = 0;
    yyStringLen = 0;

    while ( yyCh != EOF ) {
	yyLineNo = yyCurLineNo;

	if ( isalpha(yyCh) || yyCh == '_' ) {
	    do {
		if ( yyIdentLen < sizeof(yyIdent) - 1 )
		    yyIdent[yyIdentLen++] = (char) yyCh;
		yyCh = getChar();
	    } while ( isalnum(yyCh) || yyCh == '_' );
	    yyIdent[yyIdentLen] = '\0';

	    switch ( yyIdent[0] ) {
	    case 'Q':
		if ( strcmp(yyIdent + 1, "_OBJECT") == 0 ) {
		    return Tok_Q_OBJECT;
		} else if ( strcmp(yyIdent + 1, "T_TR_NOOP") == 0 ) {
		    return Tok_tr;
		} else if ( strcmp(yyIdent + 1, "T_TRANSLATE_NOOP") == 0 ) {
		    return Tok_translate;
		}
		break;
	    case 'T':
		// TR() for when all else fails
		if ( qstricmp(yyIdent + 1, "R") == 0 )
		    return Tok_tr;
		break;
	    case 'c':
		if ( strcmp(yyIdent + 1, "lass") == 0 )
		    return Tok_class;
		break;
	    case 'f':
		/*
		  QTranslator::findMessage() has the same parameters as
		  QApplication::translate().
		*/
		if ( strcmp(yyIdent + 1, "indMessage") == 0 )
		    return Tok_translate;
		break;
	    case 'n':
		if ( strcmp(yyIdent + 1, "amespace") == 0 )
		    return Tok_namespace;
		break;
	    case 'r':
		if ( strcmp(yyIdent + 1, "eturn") == 0 )
		    return Tok_return;
		break;
	    case 's':
		if ( strcmp(yyIdent + 1, "truct") == 0 )
		    return Tok_class;
		break;
	    case 't':
		if ( strcmp(yyIdent + 1, "r") == 0 ) {
		    return Tok_tr;
		} else if ( qstrcmp(yyIdent + 1, "rUtf8") == 0 ) {
		    return Tok_trUtf8;
		} else if ( qstrcmp(yyIdent + 1, "ranslate") == 0 ) {
		    return Tok_translate;
		}
	    }
	    return Tok_Ident;
	} else {
	    switch ( yyCh ) {
	    case '#':
		/*
		  Early versions of lupdate complained about
		  unbalanced braces in the following code:

		      #ifdef ALPHA
			  while ( beta ) {
		      #else
			  while ( gamma ) {
		      #endif
			      delta;
			  }

		  The code contains, indeed, two opening braces for
		  one closing brace; yet there's no reason to panic.

		  The solution is to remember yyBraceDepth as it was
		  when #if, #ifdef or #ifndef was met, and to set
		  yyBraceDepth to that value when meeting #elif or
		  #else.
		*/
		do {
		    yyCh = getChar();
		} while ( isspace(yyCh) && yyCh != '\n' );

		switch ( yyCh ) {
		case 'i':
		    yyCh = getChar();
		    if ( yyCh == 'f' ) {
			// if, ifdef, ifndef
			yySavedBraceDepth.push( yyBraceDepth );
                        yySavedParenDepth.push( yyParenDepth );
		    }
		    break;
		case 'e':
		    yyCh = getChar();
		    if ( yyCh == 'l' ) {
			// elif, else
			if ( !yySavedBraceDepth.isEmpty() ) {
			    yyBraceDepth = yySavedBraceDepth.top();
                            yyParenDepth = yySavedParenDepth.top();
			}
		    } else if ( yyCh == 'n' ) {
			// endif
			if ( !yySavedBraceDepth.isEmpty() ) {
			    yySavedBraceDepth.pop();
                            yySavedParenDepth.pop();
			}
		    }
		}
		while ( isalnum(yyCh) || yyCh == '_' )
		    yyCh = getChar();
		break;
	    case '/':
		yyCh = getChar();
		if ( yyCh == '/' ) {
		    do {
			yyCh = getChar();
		    } while ( yyCh != EOF && yyCh != '\n' );
		} else if ( yyCh == '*' ) {
		    bool metAster = FALSE;
		    bool metAsterSlash = FALSE;

		    while ( !metAsterSlash ) {
			yyCh = getChar();
			if ( yyCh == EOF ) {
			    fprintf( stderr,
				     "%s: Unterminated C++ comment starting at"
				     " line %d\n",
				     (const char *) yyFileName, yyLineNo );
			    yyComment[yyCommentLen] = '\0';
			    return Tok_Comment;
			}
			if ( yyCommentLen < sizeof(yyComment) - 1 )
			    yyComment[yyCommentLen++] = (char) yyCh;

			if ( yyCh == '*' )
			    metAster = TRUE;
			else if ( metAster && yyCh == '/' )
			    metAsterSlash = TRUE;
			else
			    metAster = FALSE;
		    }
		    yyCh = getChar();
		    yyCommentLen -= 2;
		    yyComment[yyCommentLen] = '\0';
		    return Tok_Comment;
		}
		break;
	    case '"':
		yyCh = getChar();

		while ( yyCh != EOF && yyCh != '\n' && yyCh != '"' ) {
		    if ( yyCh == '\\' ) {
			yyCh = getChar();

			if ( yyCh == '\n' ) {
			    yyCh = getChar();
			} else if ( yyCh == 'x' ) {
			    QCString hex = "0";

			    yyCh = getChar();
			    while ( isxdigit(yyCh) ) {
				hex += (char) yyCh;
				yyCh = getChar();
			    }
			    sscanf( hex, "%x", &n );
			    if ( yyStringLen < sizeof(yyString) - 1 )
				yyString[yyStringLen++] = (char) n;
			} else if ( yyCh >= '0' && yyCh < '8' ) {
			    QCString oct = "";

			    do {
				oct += (char) yyCh;
				yyCh = getChar();
			    } while ( yyCh >= '0' && yyCh < '8' );
			    sscanf( oct, "%o", &n );
			    if ( yyStringLen < sizeof(yyString) - 1 )
				yyString[yyStringLen++] = (char) n;
			} else {
			    const char *p = strchr( tab, yyCh );
			    if ( yyStringLen < sizeof(yyString) - 1 )
				yyString[yyStringLen++] = ( p == 0 ) ?
					(char) yyCh : backTab[p - tab];
			    yyCh = getChar();
			}
		    } else {
			if ( yyStringLen < sizeof(yyString) - 1 )
			    yyString[yyStringLen++] = (char) yyCh;
			yyCh = getChar();
		    }
		}
		yyString[yyStringLen] = '\0';

		if ( yyCh != '"' )
		    qWarning( "%s:%d: Unterminated C++ string",
			      (const char *) yyFileName, yyLineNo );

		if ( yyCh == EOF ) {
		    return Tok_Eof;
		} else {
		    yyCh = getChar();
		    return Tok_String;
		}
		break;
	    case '-':
		yyCh = getChar();
		if ( yyCh == '>' ) {
		    yyCh = getChar();
		    return Tok_Arrow;
		}
		break;
	    case ':':
		yyCh = getChar();
		if ( yyCh == ':' ) {
		    yyCh = getChar();
		    return Tok_Gulbrandsen;
		}
		return Tok_Colon;
	    case '\'':
		yyCh = getChar();
		if ( yyCh == '\\' )
		    yyCh = getChar();

		do {
		    yyCh = getChar();
		} while ( yyCh != EOF && yyCh != '\'' );
		yyCh = getChar();
		break;
	    case '{':
                if (yyBraceDepth == 0)
		    yyBraceLineNo = yyCurLineNo;
		yyBraceDepth++;
		yyCh = getChar();
		return Tok_LeftBrace;
	    case '}':
                if (yyBraceDepth == 0)
		    yyBraceLineNo = yyCurLineNo;
		yyBraceDepth--;
		yyCh = getChar();
		return Tok_RightBrace;
	    case '(':
                if (yyParenDepth == 0)
		    yyParenLineNo = yyCurLineNo;
		yyParenDepth++;
		yyCh = getChar();
		return Tok_LeftParen;
	    case ')':
		if (yyParenDepth == 0)
		    yyParenLineNo = yyCurLineNo;
		yyParenDepth--;
		yyCh = getChar();
		return Tok_RightParen;
	    case ',':
		yyCh = getChar();
		return Tok_Comma;
	    case ';':
		yyCh = getChar();
		return Tok_Semicolon;
	    default:
		yyCh = getChar();
	    }
	}
    }
    return Tok_Eof;
}
Example #8
0
QVariant QX11Data::motifdndObtainData(const char *mimeType)
{
    QByteArray result;

    if (Dnd_selection == 0 || !dropWidget)
        return result;

    // try to convert the selection to the requested property
    // qDebug("trying to convert to '%s'", mimeType);

    int n=0;
    QByteArray f;
    do {
        f = motifdndFormat(n);
        if (f.isEmpty())
            return result;
        n++;
    } while(qstricmp(mimeType, f.data()));

    Atom conversion_type = XNone;
    if (f == "text/plain;charset=ISO-8859-1") {
        conversion_type = XA_STRING;
    } else if (f == "text/plain;charset=UTF-8") {
        conversion_type = ATOM(UTF8_STRING);
    } else if (f == (QByteArray("text/plain;charset=") + QTextCodec::codecForLocale()->name())) {
        conversion_type = ATOM(COMPOUND_TEXT);
    } else if (f == "text/plain") {
        conversion_type = ATOM(TEXT);
    } else if (f.startsWith("x-motif-dnd/")) {
        // strip off the "x-motif-dnd/" prefix
        conversion_type = X11->xdndStringToAtom(f.remove(0, 12));
    }

    if (XGetSelectionOwner(X11->display, Dnd_selection) == XNone) {
        return result; // should never happen?
    }

    QWidget* tw = dropWidget;
    if ((dropWidget->windowType() == Qt::Desktop)) {
        tw = new QWidget;
    }

    // convert selection to the appropriate type
    XConvertSelection (X11->display, Dnd_selection, conversion_type,
                       Dnd_selection, tw->internalWinId(), Dnd_selection_time);

    XFlush(X11->display);

#ifndef QT_NO_CLIPBOARD // for QT_WEBOS
    XEvent xevent;
    bool got=X11->clipboardWaitForEvent(tw->internalWinId(), SelectionNotify, &xevent, 5000);
    if (got) {
        Atom type;

        if (X11->clipboardReadProperty(tw->internalWinId(), Dnd_selection, true, &result, 0, &type, 0)) {
        }
    }

    //   we have to convert selection in order to indicate success to the initiator
    XConvertSelection (X11->display, Dnd_selection, ATOM(XmTRANSFER_SUCCESS),
                       Dnd_selection, tw->internalWinId(), Dnd_selection_time);

    // wait again for SelectionNotify event
    X11->clipboardWaitForEvent(tw->internalWinId(), SelectionNotify, &xevent, 5000);
#endif // QT_NO_CLIPBOARD // for QT_WEBOS

    if ((dropWidget->windowType() == Qt::Desktop)) {
        delete tw;
    }

    return result;
}
void HttpUploadCollection::parse(exlib::string &str, const char *boundary)
{
    const char *pstr = str.c_str();
    int32_t nSize = (int32_t) str.length();
    exlib::string strName;
    exlib::string strFileName;
    exlib::string strContentType;
    exlib::string strContentTransferEncoding;
    const char *p, *p1, *p2, *szQueryString;
    const char *pstrSplit;
    int32_t uiSplitSize;
    char ch;

    boundary += 20;
    while (*boundary && *boundary == ' ')
        boundary++;

    if (qstricmp(boundary, "boundary=", 9))
        return;

    boundary += 9;
    uiSplitSize = (int32_t) qstrlen(boundary);

    pstrSplit = szQueryString = pstr;

    if (nSize < uiSplitSize + 2 || szQueryString[0] != '-'
            || szQueryString[1] != '-'
            || qstrcmp(szQueryString + 2, boundary, uiSplitSize))
        return;

    uiSplitSize += 2;
    szQueryString += uiSplitSize;
    nSize -= uiSplitSize;

    while (nSize)
    {
        strFileName.clear();
        strContentType.clear();
        strContentTransferEncoding.clear();

        while (nSize > 0)
        {
            ch = *szQueryString++;
            nSize--;
            if (ch != '\r')
                return;
            if (nSize > 0 && *szQueryString == '\n')
            {
                nSize--;
                szQueryString++;
            }

            p = szQueryString;
            while (nSize > 0 && *p != '\r')
            {
                nSize--;
                p++;
            }

            if (nSize == 0)
                break;

            p1 = szQueryString;
            szQueryString = p;

            if (p != p1)
            {
                if (p1 + 20 < p && !qstricmp(p1, "Content-Disposition:", 20))
                {
                    p1 += 20;
                    while (p1 < p && *p1 == ' ')
                        p1++;
                    if (p1 + 10 >= p || qstricmp(p1, "form-data;", 10))
                        return;

                    p1 += 10;
                    while (p1 < p && *p1 == ' ')
                        p1++;
                    if (p1 + 5 >= p || qstricmp(p1, "name=", 5))
                        return;

                    p1 += 5;

                    while (p1 < p && *p1 == ' ')
                        p1++;

                    ch = ';';
                    if (*p1 == '\"')
                    {
                        p1++;
                        ch = '\"';
                    }

                    p2 = p1;
                    while (p1 < p && *p1 != ch)
                        p1++;

                    strName.assign(p2, (int32_t) (p1 - p2));

                    if (p1 < p && *p1 == '\"')
                        p1++;

                    if (p1 < p && *p1 == ';')
                        p1++;

                    while (p1 < p && *p1 == ' ')
                        p1++;

                    if (p1 + 9 < p && !qstricmp(p1, "filename=", 9))
                    {
                        p1 += 9;

                        while (p1 < p && *p1 == ' ')
                            p1++;

                        ch = ';';
                        if (*p1 == '\"')
                        {
                            p1++;
                            ch = '\"';
                        }

                        p2 = p1;
                        while (p1 < p && *p1 != ch)
                        {
                            if (*p1 == '/' || *p1 == '\\')
                                p2 = p1 + 1;
                            p1++;
                        }

                        strFileName.assign(p2, (int32_t) (p1 - p2));
                    }
                }
                else if (p1 + 13 < p && !qstricmp(p1, "Content-Type:", 13))
                {
                    p1 += 13;
                    while (p1 < p && *p1 == ' ')
                        p1++;
                    strContentType.assign(p1, (int32_t) (p - p1));
                }
                else if (p1 + 26 < p && !qstricmp(p1, "Content-Transfer-Encoding:", 26))
                {
                    p1 += 26;
                    while (p1 < p && *p1 == ' ')
                        p1++;
                    strContentTransferEncoding.assign(p1, (int32_t) (p - p1));
                }
            }
            else
            {
                ch = *szQueryString++;
                nSize--;
                if (ch != '\r')
                    return;
                if (nSize > 0 && *szQueryString == '\n')
                {
                    nSize--;
                    szQueryString++;
                }
                break;
            }
        }

        p = szQueryString;
        p1 = p + nSize;
        while (p1 > p && (p = (char *) memchr(p, '-', p1 - p))
                && p1 > p + uiSplitSize && memcmp(p, pstrSplit, uiSplitSize))
            p++;

        if (!p || p1 <= p + uiSplitSize)
            break;

        nSize = (int32_t) (p1 - p - uiSplitSize);
        p1 = szQueryString;
        szQueryString = p + uiSplitSize;

        p--;
        ch = *p;
        if (ch != '\n')
            return;
        if (*(p - 1) == '\r')
            p--;

        if (!strName.empty())
        {
            int32_t uiSize = (int32_t) (p - p1);
            exlib::string strTemp;
            Variant varTemp;

            strTemp.assign(p1, uiSize);

            if (strFileName.empty())
                varTemp = strTemp;
            else
            {
                obj_ptr<HttpUploadData> objTemp = new HttpUploadData();
                date_t tm;

                objTemp->m_name = strFileName;
                objTemp->m_type = strContentType;
                objTemp->m_encoding = strContentTransferEncoding;
                objTemp->m_body = new MemoryStream::CloneStream(strTemp, tm);

                varTemp = objTemp;
            }

            add(strName, varTemp);
        }
    }
}
Example #10
0
void EngineShoutcast::updateFromPreferences() {
    qDebug() << "EngineShoutcast: updating from preferences";

    m_pUpdateShoutcastFromPrefs->slotSet(0.0f);

    m_format_is_mp3 = false;
    m_format_is_ov = false;
    m_protocol_is_icecast1 = false;
    m_protocol_is_icecast2 = false;
    m_protocol_is_shoutcast = false;
    m_ogg_dynamic_update = false;

    // Convert a bunch of QStrings to QByteArrays so we can get regular C char*
    // strings to pass to libshout.

    QString codec = m_pConfig->getValueString(ConfigKey(SHOUTCAST_PREF_KEY, "metadata_charset"));
    QByteArray baCodec = codec.toLatin1();
    m_pTextCodec = QTextCodec::codecForName(baCodec);
    if (!m_pTextCodec) {
        qDebug() << "Couldn't find shoutcast metadata codec for codec:" << codec
                 << " defaulting to ISO-8859-1.";
    }

    // Indicates our metadata is in the provided charset.
    shout_metadata_add(m_pShoutMetaData, "charset",  baCodec.constData());

    // Host, server type, port, mountpoint, login, password should be latin1.
    QByteArray baHost = m_pConfig->getValueString(
        ConfigKey(SHOUTCAST_PREF_KEY, "host")).toLatin1();
    QByteArray baServerType = m_pConfig->getValueString(
        ConfigKey(SHOUTCAST_PREF_KEY, "servertype")).toLatin1();
    QByteArray baPort = m_pConfig->getValueString(
        ConfigKey(SHOUTCAST_PREF_KEY, "port")).toLatin1();
    QByteArray baMountPoint = m_pConfig->getValueString(
        ConfigKey(SHOUTCAST_PREF_KEY, "mountpoint")).toLatin1();
    QByteArray baLogin = m_pConfig->getValueString(
        ConfigKey(SHOUTCAST_PREF_KEY, "login")).toLatin1();
    QByteArray baPassword = m_pConfig->getValueString(
        ConfigKey(SHOUTCAST_PREF_KEY, "password")).toLatin1();
    QByteArray baFormat = m_pConfig->getValueString(
        ConfigKey(SHOUTCAST_PREF_KEY, "format")).toLatin1();
    QByteArray baBitrate = m_pConfig->getValueString(
        ConfigKey(SHOUTCAST_PREF_KEY, "bitrate")).toLatin1();

    // Encode metadata like stream name, website, desc, genre, title/author with
    // the chosen TextCodec.
    QByteArray baStreamName = encodeString(m_pConfig->getValueString(
        ConfigKey(SHOUTCAST_PREF_KEY, "stream_name")));
    QByteArray baStreamWebsite = encodeString(m_pConfig->getValueString(
        ConfigKey(SHOUTCAST_PREF_KEY, "stream_website")));
    QByteArray baStreamDesc = encodeString(m_pConfig->getValueString(
        ConfigKey(SHOUTCAST_PREF_KEY, "stream_desc")));
    QByteArray baStreamGenre = encodeString(m_pConfig->getValueString(
        ConfigKey(SHOUTCAST_PREF_KEY, "stream_genre")));
    QByteArray baStreamPublic = encodeString(m_pConfig->getValueString(
        ConfigKey(SHOUTCAST_PREF_KEY, "stream_public")));

    // Dynamic Ogg metadata update
    m_ogg_dynamic_update = (bool)m_pConfig->getValueString(ConfigKey(SHOUTCAST_PREF_KEY,"ogg_dynamicupdate")).toInt();

    m_custom_metadata = (bool)m_pConfig->getValueString(
        ConfigKey(SHOUTCAST_PREF_KEY, "enable_metadata")).toInt();
    QString title = m_pConfig->getValueString(
        ConfigKey(SHOUTCAST_PREF_KEY, "custom_title"));
    QString artist = m_pConfig->getValueString(
        ConfigKey(SHOUTCAST_PREF_KEY, "custom_artist"));
    m_baCustomSong = encodeString(artist.isEmpty() ? title : artist + " - " + title);

    int format;
    int protocol;

    if (shout_set_host(m_pShout, baHost.constData()) != SHOUTERR_SUCCESS) {
        errorDialog(tr("Error setting hostname!"), shout_get_error(m_pShout));
        return;
    }

    // WTF? Why SHOUT_PROTOCOL_HTTP and not.. the chosen protocol?
    if (shout_set_protocol(m_pShout, SHOUT_PROTOCOL_HTTP) != SHOUTERR_SUCCESS) {
        errorDialog(tr("Error setting protocol!"), shout_get_error(m_pShout));
        return;
    }

    if (shout_set_port(m_pShout, baPort.toUInt()) != SHOUTERR_SUCCESS) {
        errorDialog(tr("Error setting port!"), shout_get_error(m_pShout));
        return;
    }

    if (shout_set_password(m_pShout, baPassword.constData()) != SHOUTERR_SUCCESS) {
        errorDialog(tr("Error setting password!"), shout_get_error(m_pShout));
        return;
    }

    if (shout_set_mount(m_pShout, baMountPoint.constData()) != SHOUTERR_SUCCESS) {
        errorDialog(tr("Error setting mount!"), shout_get_error(m_pShout));
        return;
    }


    if (shout_set_user(m_pShout, baLogin.constData()) != SHOUTERR_SUCCESS) {
        errorDialog(tr("Error setting username!"), shout_get_error(m_pShout));
        return;
    }

    if (shout_set_name(m_pShout, baStreamName.constData()) != SHOUTERR_SUCCESS) {
        errorDialog(tr("Error setting stream name!"), shout_get_error(m_pShout));
        return;
    }

    if (shout_set_description(m_pShout, baStreamDesc.constData()) != SHOUTERR_SUCCESS) {
        errorDialog(tr("Error setting stream description!"), shout_get_error(m_pShout));
        return;
    }

    if (shout_set_genre(m_pShout, baStreamGenre.constData()) != SHOUTERR_SUCCESS) {
        errorDialog(tr("Error setting stream genre!"), shout_get_error(m_pShout));
        return;
    }

    if (shout_set_url(m_pShout, baStreamWebsite.constData()) != SHOUTERR_SUCCESS) {
        errorDialog(tr("Error setting stream url!"), shout_get_error(m_pShout));
        return;
    }

    m_format_is_mp3 = !qstrcmp(baFormat.constData(), SHOUTCAST_FORMAT_MP3);
    m_format_is_ov = !qstrcmp(baFormat.constData(), SHOUTCAST_FORMAT_OV);
    if (m_format_is_mp3) {
        format = SHOUT_FORMAT_MP3;
    } else if (m_format_is_ov) {
        format = SHOUT_FORMAT_OGG;
    } else {
        qDebug() << "Error: unknown format:" << baFormat.constData();
        return;
    }

    if (shout_set_format(m_pShout, format) != SHOUTERR_SUCCESS) {
        errorDialog("Error setting soutcast format!", shout_get_error(m_pShout));
        return;
    }

    bool bitrate_is_int = false;
    int iBitrate = baBitrate.toInt(&bitrate_is_int);

    if (!bitrate_is_int) {
        qDebug() << "Error: unknown bitrate:" << baBitrate.constData();
    }

    int iMasterSamplerate = m_pMasterSamplerate->get();
    if (m_format_is_ov && iMasterSamplerate == 96000) {
        errorDialog(tr("Broadcasting at 96kHz with Ogg Vorbis is not currently "
                       "supported. Please try a different sample-rate or switch "
                       "to a different encoding."),
                    tr("See https://bugs.launchpad.net/mixxx/+bug/686212 for more "
                       "information."));
        return;
    }

    if (shout_set_audio_info(m_pShout, SHOUT_AI_BITRATE, baBitrate.constData()) != SHOUTERR_SUCCESS) {
        errorDialog(tr("Error setting bitrate"), shout_get_error(m_pShout));
        return;
    }

    m_protocol_is_icecast2 = !qstricmp(baServerType.constData(), SHOUTCAST_SERVER_ICECAST2);
    m_protocol_is_shoutcast = !qstricmp(baServerType.constData(), SHOUTCAST_SERVER_SHOUTCAST);
    m_protocol_is_icecast1 = !qstricmp(baServerType.constData(), SHOUTCAST_SERVER_ICECAST1);


    if (m_protocol_is_icecast2) {
        protocol = SHOUT_PROTOCOL_HTTP;
    } else if (m_protocol_is_shoutcast) {
        protocol = SHOUT_PROTOCOL_ICY;
    } else if (m_protocol_is_icecast1) {
        protocol = SHOUT_PROTOCOL_XAUDIOCAST;
    } else {
        errorDialog(tr("Error: unknown server protocol!"), shout_get_error(m_pShout));
        return;
    }

    if (m_protocol_is_shoutcast && !m_format_is_mp3) {
        errorDialog(tr("Error: libshout only supports Shoutcast with MP3 format!"),
                    shout_get_error(m_pShout));
        return;
    }

    if (shout_set_protocol(m_pShout, protocol) != SHOUTERR_SUCCESS) {
        errorDialog(tr("Error setting protocol!"), shout_get_error(m_pShout));
        return;
    }

    // Initialize m_encoder
    if (m_encoder) {
        // delete m_encoder if it has been initalized (with maybe) different bitrate
        delete m_encoder;
        m_encoder = NULL;
    }

    if (m_format_is_mp3) {
        m_encoder = new EncoderMp3(this);
    } else if (m_format_is_ov) {
        m_encoder = new EncoderVorbis(this);
    } else {
        qDebug() << "**** Unknown Encoder Format";
        return;
    }

    if (m_encoder->initEncoder(iBitrate, iMasterSamplerate) < 0) {
        //e.g., if lame is not found
        //init m_encoder itself will display a message box
        qDebug() << "**** Encoder init failed";
        delete m_encoder;
        m_encoder = NULL;
    }
}
Example #11
0
	// return true if jsonp applied
	bool tryApplyJsonp(const DomainMap::JsonpConfig &config, bool *ok, QString *errorMessage)
	{
		*ok = true;

		// must be a GET
		if(requestData.method != "GET")
			return false;

		QString callbackParam = QString::fromUtf8(config.callbackParam);
		if(callbackParam.isEmpty())
			callbackParam = "callback";

		QString bodyParam;
		if(!config.bodyParam.isEmpty())
			bodyParam = QString::fromUtf8(config.bodyParam);

		QUrl uri = requestData.uri;
		QUrlQuery query(uri);

		// two ways to activate JSON-P:
		//   1) callback param present
		//   2) default callback specified in configuration and body param present
		if(!query.hasQueryItem(callbackParam) &&
			(config.defaultCallback.isEmpty() || bodyParam.isEmpty() || !query.hasQueryItem(bodyParam)))
		{
			return false;
		}

		QByteArray callback;
		if(query.hasQueryItem(callbackParam))
		{
			callback = parsePercentEncoding(query.queryItemValue(callbackParam, QUrl::FullyEncoded).toUtf8());
			if(callback.isEmpty())
			{
				log_debug("requestsession: id=%s invalid callback parameter, rejecting", rid.second.data());
				*ok = false;
				*errorMessage = "Invalid callback parameter.";
				return false;
			}

			query.removeAllQueryItems(callbackParam);
		}
		else
			callback = config.defaultCallback;

		QString method;
		if(query.hasQueryItem("_method"))
		{
			method = QString::fromLatin1(parsePercentEncoding(query.queryItemValue("_method", QUrl::FullyEncoded).toUtf8()));
			if(!validMethod(method))
			{
				log_debug("requestsession: id=%s invalid _method parameter, rejecting", rid.second.data());
				*ok = false;
				*errorMessage = "Invalid _method parameter.";
				return false;
			}

			query.removeAllQueryItems("_method");
		}

		HttpHeaders headers;
		if(query.hasQueryItem("_headers"))
		{
			QJsonParseError e;
			QJsonDocument doc = QJsonDocument::fromJson(parsePercentEncoding(query.queryItemValue("_headers", QUrl::FullyEncoded).toUtf8()), &e);
			if(e.error != QJsonParseError::NoError || !doc.isObject())
			{
				log_debug("requestsession: id=%s invalid _headers parameter, rejecting", rid.second.data());
				*ok = false;
				*errorMessage = "Invalid _headers parameter.";
				return false;
			}

			QVariantMap headersMap = doc.object().toVariantMap();

			QMapIterator<QString, QVariant> vit(headersMap);
			while(vit.hasNext())
			{
				vit.next();

				if(vit.value().type() != QVariant::String)
				{
					log_debug("requestsession: id=%s invalid _headers parameter, rejecting", rid.second.data());
					*ok = false;
					*errorMessage = "Invalid _headers parameter.";
					return false;
				}

				QByteArray key = vit.key().toUtf8();

				// ignore some headers that we explicitly set later on
				if(qstricmp(key.data(), "host") == 0)
					continue;
				if(qstricmp(key.data(), "accept") == 0)
					continue;

				headers += HttpHeader(key, vit.value().toString().toUtf8());
			}

			query.removeAllQueryItems("_headers");
		}

		QByteArray body;
		if(!bodyParam.isEmpty())
		{
			if(query.hasQueryItem(bodyParam))
			{
				body = parsePercentEncoding(query.queryItemValue(bodyParam, QUrl::FullyEncoded).toUtf8());
				if(body.isNull())
				{
					log_debug("requestsession: id=%s invalid body parameter, rejecting", rid.second.data());
					*ok = false;
					*errorMessage = "Invalid body parameter.";
					return false;
				}

				headers.removeAll("Content-Type");
				headers += HttpHeader("Content-Type", "application/json");

				query.removeAllQueryItems(bodyParam);
			}
		}
		else
		{
			if(query.hasQueryItem("_body"))
			{
				body = parsePercentEncoding(query.queryItemValue("_body").toUtf8());
				if(body.isNull())
				{
					log_debug("requestsession: id=%s invalid _body parameter, rejecting", rid.second.data());
					*ok = false;
					*errorMessage = "Invalid _body parameter.";
					return false;
				}

				query.removeAllQueryItems("_body");
			}
		}

		uri.setQuery(query);

		// if we have no query items anymore, strip the '?'
		if(query.isEmpty())
		{
			QByteArray tmp = uri.toEncoded();
			if(tmp.length() > 0 && tmp[tmp.length() - 1] == '?')
			{
				tmp.truncate(tmp.length() - 1);
				uri = QUrl::fromEncoded(tmp, QUrl::StrictMode);
			}
		}

		if(method.isEmpty())
			method = config.defaultMethod;

		requestData.method = method;

		requestData.uri = uri;

		headers += HttpHeader("Host", uri.host().toUtf8());
		headers += HttpHeader("Accept", "*/*");

		// carry over the rest of the headers
		foreach(const HttpHeader &h, requestData.headers)
		{
			if(qstricmp(h.first.data(), "host") == 0)
				continue;
			if(qstricmp(h.first.data(), "accept") == 0)
				continue;

			headers += h;
		}

		requestData.headers = headers;
		in += body;

		jsonpCallback = callback;
		jsonpExtendedResponse = (config.mode == DomainMap::JsonpConfig::Extended);

		return true;
	}
Example #12
0
result_t JsonRpcHandler::invoke(object_base *v, obj_ptr<Handler_base> &retVal,
                                AsyncEvent *ac)
{
    if (ac)
        return CHECK_ERROR(CALL_E_NOASYNC);

    obj_ptr<Message_base> msg = Message_base::getInstance(v);
    if (msg == NULL)
        return CHECK_ERROR(CALL_E_BADVARTYPE);

    Isolate* isolate = holder();
    obj_ptr<HttpRequest_base> htreq = HttpRequest_base::getInstance(v);
    obj_ptr<SeekableStream_base> body;
    obj_ptr<Buffer_base> buf;
    v8::Local<v8::Value> jsval;
    v8::Local<v8::Object> o;
    Variant result;
    exlib::string str;
    int64_t len;
    int32_t sz, i;
    result_t hr;
    obj_ptr<List_base> params;

    if (htreq != NULL)
    {
        if (htreq->firstHeader("Content-Type", result) == CALL_RETURN_NULL)
            return CHECK_ERROR(Runtime::setError("jsonrpc: Content-Type is missing."));

        str = result.string();
        if (qstricmp(str.c_str(), "application/json", 16))
            return CHECK_ERROR(Runtime::setError("jsonrpc: Invalid Content-Type."));
    }

    msg->get_body(body);

    body->size(len);
    sz = (int32_t) len;

    body->rewind();
    hr = body->ac_read(sz, buf);
    if (hr < 0)
        return hr;
    if (hr == CALL_RETURN_NULL)
        return CHECK_ERROR(Runtime::setError("jsonrpc: request body is empty."));
    body.Release();

    buf->toString(str);
    buf.Release();

    hr = json_base::decode(str, jsval);
    if (hr < 0)
        return hr;

    if (!jsval->IsObject())
        return CHECK_ERROR(Runtime::setError("jsonrpc: Invalid rpc request."));

    o = v8::Local<v8::Object>::Cast(jsval);

    jsval = o->Get(isolate->NewFromUtf8("method", 6));
    if (IsEmpty(jsval))
        return CHECK_ERROR(Runtime::setError("jsonrpc: method is missing."));

    msg->get_value(str);
    str += '/';
    str.append(*v8::String::Utf8Value(jsval));
    msg->set_value(str);

    jsval = o->Get(isolate->NewFromUtf8("params", 6));
    if (!jsval.IsEmpty() && jsval->IsArray())
    {
        v8::Local<v8::Array> jsparams = v8::Local<v8::Array>::Cast(jsval);

        sz = jsparams->Length();
        msg->get_params(params);
        params->resize(sz);

        for (i = 0; i < sz; i++)
            params->_indexed_setter(i, jsparams->Get(i));
    }

    obj_ptr<Handler_base> hdlr1;
    hr = JSHandler::js_invoke(m_handler, v, hdlr1, NULL);
    if (hr >= 0 && hr != CALL_RETURN_NULL)
        hr = mq_base::ac_invoke(hdlr1, v);

    v8::Local<v8::String> strId = isolate->NewFromUtf8("id", 2);
    jsval = o->Get(strId);

    o = v8::Object::New(isolate->m_isolate);
    o->Set(strId, jsval);

    if (hr < 0)
    {
        errorLog("JsonRpcHandler: " + getResultMessage(hr));

        result_t hr1 = json_base::encode(o, str);
        if (hr1 < 0)
            return hr1;

        if (str.length() <= 2)
            str.assign("{", 1);
        else
        {
            str.resize(str.length() - 1);
            str += ',';
        }

        if (hr == CALL_E_INVALID_CALL)
            str.append(
                "\"error\": {\"code\": -32601, \"message\": \"Method not found.\"}}");
        else
            str.append(
                "\"error\": {\"code\": -32603, \"message\": \"Internal error.\"}}");
    }
    else
    {
        msg->get_result(result);
        o->Set(isolate->NewFromUtf8("result", 6), result);

        hr = json_base::encode(o, str);

        if (hr < 0)
            return hr;
    }

    body = new MemoryStream();

    buf = new Buffer(str);
    hr = body->ac_write(buf);
    if (hr < 0)
        return hr;


    obj_ptr<Message_base> rep;
    hr = msg->get_response(rep);
    if (hr < 0)
        return hr;

    rep->set_body(body);

    if (htreq)
        ((HttpMessage_base *)(Message_base *)rep)->setHeader(
            "Content-Type", "application/json");

    return CALL_RETURN_NULL;
}