PlatformPlugin *FactoryPrivate::platformPlugin()
{
    if (m_platformPlugin) {
        return m_platformPlugin;
    }
    if (m_noPlatformPlugin) {
        return 0;
    }
#ifndef QT_NO_DBUS
    if (!QCoreApplication::instance() || QCoreApplication::applicationName().isEmpty()) {
        pWarning() << "Phonon needs QCoreApplication::applicationName to be set to export audio output names through the DBUS interface";
    }
#endif
    Q_ASSERT(QCoreApplication::instance());
    const QByteArray platform_plugin_env = qgetenv("PHONON_PLATFORMPLUGIN");
    if (!platform_plugin_env.isEmpty()) {
        QPluginLoader pluginLoader(QString::fromLocal8Bit(platform_plugin_env.constData()));
        if (pluginLoader.load()) {
            m_platformPlugin = qobject_cast<PlatformPlugin *>(pluginLoader.instance());
            if (m_platformPlugin) {
                return m_platformPlugin;
            }
        }
    }
    const QString suffix(QLatin1String("/phonon_platform/"));
    ensureLibraryPathSet();
    QDir dir;
    dir.setNameFilters(
            !qgetenv("KDE_FULL_SESSION").isEmpty() ? QStringList(QLatin1String("kde.*")) :
            (!qgetenv("GNOME_DESKTOP_SESSION_ID").isEmpty() ? QStringList(QLatin1String("gnome.*")) :
             QStringList())
            );
    dir.setFilter(QDir::Files);
    const QStringList libPaths = QCoreApplication::libraryPaths();
    forever {
        for (int i = 0; i < libPaths.count(); ++i) {
            const QString libPath = libPaths.at(i) + suffix;
            dir.setPath(libPath);
            if (!dir.exists()) {
                continue;
            }
            const QStringList files = dir.entryList(QDir::Files);
            for (int i = 0; i < files.count(); ++i) {
                QPluginLoader pluginLoader(libPath + files.at(i));
                if (!pluginLoader.load()) {
                    pDebug() << Q_FUNC_INFO << "  platform plugin load failed:"
                        << pluginLoader.errorString();
                    continue;
                }
                pDebug() << pluginLoader.instance();
                QObject *qobj = pluginLoader.instance();
                m_platformPlugin = qobject_cast<PlatformPlugin *>(qobj);
                pDebug() << m_platformPlugin;
                if (m_platformPlugin) {
                    connect(qobj, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)),
                            SLOT(objectDescriptionChanged(ObjectDescriptionType)));
                    return m_platformPlugin;
                } else {
                    delete qobj;
                    pDebug() << Q_FUNC_INFO << dir.absolutePath() << "exists but the platform plugin was not loadable:" << pluginLoader.errorString();
                    pluginLoader.unload();
                }
            }
        }
        if (dir.nameFilters().isEmpty()) {
            break;
        }
        dir.setNameFilters(QStringList());
    }
    pDebug() << Q_FUNC_INFO << "platform plugin could not be loaded";
    m_noPlatformPlugin = true;
    return 0;
}
QStringList QBasicFontDatabase::addTTFile(const QByteArray &fontData, const QByteArray &file, QSupportedWritingSystems *supportedWritingSystems)
{
    FT_Library library = qt_getFreetype();

    int index = 0;
    int numFaces = 0;
    QStringList families;
    do {
        FT_Face face;
        FT_Error error;
        if (!fontData.isEmpty()) {
            error = FT_New_Memory_Face(library, (const FT_Byte *)fontData.constData(), fontData.size(), index, &face);
        } else {
            error = FT_New_Face(library, file.constData(), index, &face);
        }
        if (error != FT_Err_Ok) {
            qDebug() << "FT_New_Face failed with index" << index << ":" << hex << error;
            break;
        }
        numFaces = face->num_faces;

        QFont::Weight weight = QFont::Normal;

        QFont::Style style = QFont::StyleNormal;
        if (face->style_flags & FT_STYLE_FLAG_ITALIC)
            style = QFont::StyleItalic;

        if (face->style_flags & FT_STYLE_FLAG_BOLD)
            weight = QFont::Bold;

        bool fixedPitch = (face->face_flags & FT_FACE_FLAG_FIXED_WIDTH);

        QSupportedWritingSystems writingSystems;
        // detect symbol fonts
        for (int i = 0; i < face->num_charmaps; ++i) {
            FT_CharMap cm = face->charmaps[i];
            if (cm->encoding == FT_ENCODING_ADOBE_CUSTOM
                    || cm->encoding == FT_ENCODING_MS_SYMBOL) {
                writingSystems.setSupported(QFontDatabase::Symbol);
                if (supportedWritingSystems)
                    supportedWritingSystems->setSupported(QFontDatabase::Symbol);
                break;
            }
        }

        TT_OS2 *os2 = (TT_OS2 *)FT_Get_Sfnt_Table(face, ft_sfnt_os2);
        if (os2) {
            quint32 unicodeRange[4] = {
                quint32(os2->ulUnicodeRange1),
                quint32(os2->ulUnicodeRange2),
                quint32(os2->ulUnicodeRange3),
                quint32(os2->ulUnicodeRange4)
            };
            quint32 codePageRange[2] = {
                quint32(os2->ulCodePageRange1),
                quint32(os2->ulCodePageRange2)
            };

            writingSystems = QPlatformFontDatabase::writingSystemsFromTrueTypeBits(unicodeRange, codePageRange);
            if (supportedWritingSystems)
                *supportedWritingSystems = writingSystems;

            if (os2->usWeightClass == 0)
                ;
            else if (os2->usWeightClass < 350)
                weight = QFont::Light;
            else if (os2->usWeightClass < 450)
                weight = QFont::Normal;
            else if (os2->usWeightClass < 650)
                weight = QFont::DemiBold;
            else if (os2->usWeightClass < 750)
                weight = QFont::Bold;
            else if (os2->usWeightClass < 1000)
                weight = QFont::Black;

            if (os2->panose[2] >= 2) {
                int w = os2->panose[2];
                if (w <= 3)
                    weight = QFont::Light;
                else if (w <= 5)
                    weight = QFont::Normal;
                else if (w <= 7)
                    weight = QFont::DemiBold;
                else if (w <= 8)
                    weight = QFont::Bold;
                else if (w <= 10)
                    weight = QFont::Black;
            }
        }

        QString family = QString::fromLatin1(face->family_name);
        FontFile *fontFile = new FontFile;
        fontFile->fileName = QFile::decodeName(file);
        fontFile->indexValue = index;

        QFont::Stretch stretch = QFont::Unstretched;

        registerFont(family,QString::fromLatin1(face->style_name),QString(),weight,style,stretch,true,true,0,fixedPitch,writingSystems,fontFile);

        families.append(family);

        FT_Done_Face(face);
        ++index;
    } while (index < numFaces);
    return families;
}
Esempio n. 3
0
QHostInfo QHostInfoAgent::fromName(const QString &hostName)
{
    QHostInfo results;

#if defined(QHOSTINFO_DEBUG)
    qDebug("QHostInfoAgent::fromName(%s) looking up...",
           hostName.toLatin1().constData());
#endif

    // Load res_init on demand.
    static volatile bool triedResolve = false;
    if (!triedResolve) {
        QMutexLocker locker(QMutexPool::globalInstanceGet(&local_res_init));
        if (!triedResolve) {
            resolveLibrary();
            triedResolve = true;
        }
    }

    // If res_init is available, poll it.
    if (local_res_init)
        local_res_init();

    QHostAddress address;
    if (address.setAddress(hostName)) {
        // Reverse lookup
// Reverse lookups using getnameinfo are broken on darwin, use gethostbyaddr instead.
#if !defined (QT_NO_GETADDRINFO) && !defined (Q_OS_DARWIN)
        sockaddr_in sa4;
#ifndef QT_NO_IPV6
        sockaddr_in6 sa6;
#endif
        sockaddr *sa = 0;
        QT_SOCKLEN_T saSize = 0;
        if (address.protocol() == QAbstractSocket::IPv4Protocol) {
            sa = (sockaddr *)&sa4;
            saSize = sizeof(sa4);
            memset(&sa4, 0, sizeof(sa4));
            sa4.sin_family = AF_INET;
            sa4.sin_addr.s_addr = htonl(address.toIPv4Address());
        }
#ifndef QT_NO_IPV6
        else {
            sa = (sockaddr *)&sa6;
            saSize = sizeof(sa6);
            memset(&sa6, 0, sizeof(sa6));
            sa6.sin6_family = AF_INET6;
            memcpy(sa6.sin6_addr.s6_addr, address.toIPv6Address().c, sizeof(sa6.sin6_addr.s6_addr));
        }
#endif

        char hbuf[NI_MAXHOST];
        if (sa && getnameinfo(sa, saSize, hbuf, sizeof(hbuf), 0, 0, 0) == 0)
            results.setHostName(QString::fromLatin1(hbuf));
#else
        in_addr_t inetaddr = qt_safe_inet_addr(hostName.toLatin1().constData());
        struct hostent *ent = gethostbyaddr((const char *)&inetaddr, sizeof(inetaddr), AF_INET);
        if (ent)
            results.setHostName(QString::fromLatin1(ent->h_name));
#endif

        if (results.hostName().isEmpty())
            results.setHostName(address.toString());
        results.setAddresses(QList<QHostAddress>() << address);
        return results;
    }

    // IDN support
    QByteArray aceHostname = QUrl::toAce(hostName);
    results.setHostName(hostName);
    if (aceHostname.isEmpty()) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(hostName.isEmpty() ?
                               QCoreApplication::translate("QHostInfoAgent", "No host name given") :
                               QCoreApplication::translate("QHostInfoAgent", "Invalid hostname"));
        return results;
    }

#if !defined (QT_NO_GETADDRINFO)
    // Call getaddrinfo, and place all IPv4 addresses at the start and
    // the IPv6 addresses at the end of the address list in results.
    addrinfo *res = 0;
    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = PF_UNSPEC;
#ifdef Q_ADDRCONFIG
    hints.ai_flags = Q_ADDRCONFIG;
#endif

    int result = getaddrinfo(aceHostname.constData(), 0, &hints, &res);
# ifdef Q_ADDRCONFIG
    if (result == EAI_BADFLAGS) {
        // if the lookup failed with AI_ADDRCONFIG set, try again without it
        hints.ai_flags = 0;
        result = getaddrinfo(aceHostname.constData(), 0, &hints, &res);
    }
# endif

    if (result == 0) {
        addrinfo *node = res;
        QList<QHostAddress> addresses;
        while (node) {
#ifdef QHOSTINFO_DEBUG
                qDebug() << "getaddrinfo node: flags:" << node->ai_flags << "family:" << node->ai_family << "ai_socktype:" << node->ai_socktype << "ai_protocol:" << node->ai_protocol << "ai_addrlen:" << node->ai_addrlen;
#endif
            if (node->ai_family == AF_INET) {
                QHostAddress addr;
                addr.setAddress(ntohl(((sockaddr_in *) node->ai_addr)->sin_addr.s_addr));
                if (!addresses.contains(addr))
                    addresses.append(addr);
            }
#ifndef QT_NO_IPV6
            else if (node->ai_family == AF_INET6) {
                QHostAddress addr;
                sockaddr_in6 *sa6 = (sockaddr_in6 *) node->ai_addr;
                addr.setAddress(sa6->sin6_addr.s6_addr);
                if (sa6->sin6_scope_id)
                    addr.setScopeId(QString::number(sa6->sin6_scope_id));
                if (!addresses.contains(addr))
                    addresses.append(addr);
            }
#endif
            node = node->ai_next;
        }
        if (addresses.isEmpty() && node == 0) {
            // Reached the end of the list, but no addresses were found; this
            // means the list contains one or more unknown address types.
            results.setError(QHostInfo::UnknownError);
            results.setErrorString(tr("Unknown address type"));
        }

        results.setAddresses(addresses);
        freeaddrinfo(res);
    } else if (result == EAI_NONAME
               || result ==  EAI_FAIL
#ifdef EAI_NODATA
	       // EAI_NODATA is deprecated in RFC 3493
	       || result == EAI_NODATA
#endif
	       ) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(tr("Host not found"));
    } else {
        results.setError(QHostInfo::UnknownError);
        results.setErrorString(QString::fromLocal8Bit(gai_strerror(result)));
    }

#else
    // Fall back to gethostbyname for platforms that don't define
    // getaddrinfo. gethostbyname does not support IPv6, and it's not
    // reentrant on all platforms. For now this is okay since we only
    // use one QHostInfoAgent, but if more agents are introduced, locking
    // must be provided.
    QMutexLocker locker(::getHostByNameMutex());
    hostent *result = gethostbyname(aceHostname.constData());
    if (result) {
        if (result->h_addrtype == AF_INET) {
            QList<QHostAddress> addresses;
            for (char **p = result->h_addr_list; *p != 0; p++) {
                QHostAddress addr;
                addr.setAddress(ntohl(*((quint32 *)*p)));
                if (!addresses.contains(addr))
                    addresses.prepend(addr);
            }
            results.setAddresses(addresses);
        } else {
            results.setError(QHostInfo::UnknownError);
            results.setErrorString(tr("Unknown address type"));
        }
#if !defined(Q_OS_VXWORKS)
    } else if (h_errno == HOST_NOT_FOUND || h_errno == NO_DATA
               || h_errno == NO_ADDRESS) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(tr("Host not found"));
#endif
    } else {
        results.setError(QHostInfo::UnknownError);
        results.setErrorString(tr("Unknown error"));
    }
#endif //  !defined (QT_NO_GETADDRINFO)

#if defined(QHOSTINFO_DEBUG)
    if (results.error() != QHostInfo::NoError) {
        qDebug("QHostInfoAgent::fromName(): error #%d %s",
               h_errno, results.errorString().toLatin1().constData());
    } else {
        QString tmp;
        QList<QHostAddress> addresses = results.addresses();
        for (int i = 0; i < addresses.count(); ++i) {
            if (i != 0) tmp += ", ";
            tmp += addresses.at(i).toString();
        }
        qDebug("QHostInfoAgent::fromName(): found %i entries for \"%s\": {%s}",
               addresses.count(), hostName.toLatin1().constData(),
               tmp.toLatin1().constData());
    }
#endif
    return results;
}
Esempio n. 4
0
QStringList QBasicUnixFontDatabase::addTTFile(const QByteArray &fontData, const QByteArray &file)
{
    extern FT_Library qt_getFreetype();
    FT_Library library = qt_getFreetype();

    int index = 0;
    int numFaces = 0;
    QStringList families;
    do {
        FT_Face face;
        FT_Error error;
        if (!fontData.isEmpty()) {
            error = FT_New_Memory_Face(library, (const FT_Byte *)fontData.constData(), fontData.size(), index, &face);
        } else {
            error = FT_New_Face(library, file.constData(), index, &face);
        }
        if (error != FT_Err_Ok) {
            qDebug() << "FT_New_Face failed with index" << index << ":" << hex << error;
            break;
        }
        numFaces = face->num_faces;

        QFont::Weight weight = QFont::Normal;

        QFont::Style style = QFont::StyleNormal;
        if (face->style_flags & FT_STYLE_FLAG_ITALIC)
            style = QFont::StyleItalic;

        if (face->style_flags & FT_STYLE_FLAG_BOLD)
            weight = QFont::Bold;

        QSupportedWritingSystems writingSystems;
        // detect symbol fonts
        for (int i = 0; i < face->num_charmaps; ++i) {
            FT_CharMap cm = face->charmaps[i];
            if (cm->encoding == ft_encoding_adobe_custom
                    || cm->encoding == ft_encoding_symbol) {
                writingSystems.setSupported(QFontDatabase::Symbol);
                break;
            }
        }

        TT_OS2 *os2 = (TT_OS2 *)FT_Get_Sfnt_Table(face, ft_sfnt_os2);
        if (os2) {
            quint32 unicodeRange[4] = {
                quint32(os2->ulUnicodeRange1), quint32(os2->ulUnicodeRange2),
                quint32(os2->ulUnicodeRange3), quint32(os2->ulUnicodeRange4)
                    };
            quint32 codePageRange[2] = {
                quint32(os2->ulCodePageRange1), quint32(os2->ulCodePageRange2)
                    };

            writingSystems = determineWritingSystemsFromTrueTypeBits(unicodeRange, codePageRange);
        }

        QString family = QString::fromAscii(face->family_name);
        FontFile *fontFile = new FontFile;
        fontFile->fileName = file;
        fontFile->indexValue = index;

        QFont::Stretch stretch = QFont::Unstretched;

        registerFont(family,"",weight,style,stretch,true,true,0,writingSystems,fontFile);

        families.append(family);

        FT_Done_Face(face);
        ++index;
    } while (index < numFaces);
    return families;
}
Esempio n. 5
0
QList<QNetworkProxy> macQueryInternal(const QNetworkProxyQuery &query)
{
    QList<QNetworkProxy> result;

    // obtain a dictionary to the proxy settings:
    CFDictionaryRef dict = SCDynamicStoreCopyProxies(NULL);
    if (!dict) {
        qWarning("QNetworkProxyFactory::systemProxyForQuery: SCDynamicStoreCopyProxies returned NULL");
        return result;          // failed
    }

    if (isHostExcluded(dict, query.peerHostName())) {
        CFRelease(dict);
        return result;          // no proxy for this host
    }

    // is there a PAC enabled? If so, use it first.
    CFNumberRef pacEnabled;
    if ((pacEnabled = (CFNumberRef)CFDictionaryGetValue(dict, kSCPropNetProxiesProxyAutoConfigEnable))) {
        int enabled;
        if (CFNumberGetValue(pacEnabled, kCFNumberIntType, &enabled) && enabled) {
            // PAC is enabled
            CFStringRef cfPacLocation = (CFStringRef)CFDictionaryGetValue(dict, kSCPropNetProxiesProxyAutoConfigURLString);

            if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
                QCFType<CFDataRef> pacData;
                QCFType<CFURLRef> pacUrl = CFURLCreateWithString(kCFAllocatorDefault, cfPacLocation, NULL);
                SInt32 errorCode;
                if (!CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault, pacUrl, &pacData, NULL, NULL, &errorCode)) {
                    QString pacLocation = QCFString::toQString(cfPacLocation);
                    qWarning("Unable to get the PAC script at \"%s\" (%s)", qPrintable(pacLocation), cfurlErrorDescription(errorCode));
                    return result;
                }

                QCFType<CFStringRef> pacScript = CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, pacData, kCFStringEncodingISOLatin1);
                if (!pacScript) {
                    // This should never happen, but the documentation says it may return NULL if there was a problem creating the object.
                    QString pacLocation = QCFString::toQString(cfPacLocation);
                    qWarning("Unable to read the PAC script at \"%s\"", qPrintable(pacLocation));
                    return result;
                }

                QByteArray encodedURL = query.url().toEncoded(); // converted to UTF-8
                if (encodedURL.isEmpty()) {
                    return result; // Invalid URL, abort
                }

                QCFType<CFURLRef> targetURL = CFURLCreateWithBytes(kCFAllocatorDefault, (UInt8*)encodedURL.data(), encodedURL.size(), kCFStringEncodingUTF8, NULL);
                if (!targetURL) {
                    return result; // URL creation problem, abort
                }

                QCFType<CFErrorRef> pacError;
                QCFType<CFArrayRef> proxies = CFNetworkCopyProxiesForAutoConfigurationScript(pacScript, targetURL, &pacError);
                if (!proxies) {
                    QString pacLocation = QCFString::toQString(cfPacLocation);
                    QCFType<CFStringRef> pacErrorDescription = CFErrorCopyDescription(pacError);
                    qWarning("Execution of PAC script at \"%s\" failed: %s", qPrintable(pacLocation), qPrintable(QCFString::toQString(pacErrorDescription)));
                    return result;
                }

                CFIndex size = CFArrayGetCount(proxies);
                for (CFIndex i = 0; i < size; ++i) {
                    CFDictionaryRef proxy = (CFDictionaryRef)CFArrayGetValueAtIndex(proxies, i);
                    result << proxyFromDictionary(proxy);
                }
                return result;
            } else {
                QString pacLocation = QCFString::toQString(cfPacLocation);
                qWarning("Mac system proxy: PAC script at \"%s\" not handled", qPrintable(pacLocation));
            }
        }
    }

    // no PAC, decide which proxy we're looking for based on the query
    bool isHttps = false;
    QString protocol = query.protocolTag().toLower();

    // try the protocol-specific proxy
    QNetworkProxy protocolSpecificProxy;
    if (protocol == QLatin1String("ftp")) {
        protocolSpecificProxy =
            proxyFromDictionary(dict, QNetworkProxy::FtpCachingProxy,
                                kSCPropNetProxiesFTPEnable,
                                kSCPropNetProxiesFTPProxy,
                                kSCPropNetProxiesFTPPort);
    } else if (protocol == QLatin1String("http")) {
        protocolSpecificProxy =
            proxyFromDictionary(dict, QNetworkProxy::HttpProxy,
                                kSCPropNetProxiesHTTPEnable,
                                kSCPropNetProxiesHTTPProxy,
                                kSCPropNetProxiesHTTPPort);
    } else if (protocol == QLatin1String("https")) {
        isHttps = true;
        protocolSpecificProxy =
            proxyFromDictionary(dict, QNetworkProxy::HttpProxy,
                                kSCPropNetProxiesHTTPSEnable,
                                kSCPropNetProxiesHTTPSProxy,
                                kSCPropNetProxiesHTTPSPort);
    }
    if (protocolSpecificProxy.type() != QNetworkProxy::DefaultProxy)
        result << protocolSpecificProxy;

    // let's add SOCKSv5 if present too
    QNetworkProxy socks5 = proxyFromDictionary(dict, QNetworkProxy::Socks5Proxy,
                                               kSCPropNetProxiesSOCKSEnable,
                                               kSCPropNetProxiesSOCKSProxy,
                                               kSCPropNetProxiesSOCKSPort);
    if (socks5.type() != QNetworkProxy::DefaultProxy)
        result << socks5;

    // let's add the HTTPS proxy if present (and if we haven't added
    // yet)
    if (!isHttps) {
        QNetworkProxy https = proxyFromDictionary(dict, QNetworkProxy::HttpProxy,
                                                  kSCPropNetProxiesHTTPSEnable,
                                                  kSCPropNetProxiesHTTPSProxy,
                                                  kSCPropNetProxiesHTTPSPort);
        if (https.type() != QNetworkProxy::DefaultProxy && https != protocolSpecificProxy)
            result << https;
    }

    CFRelease(dict);
    return result;
}
Esempio n. 6
0
QHash<QByteArray, QByteArray> QAuthenticatorPrivate::parseDigestAuthenticationChallenge(const QByteArray &challenge)
{
    QHash<QByteArray, QByteArray> options;
    // parse the challenge
    const char *d = challenge.constData();
    const char *end = d + challenge.length();
    while (d < end) {
        while (d < end && (*d == ' ' || *d == '\n' || *d == '\r'))
            ++d;
        const char *start = d;
        while (d < end && *d != '=')
            ++d;
        QByteArray key = QByteArray(start, d - start);
        ++d;
        if (d >= end)
            break;
        bool quote = (*d == '"');
        if (quote)
            ++d;
        if (d >= end)
            break;
        start = d;
        QByteArray value;
        while (d < end) {
            bool backslash = false;
            if (*d == '\\' && d < end - 1) {
                ++d;
                backslash = true;
            }
            if (!backslash) {
                if (quote) {
                    if (*d == '"')
                        break;
                } else {
                    if (*d == ',')
                        break;
                }
            }
            value += *d;
            ++d;
        }
        while (d < end && *d != ',')
            ++d;
        ++d;
        options[key] = value;
    }

    QByteArray qop = options.value("qop");
    if (!qop.isEmpty()) {
        QList<QByteArray> qopoptions = qop.split(',');
        if (!qopoptions.contains("auth"))
            return QHash<QByteArray, QByteArray>();
        // #### can't do auth-int currently
//         if (qop.contains("auth-int"))
//             qop = "auth-int";
//         else if (qop.contains("auth"))
//             qop = "auth";
//         else
//             qop = QByteArray();
        options["qop"] = "auth";
    }

    return options;
}
bool QHttpNetworkConnectionChannel::ensureConnection()
{
    QAbstractSocket::SocketState socketState = socket->state();

    // resend this request after we receive the disconnected signal
    if (socketState == QAbstractSocket::ClosingState) {
        if (reply)
            resendCurrent = true;
        return false;
    }

    // already trying to connect?
    if (socketState == QAbstractSocket::HostLookupState ||
            socketState == QAbstractSocket::ConnectingState) {
        return false;
    }

    // make sure that this socket is in a connected state, if not initiate
    // connection to the host.
    if (socketState != QAbstractSocket::ConnectedState) {
        // connect to the host if not already connected.
        state = QHttpNetworkConnectionChannel::ConnectingState;
        pendingEncrypt = ssl;

        // reset state
        pipeliningSupported = PipeliningSupportUnknown;
        authenticationCredentialsSent = false;
        proxyCredentialsSent = false;
        authenticator.detach();
        QAuthenticatorPrivate *priv = QAuthenticatorPrivate::getPrivate(authenticator);
        priv->hasFailed = false;
        proxyAuthenticator.detach();
        priv = QAuthenticatorPrivate::getPrivate(proxyAuthenticator);
        priv->hasFailed = false;

        // This workaround is needed since we use QAuthenticator for NTLM authentication. The "phase == Done"
        // is the usual criteria for emitting authentication signals. The "phase" is set to "Done" when the
        // last header for Authorization is generated by the QAuthenticator. Basic & Digest logic does not
        // check the "phase" for generating the Authorization header. NTLM authentication is a two stage
        // process & needs the "phase". To make sure the QAuthenticator uses the current username/password
        // the phase is reset to Start.
        priv = QAuthenticatorPrivate::getPrivate(authenticator);
        if (priv && priv->phase == QAuthenticatorPrivate::Done)
            priv->phase = QAuthenticatorPrivate::Start;
        priv = QAuthenticatorPrivate::getPrivate(proxyAuthenticator);
        if (priv && priv->phase == QAuthenticatorPrivate::Done)
            priv->phase = QAuthenticatorPrivate::Start;

        QString connectHost = connection->d_func()->hostName;
        qint16 connectPort = connection->d_func()->port;

#ifndef QT_NO_NETWORKPROXY
        // HTTPS always use transparent proxy.
        if (connection->d_func()->networkProxy.type() != QNetworkProxy::NoProxy && !ssl) {
            connectHost = connection->d_func()->networkProxy.hostName();
            connectPort = connection->d_func()->networkProxy.port();
        }
        if (socket->proxy().type() == QNetworkProxy::HttpProxy) {
            // Make user-agent field available to HTTP proxy socket engine (QTBUG-17223)
            QByteArray value;
            // ensureConnection is called before any request has been assigned, but can also be called again if reconnecting
            if (request.url().isEmpty())
                value = connection->d_func()->predictNextRequest().headerField("user-agent");
            else
                value = request.headerField("user-agent");
            if (!value.isEmpty())
                socket->setProperty("_q_user-agent", value);
        }
#endif
        if (ssl) {
#ifndef QT_NO_OPENSSL
            QSslSocket *sslSocket = qobject_cast<QSslSocket*>(socket);
            sslSocket->connectToHostEncrypted(connectHost, connectPort);
            if (ignoreAllSslErrors)
                sslSocket->ignoreSslErrors();
            sslSocket->ignoreSslErrors(ignoreSslErrorsList);

            // limit the socket read buffer size. we will read everything into
            // the QHttpNetworkReply anyway, so let's grow only that and not
            // here and there.
            socket->setReadBufferSize(64*1024);
#else
            connection->d_func()->emitReplyError(socket, reply, QNetworkReply::ProtocolUnknownError);
#endif
        } else {
            // In case of no proxy we can use the Unbuffered QTcpSocket
#ifndef QT_NO_NETWORKPROXY
            if (connection->d_func()->networkProxy.type() == QNetworkProxy::NoProxy
                    && connection->cacheProxy().type() == QNetworkProxy::NoProxy
                    && connection->transparentProxy().type() == QNetworkProxy::NoProxy) {
#endif
                socket->connectToHost(connectHost, connectPort, QIODevice::ReadWrite | QIODevice::Unbuffered);
                // For an Unbuffered QTcpSocket, the read buffer size has a special meaning.
                socket->setReadBufferSize(1*1024);
#ifndef QT_NO_NETWORKPROXY
            } else {
                socket->connectToHost(connectHost, connectPort);

                // limit the socket read buffer size. we will read everything into
                // the QHttpNetworkReply anyway, so let's grow only that and not
                // here and there.
                socket->setReadBufferSize(64*1024);
            }
#endif
        }
        return false;
    }
    return true;
}
const AudioFileModel AnalyzeTask::analyzeFile(const QString &filePath, int *type)
{
	*type = fileTypeNormal;
	AudioFileModel audioFile(filePath);

	QFile readTest(filePath);
	if(!readTest.open(QIODevice::ReadOnly))
	{
		*type = fileTypeDenied;
		return audioFile;
	}
	if(checkFile_CDDA(readTest))
	{
		*type = fileTypeCDDA;
		return audioFile;
	}
	readTest.close();

	bool skipNext = false;
	unsigned int id_val[2] = {UINT_MAX, UINT_MAX};
	cover_t coverType = coverNone;
	QByteArray coverData;

	QStringList params;
	params << QString("--Inform=file://%1").arg(QDir::toNativeSeparators(m_templateFile));
	params << QDir::toNativeSeparators(filePath);
	
	QProcess process;
	lamexp_init_process(process, QFileInfo(m_mediaInfoBin).absolutePath());

	process.start(m_mediaInfoBin, params);
		
	if(!process.waitForStarted())
	{
		qWarning("MediaInfo process failed to create!");
		qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
		process.kill();
		process.waitForFinished(-1);
		return audioFile;
	}

	while(process.state() != QProcess::NotRunning)
	{
		if(*m_abortFlag)
		{
			process.kill();
			qWarning("Process was aborted on user request!");
			break;
		}
		
		if(!process.waitForReadyRead())
		{
			if(process.state() == QProcess::Running)
			{
				qWarning("MediaInfo time out. Killing process and skipping file!");
				process.kill();
				process.waitForFinished(-1);
				return audioFile;
			}
		}

		QByteArray data;

		while(process.canReadLine())
		{
			QString line = QString::fromUtf8(process.readLine().constData()).simplified();
			if(!line.isEmpty())
			{
				//qDebug("Line:%s", QUTF8(line));
				
				int index = line.indexOf('=');
				if(index > 0)
				{
					QString key = line.left(index).trimmed();
					QString val = line.mid(index+1).trimmed();
					if(!key.isEmpty())
					{
						updateInfo(audioFile, &skipNext, id_val, &coverType, &coverData, key, val);
					}
				}
			}
		}
	}

	if(audioFile.metaInfo().title().isEmpty())
	{
		QString baseName = QFileInfo(filePath).fileName();
		int index = baseName.lastIndexOf(".");

		if(index >= 0)
		{
			baseName = baseName.left(index);
		}

		baseName = baseName.replace("_", " ").simplified();
		index = baseName.lastIndexOf(" - ");

		if(index >= 0)
		{
			baseName = baseName.mid(index + 3).trimmed();
		}

		audioFile.metaInfo().setTitle(baseName);
	}
	
	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}

	if((coverType != coverNone) && (!coverData.isEmpty()))
	{
		retrieveCover(audioFile, coverType, coverData);
	}

	if((audioFile.techInfo().audioType().compare("PCM", Qt::CaseInsensitive) == 0) && (audioFile.techInfo().audioProfile().compare("Float", Qt::CaseInsensitive) == 0))
	{
		if(audioFile.techInfo().audioBitdepth() == 32) audioFile.techInfo().setAudioBitdepth(AudioFileModel::BITDEPTH_IEEE_FLOAT32);
	}

	return audioFile;
}
Esempio n. 9
0
bool CertWizard::validateCurrentPage() {
	if (currentPage() == qwpNew) {
		if (! bValidDomain) {
			QRegExp ereg(QLatin1String("(.+)@(.+)"), Qt::CaseInsensitive, QRegExp::RegExp2);
			if (ereg.exactMatch(qleEmail->text())) {
				const QString &domain = ereg.cap(2);
				if (! domain.isEmpty()) {
					qlError->setText(tr("Resolving domain %1.").arg(domain));
					bPendingDns = true;
					iLookupId = QHostInfo::lookupHost(domain, this, SLOT(lookedUp(QHostInfo)));
				} else
					bValidDomain = true;
			} else
				qlError->setText(tr("Unable to validate email.<br />Enter a valid (or blank) email to continue."));
			if (! bValidDomain) {
				qwpNew->setComplete(false);
				return false;
			}
		} else {
			kpNew = generateNewCert(qleName->text(), qleEmail->text());
			if (! validateCert(kpNew)) {
				qlError->setText(tr("There was an error generating your certificate.<br />Please try again."));
				return false;
			}
		}
	}
	if (currentPage() == qwpExport) {
		QByteArray qba = exportCert(kpNew);
		if (qba.isEmpty()) {
			QToolTip::showText(qleExportFile->mapToGlobal(QPoint(0,0)), tr("Your certificate and key could not be exported to PKCS#12 format. There might be an error in your certificate."), qleExportFile);
			return false;
		}
		QFile f(qleExportFile->text());
		if (! f.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Unbuffered)) {
			QToolTip::showText(qleExportFile->mapToGlobal(QPoint(0,0)), tr("The file could not be opened for writing. Please use another file."), qleExportFile);
			return false;
		}
		qint64 written = f.write(qba);
		f.close();
		if (written != qba.length()) {
			QToolTip::showText(qleExportFile->mapToGlobal(QPoint(0,0)), tr("The file could not be written successfully. Please use another file."), qleExportFile);
			return false;
		}
	}
	if (currentPage() == qwpImport) {
		QFile f(qleImportFile->text());
		if (! f.open(QIODevice::ReadOnly | QIODevice::Unbuffered)) {
			QToolTip::showText(qleImportFile->mapToGlobal(QPoint(0,0)), tr("The file could not be opened for reading. Please use another file."), qleImportFile);
			return false;
		}
		QByteArray qba = f.readAll();
		f.close();
		if (qba.isEmpty()) {
			QToolTip::showText(qleImportFile->mapToGlobal(QPoint(0,0)), tr("The file is empty or could not be read. Please use another file."), qleImportFile);
			return false;
		}
		QPair<QList<QSslCertificate>, QSslKey> imp = importCert(qba, qlePassword->text());
		if (! validateCert(imp)) {
			QToolTip::showText(qleImportFile->mapToGlobal(QPoint(0,0)), tr("The file did not contain a valid certificate and key. Please use another file."), qleImportFile);
			return false;
		}
		kpNew = imp;
	}
	if (currentPage() == qwpFinish) {
		g.s.kpCertificate = kpNew;
	}
	return QWizard::validateCurrentPage();
}
Esempio n. 10
0
// Update a C++ type so that any typedefs and registered ints are resolved.
QByteArray Chimera::resolve_types(const QByteArray &type)
{
    // Split into a base type and a possible list of template arguments.
    QByteArray resolved = type.simplified();

    // Get the raw type, ie. without any "const", "&" or "*".
    QByteArray raw_type;
    int original_raw_start;

    if (resolved.startsWith("const "))
        original_raw_start = 6;
    else
        original_raw_start = 0;

    raw_type = resolved.mid(original_raw_start);

    while (raw_type.endsWith('&') || raw_type.endsWith('*') || raw_type.endsWith(' '))
        raw_type.chop(1);

    int original_raw_len = raw_type.size();

    if (original_raw_len == 0)
        return QByteArray();

    // Get any template arguments.
    QList<QByteArray> args;
    int tstart = raw_type.indexOf('<');

    if (tstart >= 0)
    {
        // Make sure the template arguments are terminated.
        if (!raw_type.endsWith('>'))
            return QByteArray();

        // Split the template arguments taking nested templates into account.
        int depth = 1, arg_start = tstart + 1;

        for (int i = arg_start; i < raw_type.size(); ++i)
        {
            int arg_end = -1;
            char ch = raw_type.at(i);

            if (ch == '<')
            {
                ++depth;
            }
            else if (ch == '>')
            {
                --depth;

                if (depth < 0)
                    return QByteArray();

                if (depth == 0)
                    arg_end = i;
            }
            else if (ch == ',' && depth == 1)
            {
                arg_end = i;
            }

            if (arg_end >= 0)
            {
                QByteArray arg = resolve_types(raw_type.mid(arg_start, arg_end - arg_start));

                if (arg.isEmpty())
                    return QByteArray();

                args.append(arg);

                arg_start = arg_end + 1;
            }
        }

        if (depth != 0)
            return QByteArray();

        // Remove the template arguments.
        raw_type.truncate(tstart);
    }

    // Expand any typedef.
    const char *base_type = sipResolveTypedef(raw_type.constData());

    if (base_type)
        raw_type = base_type;

    // Do the same for any registered int types.
    if (_registered_int_types.contains(raw_type))
        raw_type = "int";

    // Add any (now resolved) template arguments.
    if (args.count() > 0)
    {
        raw_type.append('<');

        for (QList<QByteArray>::const_iterator it = args.begin();;)
        {
            raw_type.append(*it);

            if (++it == args.end())
                break;

            raw_type.append(',');
        }

        if (raw_type.endsWith('>'))
            raw_type.append(' ');

        raw_type.append('>');
    }

    // Replace the original raw type with the resolved one.
    resolved.replace(original_raw_start, original_raw_len, raw_type);

    return resolved;
}
Esempio n. 11
0
// Parse the given C++ type name.
bool Chimera::parse_cpp_type(const QByteArray &type)
{
    _name = type;

    // Resolve any types.
    QByteArray resolved = resolve_types(type);

    if (resolved.isEmpty())
        return false;

    // See if the type is known to Qt.
    _metatype = QMetaType::type(resolved.constData());

    // If not then use the PyQt_PyObject wrapper.
    if (_metatype == QMetaType::Void)
        _metatype = PyQt_PyObject::metatype;

    // See if the type (without a pointer) is known to SIP.
    bool is_ptr = resolved.endsWith('*');

    if (is_ptr)
    {
        resolved.chop(1);

        if (resolved.endsWith('*'))
            return false;
    }

    _type = sipFindType(resolved.constData());

    if (!_type)
    {
        // This is the only fundamental pointer type recognised by Qt.
        if (_metatype == QMetaType::VoidStar)
            return true;

        // This is 'int', 'bool', etc.
        if (_metatype != PyQt_PyObject::metatype && !is_ptr)
            return true;

        if ((resolved == "char" || resolved == "const char") && is_ptr)
        {
            // This is a special value meaning a (hopefully) '\0' terminated
            // string.
            _metatype = -1;

            return true;
        }

        // This is an explicit 'PyQt_PyObject'.
        if (resolved == "PyQt_PyObject" && !is_ptr)
            return true;

        return false;
    }

    if (sipTypeIsNamespace(_type))
        return false;

    if (sipTypeIsClass(_type))
    {
        set_flag();

        if (is_ptr)
        {
            PyTypeObject *type_obj = sipTypeAsPyTypeObject(_type);

            if (sipType_QWidget && PyType_IsSubtype(type_obj, sipTypeAsPyTypeObject(sipType_QWidget)))
            {
                _metatype = QMetaType::QWidgetStar;
            }
            else if (PyType_IsSubtype(type_obj, sipTypeAsPyTypeObject(sipType_QObject)))
            {
                _metatype = QMetaType::QObjectStar;
            }
        }
    }

    // We don't support pointers to enums.
    if (sipTypeIsEnum(_type) && is_ptr)
        _type = 0;

    if (sipTypeIsEnum(_type) || isFlag())
        _metatype = QMetaType::Int;

    return true;
}
Esempio n. 12
0
// Parse a normalised C++ signature as a list of types.
Chimera::Signature *Chimera::parse(const QByteArray &sig, const char *context)
{
    // Extract the argument list.
    int start_idx = sig.indexOf('(');

    if (start_idx < 0)
        start_idx = 0;
    else
        ++start_idx;

    int end_idx = sig.lastIndexOf(')');

    int len;

    if (end_idx < start_idx)
        len = -1;
    else
        len = end_idx - start_idx;

    // Parse each argument type.
    Chimera::Signature *parsed_sig = new Chimera::Signature(sig, true);

    if (len > 0)
    {
        QByteArray args_str = sig.mid(start_idx, len);

        // Check we haven't already done it.
        QList<const Chimera *> parsed_args = _previously_parsed.value(args_str);

        if (parsed_args.isEmpty())
        {
            int i, arg_start, template_level;

            i = arg_start = template_level = 0;

            // Extract each argument allowing for commas in templates.
            for (;;)
            {
                char ch = (i < args_str.size() ? args_str.at(i) : '\0');
                QByteArray arg;

                switch (ch)
                {
                case '<':
                    ++template_level;
                    break;

                case '>':
                    --template_level;
                    break;

                case '\0':
                    arg = args_str.mid(arg_start, i - arg_start);
                    break;

                case ',':
                    if (template_level == 0)
                    {
                        arg = args_str.mid(arg_start, i - arg_start);
                        arg_start = i + 1;
                    }

                    break;
                }

                if (!arg.isEmpty())
                {
                    Chimera *ct = new Chimera;

                    if (!ct->parse_cpp_type(arg))
                    {
                        delete ct;
                        delete parsed_sig;
                        qDeleteAll(parsed_args.constBegin(),
                                parsed_args.constEnd());

                        raiseParseException(arg.constData(), context);

                        return 0;
                    }

                    parsed_args.append(ct);

                    if (ch == '\0')
                        break;
                }

                ++i;
            }

            // Only parse once.
            _previously_parsed.insert(args_str, parsed_args);
        }

        parsed_sig->parsed_arguments = parsed_args;
    }

    return parsed_sig;
}
Esempio n. 13
0
Profile* Profile::loadProfile(QString name, QString password)
{
    if (ProfileLocker::hasLock())
    {
        qCritical() << "Tried to load profile "<<name<<", but another profile is already locked!";
        return nullptr;
    }

    if (!ProfileLocker::lock(name))
    {
        qWarning() << "Failed to lock profile "<<name;
        return nullptr;
    }

    // Check password
    {
        QString path = Settings::getInstance().getSettingsDirPath() + name + ".tox";
        QFile saveFile(path);
        qDebug() << "Loading tox save "<<path;

        if (!saveFile.exists())
        {
            qWarning() << "The tox save file "<<path<<" was not found";
            ProfileLocker::unlock();
            return nullptr;
        }

        if (!saveFile.open(QIODevice::ReadOnly))
        {
            qCritical() << "The tox save file " << path << " couldn't' be opened";
            ProfileLocker::unlock();
            return nullptr;
        }

        qint64 fileSize = saveFile.size();
        if (fileSize <= 0)
        {
            qWarning() << "The tox save file"<<path<<" is empty!";
            ProfileLocker::unlock();
            return nullptr;
        }

        QByteArray data = saveFile.readAll();
        if (tox_is_data_encrypted((uint8_t*)data.data()))
        {
            if (password.isEmpty())
            {
                qCritical() << "The tox save file is encrypted, but we don't have a password!";
                ProfileLocker::unlock();
                return nullptr;
            }

            uint8_t salt[TOX_PASS_SALT_LENGTH];
            tox_get_salt(reinterpret_cast<uint8_t *>(data.data()), salt);
            auto tmpkey = *Core::createPasskey(password, salt);

            data = Core::decryptData(data, tmpkey);
            if (data.isEmpty())
            {
                qCritical() << "Failed to decrypt the tox save file";
                ProfileLocker::unlock();
                return nullptr;
            }
        }
        else
        {
            if (!password.isEmpty())
                qWarning() << "We have a password, but the tox save file is not encrypted";
        }
    }

    return new Profile(name, password, false);
}
Esempio n. 14
0
bool QMplayer::download(QString url, QString destPath, QString filename, bool justCheck)
{
    QString host = url;
    QString reqPath;
    int port = 80;

    if(url.startsWith("http://"))
    {
        host.remove(0, 7);
    }

    int colonIndex = host.indexOf(':');
    int slashIndex = host.indexOf('/');
    if(slashIndex < 0)
    {
        return false;
    }
    reqPath = host.right(host.length() - slashIndex).replace(" ", "%20");
    host = host.left(slashIndex);
    if(colonIndex > 0)
    {
        QString portStr = host.right(host.length() - colonIndex - 1);
        host = host.left(colonIndex);
        port = portStr.toInt(0, 10);
    }

connect:
    QTcpSocket sock(this);
    sock.setReadBufferSize(65535);
    sock.connectToHost(host, port);
    if(!sock.waitForConnected(5000))
    {
        QMessageBox::critical(this, tr("qmplayer"), sock.errorString());
        return false;
    }

    QByteArray req("GET ");
    req.append(reqPath);
    req.append(" HTTP/1.1\r\nHost: ");
    req.append(host);
    req.append(':');
    req.append(QByteArray::number(port));
    req.append("\r\n\r\n");

    sock.write(req);
    sock.flush();
    sock.waitForBytesWritten();

    int contentLen = 0;
    bool html = false;
    QByteArray line;
    for(;;)
    {
        line = sock.readLine();
        if(line.isEmpty())
        {
            if(sock.waitForReadyRead(5000))
            {
                continue;
            }
            break;
        }
        if(line.trimmed().isEmpty())
        {
            break;
        }
        html = html | (line.indexOf("Content-Type: text/html") == 0);
        if(line.indexOf("Content-Length: ") == 0)
        {
            contentLen = line.remove(0, 16).trimmed().toInt(0, 10);
        }
    }

    if(html)
    {
        QByteArray text = sock.readAll();
        sock.close();
        if(text.length() == 0)
        {
            QMessageBox::critical(this, tr("qmplayer"),
                                  tr("No response from ") + host);
            return false;
        }
        text.replace("</br>", "\n");
        if(QMessageBox::information(this, "qmplayer", text,
                                 QMessageBox::Ok | QMessageBox::Retry) == QMessageBox::Retry)
        {
            goto connect;
        }

        return false;
    }
    else if(justCheck)
    {
        sock.close();
        return true;
    }

    QFile f(destPath);
    if(!f.open(QFile::WriteOnly))
    {
        QMessageBox::critical(this, tr("qmplayer"),
                              tr("Unable to save file:\r\n\r\n") + f.errorString());
        sock.close();
        return false;
    }

    showScreen(QMplayer::ScreenDownload);
    label->setText(tr("Downloading") + " " + filename);
#ifdef QTOPIA
     QtopiaApplication::setPowerConstraint(QtopiaApplication::DisableSuspend);
#endif

    if(contentLen <= 0)
    {
        contentLen = 1024 * 1024;
    }
    progress->setMaximum(contentLen);
    progress->setValue(0);
    int remains = contentLen;

    char buf[65535];
    int count;
    abort = false;
    for(;;)
    {
        QApplication::processEvents();
        if(abort)
        {
            break;
        }
        if(sock.bytesAvailable() < 65535
           && sock.state() == QAbstractSocket::ConnectedState)
        {
            sock.waitForReadyRead(1000);
            continue;
        }
        count = sock.read(buf, 65535);
        if(count <= 0)
        {
            break;
        }
        f.write(buf, count);
        f.flush();
        remains -= count;
        if(remains <= 0)
        {
            remains = contentLen;
        }
        progress->setValue(contentLen - remains);
    }
    f.close();
    sock.close();

#ifdef QTOPIA
    QtopiaApplication::setPowerConstraint(QtopiaApplication::Enable);
#endif

    return true;
}
Esempio n. 15
0
int main(int argc, char *argv[])
{
    // FIXME: this can be considered a poor man's solution, as it's not
    // directly obvious to a gui user. :)
    // anyway, i vote against removing it even when we have a proper gui
    // implementation.  -- ossi

    QByteArray duser = qgetenv("ADMIN_ACCOUNT");
    if (duser.isEmpty())
        duser = "******";

    KAboutData aboutData("kdesu", 0, ki18n("KDE su"),
            Version, ki18n("Runs a program with elevated privileges."),
            KAboutData::License_Artistic,
            ki18n("Copyright (c) 1998-2000 Geert Jansen, Pietro Iglio"));
    aboutData.addAuthor(ki18n("Geert Jansen"), ki18n("Maintainer"),
            "*****@*****.**", "http://www.stack.nl/~geertj/");
    aboutData.addAuthor(ki18n("Pietro Iglio"), ki18n("Original author"),
            "*****@*****.**");
    aboutData.setProgramIconName("dialog-password");

    KCmdLineArgs::init(argc, argv, &aboutData);

    // NOTE: if you change the position of the -u switch, be sure to adjust it
    // at the beginning of main()
    KCmdLineOptions options;
    options.add("!+command", ki18n("Specifies the command to run as separate arguments"));
    options.add("c <command>", ki18n("Specifies the command to run as one string"));
    options.add("f <file>", ki18n("Run command under target uid if <file> is not writable"));
    options.add("u <user>", ki18n("Specifies the target uid"), duser);
    options.add("n", ki18n("Do not keep password"));
    options.add("s", ki18n("Stop the daemon (forgets all passwords)"));
    options.add("t", ki18n("Enable terminal output (no password keeping)"));
    options.add("p <prio>", ki18n("Set priority value: 0 <= prio <= 100, 0 is lowest"), "50");
    options.add("r", ki18n("Use realtime scheduling"));
    options.add("noignorebutton", ki18n("Do not display ignore button"));
    options.add("i <icon name>", ki18n("Specify icon to use in the password dialog"));
    options.add("d", ki18n("Do not show the command to be run in the dialog"));
#ifdef Q_WS_X11
    /* KDialog originally used --embed for attaching the dialog box.  However this is misleading and so we changed to --attach.
     * For consistancy, we silently map --embed to --attach */
    options.add("attach <winid>", ki18nc("Transient means that the kdesu app will be attached to the app specified by the winid so that it is like a dialog box rather than some separate program", "Makes the dialog transient for an X app specified by winid"));
    options.add("embed <winid>");
#endif
    KCmdLineArgs::addCmdLineOptions(options);

    //KApplication::disableAutoDcopRegistration();
    // kdesu doesn't process SM events, so don't even connect to ksmserver
    QByteArray session_manager = qgetenv( "SESSION_MANAGER" );
    if (!session_manager.isEmpty())
        unsetenv( "SESSION_MANAGER" );
    KApplication app;
    // but propagate it to the started app
    if (!session_manager.isEmpty())
        setenv( "SESSION_MANAGER", session_manager.data(), 1 );

    {
#ifdef Q_WS_X11
        KStartupInfoId id;
        id.initId( kapp->startupId());
        id.setupStartupEnv(); // make DESKTOP_STARTUP_ID env. var. available again
#endif
    }

    int result = startApp();

    if (result == 127)
    {
        KMessageBox::sorry(0, i18n("Cannot execute command '%1'.", QString::fromLocal8Bit(command)));
    }

    return result;
}
Esempio n. 16
0
QList<Abi> Abi::abisOfBinary(const Utils::FileName &path)
{
    QList<Abi> tmp;
    if (path.isEmpty())
        return tmp;

    QFile f(path.toString());
    if (!f.exists())
        return tmp;

    if (!f.open(QFile::ReadOnly))
        return tmp;

    QByteArray data = f.read(1024);
    if (data.size() >= 67
            && getUint8(data, 0) == '!' && getUint8(data, 1) == '<' && getUint8(data, 2) == 'a'
            && getUint8(data, 3) == 'r' && getUint8(data, 4) == 'c' && getUint8(data, 5) == 'h'
            && getUint8(data, 6) == '>' && getUint8(data, 7) == 0x0a) {
        // We got an ar file: possibly a static lib for ELF, PE or Mach-O

        data = data.mid(8); // Cut of ar file magic
        quint64 offset = 8;

        while (!data.isEmpty()) {
            if ((getUint8(data, 58) != 0x60 || getUint8(data, 59) != 0x0a)) {
                qWarning() << path.toString() << ": Thought it was an ar-file, but it is not!";
                break;
            }

            const QString fileName = QString::fromLocal8Bit(data.mid(0, 16));
            quint64 fileNameOffset = 0;
            if (fileName.startsWith(QLatin1String("#1/")))
                fileNameOffset = fileName.mid(3).toInt();
            const QString fileLength = QString::fromLatin1(data.mid(48, 10));

            int toSkip = 60 + fileNameOffset;
            offset += fileLength.toInt() + 60 /* header */;

            tmp.append(abiOf(data.mid(toSkip)));
            if (tmp.isEmpty() && fileName == QLatin1String("/0              "))
                tmp = parseCoffHeader(data.mid(toSkip, 20)); // This might be windws...

            if (!tmp.isEmpty()
                    && tmp.at(0).binaryFormat() != Abi::MachOFormat)
                break;

            offset += (offset % 2); // ar is 2 byte aligned
            f.seek(offset);
            data = f.read(1024);
        }
    } else {
        tmp = abiOf(data);
    }
    f.close();

    // Remove duplicates:
    QList<Abi> result;
    foreach (const Abi &a, tmp) {
        if (!result.contains(a))
            result.append(a);
    }

    return result;
}
Esempio n. 17
0
QT_BEGIN_NAMESPACE

int runUic3(int argc, char * argv[])
{
    bool impl = false;
    bool wrap = false;
    bool subcl = false;
    bool extract = false;
    bool imagecollection = false;
    bool imagecollection_tmpfile = false;
    bool convert = false;
    QStringList images;
    const char *error = 0;
    const char* fileName = 0;
    const char* className = 0;
    const char* headerFile = 0;
    const char* convertedUiFile = 0;
    QByteArray outputFile;
    QString  qrcOutputFile;
    QByteArray image_tmpfile;
    const char* projectName = 0;
    const char* trmacro = 0;
    bool nofwd = false;
    bool fix = false;
    bool deps = false;
    bool implicitIncludes = true;
    QByteArray pchFile;


    QApplication app(argc, argv, false);

    for (int n = 1; n < argc && error == 0; n++) {
        QByteArray arg = argv[n];
        if (arg[0] == '-') {                        // option
            QByteArray opt = arg.data() + 1;
            if (opt[0] == 'o') {                // output redirection
                if (opt[1] == '\0') {
                    if (!(n < argc-1)) {
                        error = "Missing output-file name";
                        break;
                    }
                    outputFile = argv[++n];
                } else
                    outputFile = opt.data() + 1;
            } else if (opt[0] == 'i' || opt == "impl") {
                impl = true;
                if (opt == "impl" || opt[1] == '\0') {
                    if (!(n < argc-1)) {
                        error = "Missing name of header file";
                        break;
                    }
                    headerFile = argv[++n];
                } else
                    headerFile = opt.data() + 1;
            } else if (opt[0] == 'w' || opt == "wrap") {
                wrap = true;
                if (opt == "wrap" || opt[1] == '\0') {
                    if (!(n < argc-1)) {
                        error = "Missing name of converted ui file";
                        break;
                    }
                    convertedUiFile = argv[++n];
                } else
                    convertedUiFile = opt.data() + 1;
            } else if (opt == "extract") {                // output redirection
                extract = true;
                if (!(n < argc-1)) {
                    error = "Missing output qrc-file name";
                    break;
                }
                qrcOutputFile = QFile::decodeName(argv[++n]);
            } else if ( opt[0] == 'e' || opt == "embed" ) {
                imagecollection = true;
                if ( opt == "embed" || opt[1] == '\0' ) {
                    if ( !(n < argc-1) ) {
                        error = "Missing name of project";
                        break;
                    }
                    projectName = argv[++n];
                } else {
                    projectName = opt.data() + 1;
                }
                if ( argc > n+1 && qstrcmp( argv[n+1], "-f" ) == 0 ) {
                    imagecollection_tmpfile = true;
                    image_tmpfile = argv[n+2];
                    n += 2;
                }
            } else if (opt == "d") {
                deps = true;
            } else if (opt == "no-implicit-includes") {
                implicitIncludes = false;
            } else if (opt == "nofwd") {
                nofwd = true;
            } else if (opt == "nounload") {
                // skip
            } else if (opt == "convert") {
                convert = true;
            } else if (opt == "subdecl") {
                subcl = true;
                if (!(n < argc-2)) {
                    error = "Missing arguments";
                    break;
                }
                className = argv[++n];
                headerFile = argv[++n];
            } else if (opt == "subimpl") {
                subcl = true;
                impl = true;
                if (!(n < argc-2)) {
                    error = "Missing arguments";
                    break;
                }
                className = argv[++n];
                headerFile = argv[++n];
            } else if (opt == "tr") {
                if (opt == "tr" || opt[1] == '\0') {
                    if (!(n < argc-1)) {
                        error = "Missing tr macro.";
                        break;
                    }
                    trmacro = argv[++n];
                } else {
                    trmacro = opt.data() + 1;
                }
            } else if (opt == "L") {
                if (!(n < argc-1)) {
                    error = "Missing plugin path.";
                    break;
                }
                ++n; // ignore the next argument
            } else if (opt == "version") {
                fprintf(stderr,
                        "Qt User Interface Compiler version %s\n",
                        QT_VERSION_STR);
                return 1;
            } else if (opt == "help") {
                break;
            } else if (opt == "fix") {
                fix = true;
            } else if (opt == "pch") {
                if (!(n < argc-1)) {
                    error = "Missing name of PCH file";
                    break;
                }
                pchFile = argv[++n];
            } else {
                error = "Unrecognized option";
            }
        } else {
            if (imagecollection && !imagecollection_tmpfile)
                images << QLatin1String(argv[n]);
            else if (fileName)                // can handle only one file
                error = "Too many input files specified";
            else
                fileName = argv[n];
        }
    }

    if (argc < 2 || error || (!fileName && !imagecollection)) {
        fprintf(stderr,
                "Qt User Interface Compiler version %s\n",
                QT_VERSION_STR);
        if (error)
            fprintf(stderr, "uic: %s\n", error);

        fprintf(stderr, "Usage: %s  [options] [mode] <uifile>\n\n"
                "Convert a UI file to version 4:\n"
                "   %s  [options] -convert <uifile>\n"
                "Generate declaration:\n"
                "   %s  [options] <uifile>\n"
                "\t<uiheaderfile>  name of the data file\n"
                "   %s  [options] -decl <uiheaderfile> <uifile>\n"
                "\t<uiheaderfile>  name of the data file\n"
                "   %s  [options] -wrap <converteduifile> <uifile>\n"
                "\t<converteduifile>  name of the converted ui file\n"
                "Generate implementation:\n"
                "   %s  [options] -impl <headerfile> <uifile>\n"
                "\t<headerfile>    name of the declaration file\n"
                "Generate image collection:\n"
                "   %s  [options] -embed <project> <image1> <image2> <image3> ...\n"
                "or\n"
                "   %s  [options] -embed <project> -f <temporary file containing image names>\n"
                "\t<project>       project name\n"
                "\t<image[1-N]>    image files\n"
                "Generate subclass declaration:\n"
                "   %s  [options] -subdecl <subclassname> <baseclassheaderfile> <uifile>\n"
                "\t<subclassname>     name of the subclass to generate\n"
                "\t<baseclassheaderfile>    declaration file of the baseclass\n"
                "Generate subclass implementation:\n"
                "   %s  [options] -subimpl <subclassname> <subclassheaderfile> <uifile>\n"
                "\t<subclassname>     name of the subclass to generate\n"
                "\t<subclassheaderfile>    declaration file of the subclass\n"
                "Options:\n"
                "\t-o file            Write output to file rather than stdout\n"
                "\t-extract qrcFile   Create resource file and extract embedded images into \"image\" dir\n"
                "\t-pch file          Add #include \"file\" as the first statement in implementation\n"
                "\t-nofwd             Omit forward declarations of custom classes\n"
                "\t-no-implicit-includes Do not generate #include-directives for custom classes\n"
                "\t-nounload          Don't unload plugins after processing\n"
                "\t-tr func           Use func() instead of tr() for i18n\n"
                "\t-L path            Additional plugin search path\n"
                "\t-version           Display version of uic\n"
                "\t-help              Display this information\n"
                , argv[0], argv[0], argv[0], argv[0], argv[0], argv[0], argv[0], argv[0], argv[0], argv[0]
               );
        return 1;
    }

    if (imagecollection_tmpfile) {
        QFile ifile(QFile::decodeName(image_tmpfile));
        if (ifile.open(QIODevice::ReadOnly)) {
            QTextStream ts(&ifile);
            QString s = ts.read();
            s = s.simplified();
            images = s.split(QLatin1Char(' '));
            for (QStringList::Iterator it = images.begin(); it != images.end(); ++it)
                *it = (*it).simplified();
        }
    }

    QFile fileOut;
    if (!outputFile.isEmpty()) {
        fileOut.setFileName(QFile::decodeName(outputFile));
        if (!fileOut.open(QIODevice::WriteOnly)) {
            fprintf(stderr, "%s: Could not open output file '%s'\n", argv[0], outputFile.data());
            return 1;
        }
    } else {
        fileOut.open(QIODevice::WriteOnly, stdout);
    }

    QTextStream out(&fileOut);

    Ui3Reader ui3(out);
    ui3.setExtractImages(extract, qrcOutputFile);

    if (projectName && imagecollection) {
        out.setEncoding(QTextStream::Latin1);
        ui3.embed(projectName, images);
        return 0;
    }

    out.setEncoding(QTextStream::UnicodeUTF8);

    QFile file(QFile::decodeName(fileName));
    if (!file.open(QIODevice::ReadOnly)) {
        fprintf(stderr, "%s: Could not open file '%s'\n", argv[0], fileName);
        return 1;
    }

    QDomDocument doc;
    QString errMsg;
    int errLine;
    if (!doc.setContent(&file, &errMsg, &errLine)) {
        fprintf(stderr, "%s: Failed to parse %s: %s in line %d\n", argv[0], fileName, errMsg.latin1(), errLine);
        return 1;
    }

    QDomElement e = doc.firstChild().toElement();
    double version = e.attribute(QLatin1String("version"), QLatin1String("3.0")).toDouble();

    if (version > 3.3) {
        fprintf(stderr, "%s: File generated with too recent version of Qt Designer (%s vs. %s)\n",
                argv[0], e.attribute(QLatin1String("version")).latin1(), "3.3");
        return 1;
    }

    DomTool::fixDocument(doc);

    if (fix) {
        out << doc.toString();
        return 0;
    }

    if (imagecollection) {
        out.setEncoding(QTextStream::Latin1);
        ui3.embed(projectName, images);
        return 0;
    } else if (deps) {
        QStringList globalIncludes, localIncludes;
        ui3.computeDeps(e, globalIncludes, localIncludes, impl);

        foreach (QString i, globalIncludes)
            printf("%s\n", i.toLatin1().constData());

        foreach (QString i, localIncludes)
            printf("%s\n", i.toLatin1().constData());

        if (impl)
            printf("%s\n", headerFile);

        return 0;
    } else if (convert) {
        ui3.generateUi4(QFile::decodeName(fileName), QFile::decodeName(outputFile), doc, implicitIncludes);
        return 0;
    }

    QString protector;
    if (subcl && className && !impl)
        protector = QString::fromUtf8(className).toUpper() + QLatin1String("_H");

    if (!protector.isEmpty()) {
        out << "#ifndef " << protector << endl;
        out << "#define " << protector << endl;
    }

    if (!pchFile.isEmpty() && impl) {
        out << "#include \"" << pchFile << "\" // PCH include" << endl;
    }

    if (headerFile) {
        out << "#include \"" << headerFile << "\"" << endl << endl;
    }

    QString convertedUi;
    if (wrap) {
        convertedUi = QFile::decodeName(convertedUiFile);
        int pos = convertedUi.lastIndexOf(QLatin1String(".ui"));
        if (pos > 0) {
            convertedUi = convertedUi.mid(0, pos);
            convertedUi += QLatin1String(".h");
        }
        convertedUi = QLatin1String("ui_") + convertedUi;
    }

    ui3.generate(QFile::decodeName(fileName),
                 QFile::decodeName(outputFile),
                 doc,
                 !impl,
                 subcl,
                 QString::fromUtf8(trmacro),
                 QString::fromUtf8(className),
                 nofwd,
                 implicitIncludes,
                 convertedUi);

    if (!protector.isEmpty()) {
        out << endl;
        out << "#endif // " << protector << endl;
    }

    if (fileOut.error() != QFile::NoError) {
        fprintf(stderr, "%s: Error writing to file\n", argv[0]);
        if (!outputFile.isEmpty())
            remove(outputFile);
    }

    return 0;
}
Esempio n. 18
0
int LdapOperation::LdapOperationPrivate::bind( const QByteArray &creds,
                                               SASL_Callback_Proc *saslproc,
                                               void *data, bool async )
{
  Q_ASSERT( mConnection );
  LDAP *ld = (LDAP *) mConnection->handle();
  LdapServer server;
  server = mConnection->server();

  int ret;

  if ( server.auth() == LdapServer::SASL ) {
#if defined( SASL2_FOUND ) && !defined( HAVE_WINLDAP_H )
    sasl_conn_t *saslconn = (sasl_conn_t *)mConnection->saslHandle();
    sasl_interact_t *client_interact = NULL;
    const char *out = NULL;
    uint outlen;
    const char *mechusing = NULL;
    struct berval ccred, *scred;
    int saslresult;
    QByteArray sdata = creds;

    QString mech = server.mech();
    if ( mech.isEmpty() ) {
      mech = "DIGEST-MD5";
    }

    SASL_Data sasldata;
    sasldata.proc = saslproc;
    sasldata.data = data;
    sasldata.creds.fields = 0;
    sasldata.creds.realm = server.realm();
    sasldata.creds.authname = server.user();
    sasldata.creds.authzid = server.bindDn();
    sasldata.creds.password = server.password();

    do {
      if ( sdata.isEmpty() ) {
        do {
          saslresult = sasl_client_start( saslconn, mech.toLatin1(),
                                          &client_interact, &out, &outlen, &mechusing );

          if ( saslresult == SASL_INTERACT ) {
            if ( kldap_sasl_interact( client_interact, &sasldata ) != KLDAP_SUCCESS ) {
              return KLDAP_SASL_ERROR;
            }
          }
          kDebug() << "sasl_client_start mech: "
                   << mechusing << " outlen " << outlen
                   << " result: " << saslresult;
        } while ( saslresult == SASL_INTERACT );
        if ( saslresult != SASL_CONTINUE && saslresult != SASL_OK ) {
          return KLDAP_SASL_ERROR;
        }

      } else {
        kDebug() << "sasl_client_step";
        do {
          saslresult = sasl_client_step( saslconn, sdata.data(), sdata.size(),
                                         &client_interact, &out, &outlen );
          if ( saslresult == SASL_INTERACT ) {
            if ( kldap_sasl_interact( client_interact, &sasldata ) != KLDAP_SUCCESS ) {
              return KLDAP_SASL_ERROR;
            }
          }
        } while ( saslresult == SASL_INTERACT );
        kDebug() << "sasl_client_step result" << saslresult;
        if ( saslresult != SASL_CONTINUE && saslresult != SASL_OK ) {
          return KLDAP_SASL_ERROR;
        }
      }

      ccred.bv_val = (char*) out;
      ccred.bv_len = outlen;

      if ( async ) {
        kDebug() << "ldap_sasl_bind";
        int msgid;
        ret =
          ldap_sasl_bind( ld, server.bindDn().toUtf8().data(), mech.toLatin1(),
                          &ccred, 0, 0, &msgid );
        if ( ret == 0 ) {
          ret = msgid;
        }
        kDebug() << "ldap_sasl_bind msgid" << ret;
      } else {
        kDebug() << "ldap_sasl_bind_s";
        ret =
          ldap_sasl_bind_s( ld, server.bindDn().toUtf8().data(), mech.toLatin1(),
                            &ccred, 0, 0, &scred );
        kDebug() << "ldap_sasl_bind_s ret" << ret;
        if ( scred ) {
          sdata = QByteArray( scred->bv_val, scred->bv_len );
        } else {
          sdata = QByteArray();
        }
      }
    } while ( !async && ret == KLDAP_SASL_BIND_IN_PROGRESS );
#else
    kError() << "SASL authentication is not available "
             << "(re-compile kldap with cyrus-sasl and OpenLDAP development).";
    return KLDAP_SASL_ERROR;
#endif
  } else { //simple auth
    QByteArray bindname, pass;
    struct berval ccred;
    if ( server.auth() == LdapServer::Simple ) {
      bindname = server.bindDn().toUtf8();
      pass = server.password().toUtf8();
    }
    ccred.bv_val = pass.data();
    ccred.bv_len = pass.size();
    kDebug() << "binding to server, bindname: " << bindname << " password: *****";

    if ( async ) {
      kDebug() << "ldap_sasl_bind (simple)";
#ifndef HAVE_WINLDAP_H
      int msgid = 0;
      ret = ldap_sasl_bind( ld, bindname.data(), 0, &ccred, 0, 0, &msgid );
      if ( ret == 0 ) {
        ret = msgid;
      }
#else
      ret = ldap_simple_bind( ld, bindname.data(), pass.data() );
#endif
    } else {
      kDebug() << "ldap_sasl_bind_s (simple)";
#ifndef HAVE_WINLDAP_H
      ret = ldap_sasl_bind_s( ld, bindname.data(), 0, &ccred, 0, 0, 0 );
#else
      ret = ldap_simple_bind_s( ld, bindname.data(), pass.data() );
#endif
    }
  }
  return ret;
}
Esempio n. 19
0
void QEglFSKmsEglDeviceWindow::resetSurface()
{
    qCDebug(qLcEglfsKmsDebug, "Creating stream");

    EGLDisplay display = screen()->display();
    EGLint streamAttribs[3];
    int streamAttribCount = 0;
    int fifoLength = qEnvironmentVariableIntValue("QT_QPA_EGLFS_STREAM_FIFO_LENGTH");
    if (fifoLength > 0) {
        streamAttribs[streamAttribCount++] = EGL_STREAM_FIFO_LENGTH_KHR;
        streamAttribs[streamAttribCount++] = fifoLength;
    }
    streamAttribs[streamAttribCount++] = EGL_NONE;

    m_egl_stream = m_integration->m_funcs->create_stream(display, streamAttribs);
    if (m_egl_stream == EGL_NO_STREAM_KHR) {
        qWarning("resetSurface: Couldn't create EGLStream for native window");
        return;
    }

    qCDebug(qLcEglfsKmsDebug, "Created stream %p on display %p", m_egl_stream, display);

    EGLint count;
    if (m_integration->m_funcs->query_stream(display, m_egl_stream, EGL_STREAM_FIFO_LENGTH_KHR, &count)) {
        if (count > 0)
            qCDebug(qLcEglfsKmsDebug, "Using EGLStream FIFO mode with %d frames", count);
        else
            qCDebug(qLcEglfsKmsDebug, "Using EGLStream mailbox mode");
    } else {
        qCDebug(qLcEglfsKmsDebug, "Could not query number of EGLStream FIFO frames");
    }

    if (!m_integration->m_funcs->get_output_layers(display, Q_NULLPTR, Q_NULLPTR, 0, &count) || count == 0) {
        qWarning("No output layers found");
        return;
    }

    qCDebug(qLcEglfsKmsDebug, "Output has %d layers", count);

    QVector<EGLOutputLayerEXT> layers;
    layers.resize(count);
    EGLint actualCount;
    if (!m_integration->m_funcs->get_output_layers(display, Q_NULLPTR, layers.data(), count, &actualCount)) {
        qWarning("Failed to get layers");
        return;
    }

    QEglFSKmsEglDeviceScreen *cur_screen = static_cast<QEglFSKmsEglDeviceScreen *>(screen());
    Q_ASSERT(cur_screen);
    QKmsOutput &output(cur_screen->output());
    const uint32_t wantedId = !output.wants_plane ? output.crtc_id : output.plane_id;
    qCDebug(qLcEglfsKmsDebug, "Searching for id: %d", wantedId);

    EGLOutputLayerEXT layer = EGL_NO_OUTPUT_LAYER_EXT;
    for (int i = 0; i < actualCount; ++i) {
        EGLAttrib id;
        if (m_integration->m_funcs->query_output_layer_attrib(display, layers[i], EGL_DRM_CRTC_EXT, &id)) {
            qCDebug(qLcEglfsKmsDebug, "  [%d] layer %p - crtc %d", i, layers[i], (int) id);
            if (id == EGLAttrib(wantedId))
                layer = layers[i];
        } else if (m_integration->m_funcs->query_output_layer_attrib(display, layers[i], EGL_DRM_PLANE_EXT, &id)) {
            qCDebug(qLcEglfsKmsDebug, "  [%d] layer %p - plane %d", i, layers[i], (int) id);
            if (id == EGLAttrib(wantedId))
                layer = layers[i];
        } else {
            qCDebug(qLcEglfsKmsDebug, "  [%d] layer %p - unknown", i, layers[i]);
        }
    }

    QByteArray reqLayerIndex = qgetenv("QT_QPA_EGLFS_LAYER_INDEX");
    if (!reqLayerIndex.isEmpty()) {
        int idx = reqLayerIndex.toInt();
        if (idx >= 0 && idx < layers.count()) {
            qCDebug(qLcEglfsKmsDebug, "EGLOutput layer index override = %d", idx);
            layer = layers[idx];
        }
    }

    if (layer == EGL_NO_OUTPUT_LAYER_EXT) {
        qWarning("resetSurface: Couldn't get EGLOutputLayer for native window");
        return;
    }

    qCDebug(qLcEglfsKmsDebug, "Using layer %p", layer);

    if (!m_integration->m_funcs->stream_consumer_output(display, m_egl_stream, layer))
        qWarning("resetSurface: Unable to connect stream");

    m_config = QEglFSDeviceIntegration::chooseConfig(display, m_integration->surfaceFormatFor(window()->requestedFormat()));
    m_format = q_glFormatFromConfig(display, m_config);
    qCDebug(qLcEglfsKmsDebug) << "Stream producer format is" << m_format;

    const int w = cur_screen->rawGeometry().width();
    const int h = cur_screen->rawGeometry().height();
    qCDebug(qLcEglfsKmsDebug, "Creating stream producer surface of size %dx%d", w, h);

    const EGLint stream_producer_attribs[] = {
        EGL_WIDTH,  w,
        EGL_HEIGHT, h,
        EGL_NONE
    };

    m_surface = m_integration->m_funcs->create_stream_producer_surface(display, m_config, m_egl_stream, stream_producer_attribs);
    if (m_surface == EGL_NO_SURFACE)
        return;

    qCDebug(qLcEglfsKmsDebug, "Created stream producer surface %p", m_surface);
}
Esempio n. 20
0
// ### move this to qnetworkcookie_p.h and share with qnetworkaccesshttpbackend
static QPair<QByteArray, QByteArray> nextField(const QByteArray &text, int &position, bool isNameValue)
{
    // format is one of:
    //    (1)  token
    //    (2)  token = token
    //    (3)  token = quoted-string
    int i;
    const int length = text.length();
    position = nextNonWhitespace(text, position);

    // parse the first part, before the equal sign
    for (i = position; i < length; ++i) {
        register char c = text.at(i);
        if (c == ';' || c == '=')
            break;
    }

    QByteArray first = text.mid(position, i - position).trimmed();
    position = i;

    if (first.isEmpty())
        return qMakePair(QByteArray(), QByteArray());
    if (i == length || text.at(i) != '=')
        // no equal sign, we found format (1)
        return qMakePair(first, QByteArray());

    QByteArray second;
    second.reserve(32);         // arbitrary but works for most cases

    i = nextNonWhitespace(text, position + 1);
    if (i < length && text.at(i) == '"') {
        // a quote, we found format (3), where:
        // quoted-string  = ( <"> *(qdtext | quoted-pair ) <"> )
        // qdtext         = <any TEXT except <">>
        // quoted-pair    = "\" CHAR

        // If it is NAME=VALUE, retain the value as is
        // refer to http://bugreports.qt-project.org/browse/QTBUG-17746
        if (isNameValue)
            second += '"';
        ++i;
        while (i < length) {
            register char c = text.at(i);
            if (c == '"') {
                // end of quoted text
                if (isNameValue)
                    second += '"';
                break;
            } else if (c == '\\') {
                if (isNameValue)
                    second += '\\';
                ++i;
                if (i >= length)
                    // broken line
                    return qMakePair(QByteArray(), QByteArray());
                c = text.at(i);
            }

            second += c;
            ++i;
        }

        for ( ; i < length; ++i) {
            register char c = text.at(i);
            if (c == ';')
                break;
        }
        position = i;
    } else {
        // no quote, we found format (2)
        position = i;
        for ( ; i < length; ++i) {
            register char c = text.at(i);
            // for name value pairs, we want to parse until reaching the next ';'
            // and not break when reaching a space char
            if (c == ';' || ((isNameValue && (c == '\n' || c == '\r')) || (!isNameValue && isLWS(c))))
                break;
        }

        second = text.mid(position, i - position).trimmed();
        position = i;
    }

    if (second.isNull())
        second.resize(0); // turns into empty-but-not-null
    return qMakePair(first, second);
}
Esempio n. 21
0
QT_USE_NAMESPACE

int main(int argc, char **argv)
{
    CoInitialize(0);

    enum State {
        Default = 0,
            OutOption
    } state;
    state = Default;
    
    QByteArray outname;
    QByteArray object;
    
    for (int a = 1; a < argc; ++a) {
        QByteArray arg(argv[a]);
        const char first = arg[0];
        switch(state) {
        case Default:
            if (first == '-' || first == '/') {
                arg = arg.mid(1);
                arg.toLower();
                if (arg == "o")
                    state = OutOption;
                else if (arg == "v") {
                    qWarning("dumpdoc: Version 1.0");
                    return 0;
                } else if (arg == "h") {
                    qWarning("dumpdoc Usage:\n\tdumpdoc object [-o <file>]"
                        "              \n\tobject   : object[/subobject]*"
                        "              \n\tsubobject: property\n"
                        "      \nexample:\n\tdumpdoc Outlook.Application/Session/CurrentUser -o outlook.html");
                    return 0;
                }
            } else {
                object = arg;
            }
            break;
        case OutOption:
            outname = arg;
            state = Default;
            break;
            
        default:
            break;
        }
    }
    
    if (object.isEmpty()) {
        qWarning("dumpdoc: No object name provided.\n"
            "         Use -h for help.");
        return -1;
    }
    QFile outfile;
    if (!outname.isEmpty()) {
        outfile.setFileName(QString::fromLatin1(outname.constData()));
        if (!outfile.open(QIODevice::WriteOnly | QIODevice::Text)) {
            qWarning("dumpdoc: Could not open output file '%s'", outname.data());
        }
    } else {
        outfile.open(stdout, QIODevice::WriteOnly);
    }
    QTextStream out(&outfile);
    
    QByteArray subobject = object;
    int index = subobject.indexOf('/');
    if (index != -1)
        subobject = subobject.left(index);
    
    QAxObject topobject(QString::fromLatin1(subobject.constData()));
    
    if (topobject.isNull()) {
        qWarning("dumpdoc: Could not instantiate COM object '%s'", subobject.data());
        return -2;
    }
    
    QAxObject *axobject = &topobject;
    while (index != -1 && axobject) {
        index++;
        subobject = object.mid(index);
        if (object.indexOf('/', index) != -1) {
            int oldindex = index;
            index = object.indexOf('/', index);
            subobject = object.mid(oldindex, index-oldindex);	    
        } else {
            index = -1;
        }
        
        axobject = axobject->querySubObject(subobject);
    }
    if (!axobject || axobject->isNull()) {
        qWarning("dumpdoc: Subobject '%s' does not exist in '%s'", subobject.data(), object.data());
        return -3;
    }
    
    QString docu = axobject->generateDocumentation();
    out << docu;
    return 0;
}
Esempio n. 22
0
QList<QNetworkCookie> QNetworkCookiePrivate::parseSetCookieHeaderLine(const QByteArray &cookieString)
{
    // According to http://wp.netscape.com/newsref/std/cookie_spec.html,<
    // the Set-Cookie response header is of the format:
    //
    //   Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure
    //
    // where only the NAME=VALUE part is mandatory
    //
    // We do not support RFC 2965 Set-Cookie2-style cookies

    QList<QNetworkCookie> result;
    QDateTime now = QDateTime::currentDateTime().toUTC();

    int position = 0;
    const int length = cookieString.length();
    while (position < length) {
        QNetworkCookie cookie;

        // The first part is always the "NAME=VALUE" part
        QPair<QByteArray,QByteArray> field = nextField(cookieString, position, true);
        if (field.first.isEmpty() || field.second.isNull())
            // parsing error
            break;
        cookie.setName(field.first);
        cookie.setValue(field.second);

        position = nextNonWhitespace(cookieString, position);
        while (position < length) {
            switch (cookieString.at(position++)) {
            case ';':
                // new field in the cookie
                field = nextField(cookieString, position, false);
                field.first = field.first.toLower(); // everything but the NAME=VALUE is case-insensitive

                if (field.first == "expires") {
                    position -= field.second.length();
                    int end;
                    for (end = position; end < length; ++end)
                        if (isValueSeparator(cookieString.at(end)))
                            break;

                    QByteArray dateString = cookieString.mid(position, end - position).trimmed();
                    position = end;
                    QDateTime dt = parseDateString(dateString.toLower());
                    if (!dt.isValid()) {
                        return result;
                    }
                    cookie.setExpirationDate(dt);
                } else if (field.first == "domain") {
                    QByteArray rawDomain = field.second;
                    QString maybeLeadingDot;
                    if (rawDomain.startsWith('.')) {
                        maybeLeadingDot = QLatin1Char('.');
                        rawDomain = rawDomain.mid(1);
                    }

                    QString normalizedDomain = QUrl::fromAce(QUrl::toAce(QString::fromUtf8(rawDomain)));
                    if (normalizedDomain.isEmpty() && !rawDomain.isEmpty())
                        return result;
                    cookie.setDomain(maybeLeadingDot + normalizedDomain);
                } else if (field.first == "max-age") {
                    bool ok = false;
                    int secs = field.second.toInt(&ok);
                    if (!ok)
                        return result;
                    cookie.setExpirationDate(now.addSecs(secs));
                } else if (field.first == "path") {
                    QString path = QUrl::fromPercentEncoding(field.second);
                    cookie.setPath(path);
                } else if (field.first == "secure") {
                    cookie.setSecure(true);
                } else if (field.first == "httponly") {
                    cookie.setHttpOnly(true);
                } else if (field.first == "comment") {
                    //cookie.setComment(QString::fromUtf8(field.second));
                } else if (field.first == "version") {
                    if (field.second != "1") {
                        // oops, we don't know how to handle this cookie
                        return result;
                    }
                } else {
                    // got an unknown field in the cookie
                    // what do we do?
                }

                position = nextNonWhitespace(cookieString, position);
            }
        }

        if (!cookie.name().isEmpty())
            result += cookie;
    }

    return result;
}
Esempio n. 23
0
void ContextWidget::setWide(bool w)
{
    if (w==isWide) {
        return;
    }

    isWide=w;
    if (w) {
        if (standardContext->layout()) {
            delete standardContext->layout();
        }
        QHBoxLayout *l=new QHBoxLayout(standardContext);
        standardContext->setLayout(l);
        int m=l->margin()/2;
        l->setMargin(0);
        if (stack) {
            stack->setVisible(false);
            viewSelector->setVisible(false);
            stack->removeWidget(artist);
            stack->removeWidget(album);
            stack->removeWidget(song);
            artist->setVisible(true);
            album->setVisible(true);
            song->setVisible(true);
        }
        l->addItem(new QSpacerItem(m, m, QSizePolicy::Fixed, QSizePolicy::Fixed));
        QByteArray state;
        bool resetSplitter=splitter;
        if (!splitter) {
            splitter=new ThinSplitter(standardContext);
            state=Settings::self()->contextSplitterState();
        }
        l->addWidget(splitter);
        artist->setParent(splitter);
        album->setParent(splitter);
        song->setParent(splitter);
        splitter->addWidget(artist);
        splitter->addWidget(album);
        splitter->setVisible(true);
        splitter->addWidget(song);
        if (resetSplitter) {
            splitter->reset();
        } else if (!state.isEmpty()) {
            splitter->restoreState(state);
        }
    } else {
        if (standardContext->layout()) {
            delete standardContext->layout();
        }
        QGridLayout *l=new QGridLayout(standardContext);
        standardContext->setLayout(l);
        int m=l->margin()/2;
        l->setMargin(0);
        l->setSpacing(0);
        if (!stack) {
            stack=new QStackedWidget(standardContext);
        }
        if (!viewSelector) {
            viewSelector=new ViewSelector(standardContext);
            viewSelector->addItem(i18n("&Artist"), "artist");
            viewSelector->addItem(i18n("Al&bum"), "album");
            viewSelector->addItem(i18n("&Track"), "song");
            viewSelector->setPalette(palette());
            connect(viewSelector, SIGNAL(activated(int)), stack, SLOT(setCurrentIndex(int)));
        }
        if (splitter) {
            splitter->setVisible(false);
        }
        stack->setVisible(true);
        viewSelector->setVisible(true);
        artist->setParent(stack);
        album->setParent(stack);
        song->setParent(stack);
        stack->addWidget(artist);
        stack->addWidget(album);
        stack->addWidget(song);
        l->addItem(new QSpacerItem(m, m, QSizePolicy::Fixed, QSizePolicy::Fixed), 0, 0, 1, 1);
        l->addWidget(stack, 0, 1, 1, 1);
        l->addWidget(viewSelector, 1, 0, 1, 2);
        QString lastSaved=Settings::self()->contextSlimPage();
        if (!lastSaved.isEmpty()) {
            for (int i=0; i<viewSelector->count(); ++i) {
                if (viewSelector->itemData(i).toString()==lastSaved) {
                    viewSelector->setCurrentIndex(i);
                    stack->setCurrentIndex(i);
                    break;
                }
            }
        }
    }
}
Esempio n. 24
0
/**
 * \fn UPNPScanner::ParseDescription(const QUrl&, QNetworkReply*)
 *  Parse the device description XML return my a media server.
 */
bool UPNPScanner::ParseDescription(const QUrl &url, QNetworkReply *reply)
{
    if (url.isEmpty() || !reply)
        return false;

    QByteArray data = reply->readAll();
    if (data.isEmpty())
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("%1 returned an empty device description.")
            .arg(url.toString()));
        return false;
    }

    // parse the device description
    QString controlURL = QString();
    QString eventURL   = QString();
    QString friendlyName = QString("Unknown");
    QString URLBase = QString();

    QDomDocument doc;
    QString errorMessage;
    int errorLine   = 0;
    int errorColumn = 0;
    if (!doc.setContent(data, false, &errorMessage, &errorLine, &errorColumn))
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("Failed to parse device description from %1")
            .arg(url.toString()));
        LOG(VB_GENERAL, LOG_ERR, LOC + QString("Line: %1 Col: %2 Error: '%3'")
            .arg(errorLine).arg(errorColumn).arg(errorMessage));
        return false;
    }

    QDomElement docElem = doc.documentElement();
    QDomNode n = docElem.firstChild();
    while (!n.isNull())
    {
        QDomElement e1 = n.toElement();
        if (!e1.isNull())
        {
            if(e1.tagName() == "device")
                ParseDevice(e1, controlURL, eventURL, friendlyName);
            if (e1.tagName() == "URLBase")
                URLBase = e1.text();
        }
        n = n.nextSibling();
    }

    if (controlURL.isEmpty())
    {
        LOG(VB_UPNP, LOG_ERR, LOC +
            QString("Failed to parse device description for %1")
            .arg(url.toString()));
        return false;
    }

    // if no URLBase was provided, use the known url
    if (URLBase.isEmpty())
        URLBase = url.toString(QUrl::RemovePath | QUrl::RemoveFragment |
                               QUrl::RemoveQuery);

    // strip leading slashes off the controlURL
    while (!controlURL.isEmpty() && controlURL.left(1) == "/")
        controlURL = controlURL.mid(1);

    // strip leading slashes off the eventURL
    //while (!eventURL.isEmpty() && eventURL.left(1) == "/")
    //    eventURL = eventURL.mid(1);

    // strip trailing slashes off URLBase
    while (!URLBase.isEmpty() && URLBase.right(1) == "/")
        URLBase = URLBase.mid(0, URLBase.size() - 1);

    controlURL = URLBase + "/" + controlURL;
    QString fulleventURL = URLBase + "/" + eventURL;

    LOG(VB_UPNP, LOG_INFO, LOC + QString("Control URL for %1 at %2")
        .arg(friendlyName).arg(controlURL));
    LOG(VB_UPNP, LOG_INFO, LOC + QString("Event URL for %1 at %2")
        .arg(friendlyName).arg(fulleventURL));

    // update the server details. If the server has gone away since the request
    // was posted, this will silently fail and we won't try again
    QString usn;
    QUrl qeventurl = QUrl(fulleventURL);
    int timeout = 0;

    m_lock.lock();
    QHashIterator<QString,MediaServer*> it(m_servers);
    while (it.hasNext())
    {
        it.next();
        if (it.value()->m_URL == url)
        {
            usn = it.key();
            QUrl qcontrolurl(controlURL);
            it.value()->m_controlURL   = qcontrolurl;
            it.value()->m_eventSubURL  = qeventurl;
            it.value()->m_eventSubPath = eventURL;
            it.value()->m_friendlyName = friendlyName;
            it.value()->m_name         = friendlyName;
            break;
        }
    }

    if (m_subscription && !usn.isEmpty())
    {
        timeout = m_subscription->Subscribe(usn, qeventurl, eventURL);
        m_servers[usn]->m_subscribed = (timeout > 0);
    }
    m_lock.unlock();

    if (timeout > 0)
    {
        LOG(VB_GENERAL, LOG_INFO, LOC +
            QString("Subscribed for %1 seconds to %2") .arg(timeout).arg(usn));
        ScheduleRenewal(usn, timeout);
        // we only scan servers we are subscribed to - and the scan is now
        // incomplete
        m_scanComplete = false;
    }

    Debug();
    return true;
}
Esempio n. 25
0
File: paste.cpp Progetto: KDE/kio
KIOWIDGETS_EXPORT bool KIO::isClipboardDataCut(const QMimeData *mimeData)
{
    const QByteArray a = mimeData->data(QStringLiteral("application/x-kde-cutselection"));
    return (!a.isEmpty() && a.at(0) == '1');
}
Esempio n. 26
0
/**
 * \fn UPNPScanner::ParseBrowse(const QUrl&, QNetworkReply*)
 *  Parse the XML returned from Content Directory Service browse request.
 */
void UPNPScanner::ParseBrowse(const QUrl &url, QNetworkReply *reply)
{
    QByteArray data = reply->readAll();
    if (data.isEmpty())
        return;

    // Open the response for parsing
    QDomDocument *parent = new QDomDocument();
    QString errorMessage;
    int errorLine   = 0;
    int errorColumn = 0;
    if (!parent->setContent(data, false, &errorMessage, &errorLine,
                            &errorColumn))
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("DIDL Parse error, Line: %1 Col: %2 Error: '%3'")
            .arg(errorLine).arg(errorColumn).arg(errorMessage));
        delete parent;
        return;
    }

    LOG(VB_UPNP, LOG_INFO, "\n\n" + parent->toString(4) + "\n\n");

    // pull out the actual result
    QDomDocument *result = NULL;
    uint num      = 0;
    uint total    = 0;
    uint updateid = 0;
    QDomElement docElem = parent->documentElement();
    QDomNode n = docElem.firstChild();
    if (!n.isNull())
        result = FindResult(n, num, total, updateid);
    delete parent;

    if (!result || num < 1 || total < 1)
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("Failed to find result for %1") .arg(url.toString()));
        return;
    }

    // determine the 'server' which requested the browse
    m_lock.lock();

    MediaServer* server = NULL;
    QHashIterator<QString,MediaServer*> it(m_servers);
    while (it.hasNext())
    {
        it.next();
        if (url == it.value()->m_controlURL)
        {
            server = it.value();
            break;
        }
    }

    // discard unmatched responses
    if (!server)
    {
        m_lock.unlock();
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("Received unknown response for %1").arg(url.toString()));
        return;
    }

    // check the update ID
    if (server->m_systemUpdateID != (int)updateid)
    {
        // if this is not the root container, this browse will now fail
        // as the appropriate parentID will not be found
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("%1 updateID changed during browse (old %2 new %3)")
            .arg(server->m_friendlyName).arg(server->m_systemUpdateID)
            .arg(updateid));
        m_scanComplete &= server->ResetContent(updateid);
        Debug();
    }

    // find containers (directories) and actual items and add them
    docElem = result->documentElement();
    n = docElem.firstChild();
    while (!n.isNull())
    {
        FindItems(n, *server);
        n = n.nextSibling();
    }
    delete result;

    m_lock.unlock();
}
Esempio n. 27
0
QString QBasicFontDatabase::fontNameFromTTFile(const QString &filename)
{
    QFile f(filename);
    QString retVal;
    qint64 bytesRead;
    qint64 bytesToRead;

    if (f.open(QIODevice::ReadOnly)) {
        OFFSET_TABLE ttOffsetTable;
        bytesToRead = sizeof(OFFSET_TABLE);
        bytesRead = f.read((char*)&ttOffsetTable, bytesToRead);
        if (bytesToRead != bytesRead)
            return retVal;
        ttOffsetTable.numTables = qFromBigEndian(ttOffsetTable.numTables);
        ttOffsetTable.majorVersion = qFromBigEndian(ttOffsetTable.majorVersion);
        ttOffsetTable.minorVersion = qFromBigEndian(ttOffsetTable.minorVersion);

        if (ttOffsetTable.majorVersion != 1 || ttOffsetTable.minorVersion != 0)
            return retVal;

        TABLE_DIRECTORY tblDir;
        bool found = false;

        for (int i = 0; i < ttOffsetTable.numTables; i++) {
            bytesToRead = sizeof(TABLE_DIRECTORY);
            bytesRead = f.read((char*)&tblDir, bytesToRead);
            if (bytesToRead != bytesRead)
                return retVal;
            if (qFromBigEndian(tblDir.tag) == MAKE_TAG('n', 'a', 'm', 'e')) {
                found = true;
                tblDir.length = qFromBigEndian(tblDir.length);
                tblDir.offset = qFromBigEndian(tblDir.offset);
                break;
            }
        }

        if (found) {
            f.seek(tblDir.offset);
            NAME_TABLE_HEADER ttNTHeader;
            bytesToRead = sizeof(NAME_TABLE_HEADER);
            bytesRead = f.read((char*)&ttNTHeader, bytesToRead);
            if (bytesToRead != bytesRead)
                return retVal;
            ttNTHeader.nrCount = qFromBigEndian(ttNTHeader.nrCount);
            ttNTHeader.storageOffset = qFromBigEndian(ttNTHeader.storageOffset);
            NAME_RECORD ttRecord;
            found = false;

            for (int i = 0; i < ttNTHeader.nrCount; i++) {
                bytesToRead = sizeof(NAME_RECORD);
                bytesRead = f.read((char*)&ttRecord, bytesToRead);
                if (bytesToRead != bytesRead)
                    return retVal;
                ttRecord.nameID = qFromBigEndian(ttRecord.nameID);
                if (ttRecord.nameID == 1) {
                    ttRecord.stringLength = qFromBigEndian(ttRecord.stringLength);
                    ttRecord.stringOffset = qFromBigEndian(ttRecord.stringOffset);
                    int nPos = f.pos();
                    f.seek(tblDir.offset + ttRecord.stringOffset + ttNTHeader.storageOffset);

                    QByteArray nameByteArray = f.read(ttRecord.stringLength);
                    if (!nameByteArray.isEmpty()) {
                        if (ttRecord.encodingID == 256 || ttRecord.encodingID == 768) {
                            //This is UTF-16 in big endian
                            int stringLength = ttRecord.stringLength / 2;
                            retVal.resize(stringLength);
                            QChar *data = retVal.data();
                            const ushort *srcData = (const ushort *)nameByteArray.data();
                            for (int i = 0; i < stringLength; ++i)
                                data[i] = qFromBigEndian(srcData[i]);
                            return retVal;
                        } else if (ttRecord.encodingID == 0) {
                            //This is Latin1
                            retVal = QString::fromLatin1(nameByteArray);
                        } else {
                            qWarning("Could not retrieve Font name from file: %s", qPrintable(QDir::toNativeSeparators(filename)));
                        }
                        break;
                    }
                    f.seek(nPos);
                }
            }
        }
        f.close();
    }
    return retVal;
}
Esempio n. 28
0
QT_BEGIN_NAMESPACE

/*!
    \class QDBusReply
    \inmodule QtDBus
    \since 4.2

    \brief The QDBusReply class stores the reply for a method call to a remote object.

    A QDBusReply object is a subset of the QDBusMessage object that represents a method call's
    reply. It contains only the first output argument or the error code and is used by
    QDBusInterface-derived classes to allow returning the error code as the function's return
    argument.

    It can be used in the following manner:
    \snippet doc/src/snippets/code/src_qdbus_qdbusreply.cpp 0

    If the remote method call cannot fail, you can skip the error checking:
    \snippet doc/src/snippets/code/src_qdbus_qdbusreply.cpp 1

    However, if it does fail under those conditions, the value returned by QDBusReply::value() is
    a default-constructed value. It may be indistinguishable from a valid return value.

    QDBusReply objects are used for remote calls that have no output
    arguments or return values (i.e., they have a "void" return
    type). Use the isValid() function to test if the reply succeeded.

    \sa QDBusMessage, QDBusInterface
*/

/*!
    \fn QDBusReply::QDBusReply(const QDBusMessage &reply)
    Automatically construct a QDBusReply object from the reply message \a reply, extracting the
    first return value from it if it is a success reply.
*/

/*!
    \fn QDBusReply::QDBusReply(const QDBusPendingReply<T> &reply)
    Constructs a QDBusReply object from the pending reply message, \a reply.
*/

/*!
    \fn QDBusReply::QDBusReply(const QDBusPendingCall &pcall)
    Automatically construct a QDBusReply object from the asynchronous
    pending call \a pcall. If the call isn't finished yet, QDBusReply
    will call QDBusPendingCall::waitForFinished(), which is a blocking
    operation.

    If the return types patch, QDBusReply will extract the first
    return argument from the reply.
*/

/*!
    \fn QDBusReply::QDBusReply(const QDBusError &error)
    Constructs an error reply from the D-Bus error code given by \a error.
*/

/*!
    \fn QDBusReply::operator=(const QDBusReply &other)
    Makes this object be a copy of the object \a other.
*/

/*!
    \fn QDBusReply::operator=(const QDBusError &error)
    Sets this object to contain the error code given by \a error. You
    can later access it with error().
*/

/*!
    \fn QDBusReply::operator=(const QDBusMessage &message)

    Makes this object contain the reply specified by message \a
    message. If \a message is an error message, this function will
    copy the error code and message into this object

    If \a message is a standard reply message and contains at least
    one parameter, it will be copied into this object, as long as it
    is of the correct type. If it's not of the same type as this
    QDBusError object, this function will instead set an error code
    indicating a type mismatch.
*/

/*!
    \fn QDBusReply::operator=(const QDBusPendingCall &pcall)

    Makes this object contain the reply specified by the pending
    asynchronous call \a pcall. If the call is not finished yet, this
    function will call QDBusPendingCall::waitForFinished() to block
    until the reply arrives.

    If \a pcall finishes with an error message, this function will
    copy the error code and message into this object

    If \a pcall finished with a standard reply message and contains at
    least one parameter, it will be copied into this object, as long
    as it is of the correct type. If it's not of the same type as this
    QDBusError object, this function will instead set an error code
    indicating a type mismatch.
*/

/*!
    \fn bool QDBusReply::isValid() const

    Returns true if no error occurred; otherwise, returns false.

    \sa error()
*/

/*!
    \fn QDBusReply::error()

    Returns the error code that was returned from the remote function call. If the remote call did
    not return an error (i.e., if it succeeded), then the QDBusError object that is returned will
    not be a valid error code (QDBusError::isValid() will return false).

    \sa isValid()
*/

/*!
    \fn QDBusReply::value() const
    Returns the remote function's calls return value. If the remote call returned with an error,
    the return value of this function is undefined and may be undistinguishable from a valid return
    value.

    This function is not available if the remote call returns \c void.
*/

/*!
    \fn QDBusReply::operator Type() const
    Returns the same as value().

    This function is not available if the remote call returns \c void.
*/

/*!
    \internal
    Fills in the QDBusReply data \a error and \a data from the reply message \a reply.
*/
void qDBusReplyFill(const QDBusMessage &reply, QDBusError &error, QVariant &data)
{
    error = reply;

    if (error.isValid()) {
        data = QVariant();      // clear it
        return;
    }

    if (reply.arguments().count() >= 1 && reply.arguments().at(0).userType() == data.userType()) {
        data = reply.arguments().at(0);
        return;
    }

    const char *expectedSignature = QDBusMetaType::typeToSignature(data.userType());
    const char *receivedType = 0;
    QByteArray receivedSignature;

    if (reply.arguments().count() >= 1) {
        if (reply.arguments().at(0).userType() == QDBusMetaTypeId::argument) {
            // compare signatures instead
            QDBusArgument arg = qvariant_cast<QDBusArgument>(reply.arguments().at(0));
            receivedSignature = arg.currentSignature().toLatin1();
            if (receivedSignature == expectedSignature) {
                // matched. Demarshall it
                QDBusMetaType::demarshall(arg, data.userType(), data.data());
                return;
            }
        } else {
            // not an argument and doesn't match?
            int type = reply.arguments().at(0).userType();
            receivedType = QVariant::typeToName(QVariant::Type(type));
            receivedSignature = QDBusMetaType::typeToSignature(type);
        }
    }

    // error
    if (receivedSignature.isEmpty())
        receivedSignature = "no signature";
    QString errorMsg;
    if (receivedType) {
        errorMsg = QString::fromLatin1("Unexpected reply signature: got \"%1\" (%4), "
                                         "expected \"%2\" (%3)")
                   .arg(QLatin1String(receivedSignature),
                        QLatin1String(expectedSignature),
                        QLatin1String(data.typeName()),
                        QLatin1String(receivedType));
    } else {
        errorMsg = QString::fromLatin1("Unexpected reply signature: got \"%1\", "
                                         "expected \"%2\" (%3)")
                   .arg(QLatin1String(receivedSignature),
                        QLatin1String(expectedSignature),
                        QLatin1String(data.typeName()));
    }

    error = QDBusError(QDBusError::InvalidSignature, errorMsg);
    data = QVariant();      // clear it
}
Esempio n. 29
0
int QgsGml::getFeatures( const QString& uri, QGis::WkbType* wkbType, QgsRectangle* extent, const QString& userName, const QString& password , const QString& authcfg )
{
    mUri = uri;
    mWkbType = wkbType;

    XML_Parser p = XML_ParserCreateNS( nullptr, NS_SEPARATOR );
    XML_SetUserData( p, this );
    XML_SetElementHandler( p, QgsGml::start, QgsGml::end );
    XML_SetCharacterDataHandler( p, QgsGml::chars );

    //start with empty extent
    mExtent.setMinimal();

    QNetworkRequest request( mUri );
    if ( !authcfg.isEmpty() )
    {
        if ( !QgsAuthManager::instance()->updateNetworkRequest( request, authcfg ) )
        {
            QgsMessageLog::logMessage(
                tr( "GML Getfeature network request update failed for authcfg %1" ).arg( authcfg ),
                tr( "Network" ),
                QgsMessageLog::CRITICAL
            );
            return 1;
        }
    }
    else if ( !userName.isNull() || !password.isNull() )
    {
        request.setRawHeader( "Authorization", "Basic " + QString( "%1:%2" ).arg( userName, password ).toAscii().toBase64() );
    }
    QNetworkReply* reply = QgsNetworkAccessManager::instance()->get( request );

    connect( reply, SIGNAL( finished() ), this, SLOT( setFinished() ) );
    connect( reply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( handleProgressEvent( qint64, qint64 ) ) );

    //find out if there is a QGIS main window. If yes, display a progress dialog
    QProgressDialog* progressDialog = nullptr;
    QWidget* mainWindow = nullptr;
    QWidgetList topLevelWidgets = qApp->topLevelWidgets();
    for ( QWidgetList::const_iterator it = topLevelWidgets.constBegin(); it != topLevelWidgets.constEnd(); ++it )
    {
        if (( *it )->objectName() == "QgisApp" )
        {
            mainWindow = *it;
            break;
        }
    }
    if ( mainWindow )
    {
        progressDialog = new QProgressDialog( tr( "Loading GML data\n%1" ).arg( mTypeName ), tr( "Abort" ), 0, 0, mainWindow );
        progressDialog->setWindowModality( Qt::ApplicationModal );
        connect( this, SIGNAL( dataReadProgress( int ) ), progressDialog, SLOT( setValue( int ) ) );
        connect( this, SIGNAL( totalStepsUpdate( int ) ), progressDialog, SLOT( setMaximum( int ) ) );
        connect( progressDialog, SIGNAL( canceled() ), this, SLOT( setFinished() ) );
        progressDialog->show();
    }

    int atEnd = 0;
    while ( !atEnd )
    {
        if ( mFinished )
        {
            atEnd = 1;
        }
        QByteArray readData = reply->readAll();
        if ( !readData.isEmpty() )
        {
            if ( XML_Parse( p, readData.constData(), readData.size(), atEnd ) == 0 )
            {
                XML_Error errorCode = XML_GetErrorCode( p );
                QString errorString = tr( "Error: %1 on line %2, column %3" )
                                      .arg( XML_ErrorString( errorCode ) )
                                      .arg( XML_GetCurrentLineNumber( p ) )
                                      .arg( XML_GetCurrentColumnNumber( p ) );
                QgsMessageLog::logMessage( errorString, tr( "WFS" ) );
            }
        }
        QCoreApplication::processEvents();
    }

    QNetworkReply::NetworkError replyError = reply->error();
    QString replyErrorString = reply->errorString();

    delete reply;
    delete progressDialog;

    if ( replyError )
    {
        QgsMessageLog::logMessage(
            tr( "GML Getfeature network request failed with error: %1" ).arg( replyErrorString ),
            tr( "Network" ),
            QgsMessageLog::CRITICAL
        );
        return 1;
    }

    if ( *mWkbType != QGis::WKBNoGeometry )
    {
        if ( mExtent.isEmpty() )
        {
            //reading of bbox from the server failed, so we calculate it less efficiently by evaluating the features
            calculateExtentFromFeatures();
        }
    }

    XML_ParserFree( p );

    if ( extent )
        *extent = mExtent;

    return 0;
}
Esempio n. 30
0
QByteArray MIMECodec::decodeBase64(const QByteArray &buf)
{
  if (buf.isEmpty() || buf.size() < 4)
    return QByteArray();

  unsigned bufSize = buf.size();
  QByteArray outbuf(((bufSize + 3) / 4) * 3);
  const char *ptrBuf = buf.data();

#ifdef _QTWIN_

  int index = 0, oindex = 0;
#else

  unsigned index = 0, oindex = 0;
#endif

  unsigned char e1 = 0, e2 = 0, e3 = 0, e4 = 0;
  unsigned char c1 = 0, c2 = 0, c3 = 0;

  const QCString table(base64table);
  int revbase64table[256];
  {
    for (int i = 0; i < 256; i++)
      revbase64table[i] = -1;
  }
  {
    for (int i = 65; i < 91; i++)
      revbase64table[i] = i - 65;
  }
  {
    for (int i = 97; i < 123; i++)
      revbase64table[i] = i - 71;
  }
  {
    for (int i = 48; i < 58; i++)
      revbase64table[i] = i + 4;
  }
  revbase64table[43] = 62;
  revbase64table[47] = 63;
  revbase64table[61] = 64;

  while (index < bufSize) {
    if (revbase64table[(int)ptrBuf[index] ] == -1) {
      index++;
    } else {
      e1 = ptrBuf[index++];
      e2 = index < bufSize ? ptrBuf[index++] : 'A';
      e3 = index < bufSize ? ptrBuf[index++] : 'A';
      e4 = index < bufSize ? ptrBuf[index++] : 'A';

      e1 = revbase64table[e1];
      e2 = revbase64table[e2];
      e3 = revbase64table[e3];
      e4 = revbase64table[e4];

      c1 = e1 * 4 + (e2 & 48) / 16;
      c2 = (e2 & 15) * 16 + (e3 & 60) / 4;
      c3 = (e3 & 3) * 64 + e4;

      outbuf[oindex++] = c1;
      outbuf[oindex++] = c2;
      outbuf[oindex++] = c3;
    }
  }

  unsigned last = 0;
  for (unsigned i = bufSize - 1; i; i--)
    if (revbase64table[(int)ptrBuf[i] ] != -1) {
      last = i;
      break;
    }

  if (ptrBuf[last - 1] == '=' &&
      ptrBuf[last]   == '=')
    oindex--;
  else if (ptrBuf[last] != '=')
    oindex++;

  // do we need it ??
  if (outbuf.size() >= oindex)
    outbuf[oindex - 1] = '\0';

  outbuf.truncate(oindex - 1);

  return outbuf;
}