Initial commit to the repository
authorJuho Vähä-Herttua <juhovh@iki.fi>
Fri, 9 Mar 2012 12:10:51 +0000 (14:10 +0200)
committerJuho Vähä-Herttua <juhovh@iki.fi>
Wed, 16 May 2012 21:31:57 +0000 (00:31 +0300)
124 files changed:
.gitignore [new file with mode: 0644]
AirTV-Qt/AirTV.icns [new file with mode: 0644]
AirTV-Qt/AirTV.ico [new file with mode: 0644]
AirTV-Qt/AirTV.pro [new file with mode: 0644]
AirTV-Qt/AirTV.qrc [new file with mode: 0644]
AirTV-Qt/AirTV.rc [new file with mode: 0644]
AirTV-Qt/audiooutput.cpp [new file with mode: 0644]
AirTV-Qt/audiooutput.h [new file with mode: 0644]
AirTV-Qt/images/airtv.svg [new file with mode: 0644]
AirTV-Qt/main.cpp [new file with mode: 0644]
AirTV-Qt/mainapplication.cpp [new file with mode: 0644]
AirTV-Qt/mainapplication.h [new file with mode: 0644]
AirTV-Qt/mainwindow.ui [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/INSTALL.TXT [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/README.TXT [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/buildlib/buildlib.pro [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/common.pri [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/configure [new file with mode: 0755]
AirTV-Qt/qtsingleapplication/configure.bat [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/doc/html/classic.css [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/doc/html/images/qt-logo.png [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/doc/html/index.html [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication-example-loader.html [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication-example-trivial.html [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication-members.html [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication-obsolete.html [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication.dcf [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication.html [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication.index [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication.qhp [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/doc/html/qtsinglecoreapplication-example-console.html [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/doc/html/qtsinglecoreapplication-members.html [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/doc/html/qtsinglecoreapplication.html [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/doc/images/qt-logo.png [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/doc/index.qdoc [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/examples/console/console.pro [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/examples/console/console.qdoc [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/examples/console/main.cpp [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/examples/examples.pro [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/examples/loader/file1.qsl [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/examples/loader/file2.qsl [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/examples/loader/loader.pro [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/examples/loader/loader.qdoc [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/examples/loader/main.cpp [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/examples/trivial/main.cpp [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/examples/trivial/trivial.pro [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/examples/trivial/trivial.qdoc [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/qtsingleapplication.pro [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/src/QtLockedFile [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/src/QtSingleApplication [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/src/qtlocalpeer.cpp [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/src/qtlocalpeer.h [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/src/qtlockedfile.cpp [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/src/qtlockedfile.h [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/src/qtlockedfile_unix.cpp [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/src/qtlockedfile_win.cpp [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/src/qtsingleapplication.cpp [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/src/qtsingleapplication.h [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/src/qtsingleapplication.pri [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/src/qtsinglecoreapplication.cpp [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/src/qtsinglecoreapplication.h [new file with mode: 0644]
AirTV-Qt/qtsingleapplication/src/qtsinglecoreapplication.pri [new file with mode: 0644]
AirTV-Qt/raopcallbackhandler.cpp [new file with mode: 0644]
AirTV-Qt/raopcallbackhandler.h [new file with mode: 0644]
AirTV-Qt/raopservice.cpp [new file with mode: 0644]
AirTV-Qt/raopservice.h [new file with mode: 0644]
Makefile [new file with mode: 0644]
README [new file with mode: 0644]
airport.key [new file with mode: 0644]
include/dnssd.h [new file with mode: 0644]
include/raop.h [new file with mode: 0644]
src/alac/alac.c [new file with mode: 0644]
src/alac/alac.h [new file with mode: 0644]
src/alac/stdint_win.h [new file with mode: 0644]
src/base64.c [new file with mode: 0644]
src/base64.h [new file with mode: 0644]
src/compat.h [new file with mode: 0644]
src/crypto/aes.c [new file with mode: 0644]
src/crypto/bigint.c [new file with mode: 0644]
src/crypto/bigint.h [new file with mode: 0644]
src/crypto/bigint_impl.h [new file with mode: 0644]
src/crypto/config.h [new file with mode: 0644]
src/crypto/crypto.h [new file with mode: 0644]
src/crypto/hmac.c [new file with mode: 0644]
src/crypto/md5.c [new file with mode: 0644]
src/crypto/os_port.h [new file with mode: 0644]
src/crypto/rc4.c [new file with mode: 0644]
src/crypto/sha1.c [new file with mode: 0644]
src/dnssd.c [new file with mode: 0644]
src/dnssd.m [new file with mode: 0644]
src/dnssdint.h [new file with mode: 0644]
src/global.h [new file with mode: 0644]
src/http_parser.c [new file with mode: 0644]
src/http_parser.h [new file with mode: 0644]
src/http_request.c [new file with mode: 0644]
src/http_request.h [new file with mode: 0644]
src/http_response.c [new file with mode: 0644]
src/http_response.h [new file with mode: 0644]
src/httpd.c [new file with mode: 0644]
src/httpd.h [new file with mode: 0644]
src/logger.c [new file with mode: 0644]
src/logger.h [new file with mode: 0644]
src/memalign.h [new file with mode: 0644]
src/netutils.c [new file with mode: 0644]
src/netutils.h [new file with mode: 0644]
src/raop.c [new file with mode: 0644]
src/raop_buffer.c [new file with mode: 0644]
src/raop_buffer.h [new file with mode: 0644]
src/raop_rtp.c [new file with mode: 0644]
src/raop_rtp.h [new file with mode: 0644]
src/rsakey.c [new file with mode: 0644]
src/rsakey.h [new file with mode: 0644]
src/rsapem.c [new file with mode: 0644]
src/rsapem.h [new file with mode: 0644]
src/sdp.c [new file with mode: 0644]
src/sdp.h [new file with mode: 0644]
src/sockets.h [new file with mode: 0644]
src/threads.h [new file with mode: 0644]
src/utils.c [new file with mode: 0644]
src/utils.h [new file with mode: 0644]
test/dnssd_test.c [new file with mode: 0644]
test/dnssd_test.m [new file with mode: 0644]
test/main.c [new file with mode: 0644]
test/shairport.c [new file with mode: 0644]

diff --git a/.gitignore b/.gitignore
new file mode 100644 (file)
index 0000000..c9c2803
--- /dev/null
@@ -0,0 +1,7 @@
+*-build-*
+*.user
+*.o
+*.DS_Store
+*.swp
+project.xcworkspace
+xcuserdata
diff --git a/AirTV-Qt/AirTV.icns b/AirTV-Qt/AirTV.icns
new file mode 100644 (file)
index 0000000..060ba2d
Binary files /dev/null and b/AirTV-Qt/AirTV.icns differ
diff --git a/AirTV-Qt/AirTV.ico b/AirTV-Qt/AirTV.ico
new file mode 100644 (file)
index 0000000..7505011
Binary files /dev/null and b/AirTV-Qt/AirTV.ico differ
diff --git a/AirTV-Qt/AirTV.pro b/AirTV-Qt/AirTV.pro
new file mode 100644 (file)
index 0000000..cfe3b4f
--- /dev/null
@@ -0,0 +1,104 @@
+#-------------------------------------------------
+#
+# Project created by QtCreator 2011-12-04T00:47:51
+#
+#-------------------------------------------------
+
+QT       += core gui multimedia phonon svg
+
+include(qtsingleapplication/src/qtsingleapplication.pri)
+
+TARGET = AirTV
+TEMPLATE = app
+ICON = AirTV.icns
+RC_FILE = AirTV.rc
+
+win32 {
+    LIBS += C:\\QtSDK\\mingw\\lib\\libws2_32.a
+    QMAKE_LFLAGS += -static-libgcc
+}
+unix:!macx {
+    LIBS += -ldns_sd
+}
+macx {
+    QMAKE_MACOSX_DEPLOYMENT_TARGET = 10.5
+}
+
+INCLUDEPATH += ../include/
+SOURCES += main.cpp\
+    ../src/utils.c \
+    ../src/sdp.c \
+    ../src/rsapem.c \
+    ../src/rsakey.c \
+    ../src/raop.c \
+    ../src/raop_rtp.c \
+    ../src/raop_buffer.c \
+    ../src/netutils.c \
+    ../src/httpd.c \
+    ../src/http_response.c \
+    ../src/http_request.c \
+    ../src/http_parser.c \
+    ../src/dnssd.c \
+    ../src/base64.c \
+    ../src/alac/alac.c \
+    ../src/crypto/sha1.c \
+    ../src/crypto/rc4.c \
+    ../src/crypto/md5.c \
+    ../src/crypto/hmac.c \
+    ../src/crypto/bigint.c \
+    ../src/crypto/aes.c \
+    audiooutput.cpp \
+    raopservice.cpp \
+    mainapplication.cpp \
+    raopcallbackhandler.cpp \
+    ../src/logger.c
+
+HEADERS  += \
+    audiooutput.h \
+    raopservice.h \
+    mainapplication.h \
+    raopcallbackhandler.h
+
+FORMS    += mainwindow.ui
+
+RESOURCES += \
+    AirTV.qrc
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/AirTV-Qt/AirTV.qrc b/AirTV-Qt/AirTV.qrc
new file mode 100644 (file)
index 0000000..2310ae5
--- /dev/null
@@ -0,0 +1,5 @@
+<RCC>
+    <qresource prefix="/icons">
+        <file alias="airtv.svg">images/airtv.svg</file>
+    </qresource>
+</RCC>
diff --git a/AirTV-Qt/AirTV.rc b/AirTV-Qt/AirTV.rc
new file mode 100644 (file)
index 0000000..bfbdddf
--- /dev/null
@@ -0,0 +1 @@
+IDI_ICON1               ICON    DISCARDABLE     "AirTV.ico"
diff --git a/AirTV-Qt/audiooutput.cpp b/AirTV-Qt/audiooutput.cpp
new file mode 100644 (file)
index 0000000..e87c60d
--- /dev/null
@@ -0,0 +1,184 @@
+#include "audiooutput.h"
+
+#include <QDebug>
+#include <QtEndian>
+#include <math.h>
+
+#define BUFFER_SIZE (64*1024)
+
+AudioOutput::AudioOutput(QObject *parent) :
+    QIODevice(parent),
+    m_initialized(false),
+    m_output(0),
+    m_volume(0.0f)
+{
+}
+
+bool AudioOutput::init(int bits, int channels, int samplerate)
+{
+    if (m_initialized) {
+        return false;
+    }
+    if (bits != 16) {
+        return false;
+    }
+
+    m_format.setSampleSize(bits);
+    m_format.setChannels(channels);
+    m_format.setFrequency(samplerate);
+    m_format.setCodec("audio/pcm");
+    m_format.setByteOrder(QAudioFormat::LittleEndian);
+    m_format.setSampleType(QAudioFormat::SignedInt);
+
+    m_initialized = setDevice(QAudioDeviceInfo::defaultOutputDevice());
+    return m_initialized;
+}
+
+bool AudioOutput::setDevice(QAudioDeviceInfo deviceInfo)
+{
+    if (!deviceInfo.isFormatSupported(m_format)) {
+        qDebug() << "Format not supported!";
+        return false;
+    }
+    m_deviceInfo = deviceInfo;
+    this->reinit();
+    return true;
+}
+
+void AudioOutput::reinit()
+{
+    bool running = false;
+    if (m_output && m_output->state() != QAudio::StoppedState) {
+        running = true;
+    }
+    this->stop();
+
+    // Reinitialize audio output
+    delete m_output;
+    m_output = 0;
+    m_output = new QAudioOutput(m_deviceInfo, m_format, this);
+
+    // Set constant values to new audio output
+    connect(m_output, SIGNAL(notify()), SLOT(notified()));
+    connect(m_output, SIGNAL(stateChanged(QAudio::State)), SLOT(stateChanged(QAudio::State)));
+    if (running) {
+        this->start();
+    }
+}
+
+void AudioOutput::start()
+{
+    if (m_output == 0 || m_output->state() != QAudio::StoppedState) {
+        return;
+    }
+    this->open(QIODevice::ReadOnly);
+    m_buffer.clear();
+    m_output->start(this);
+    m_output->suspend();
+}
+
+void AudioOutput::setVolume(float volume)
+{
+    m_volume = volume;
+}
+
+void AudioOutput::output(const char *data, int datalen)
+{
+    if (m_output && m_output->state() != QAudio::StoppedState) {
+        // Append input data to the end of buffer
+        m_buffer.append(data, datalen);
+
+        // Check if our buffer has grown too large
+        if (m_buffer.length() > 2*BUFFER_SIZE) {
+            // There could be a better way to handle this
+            this->flush();
+        }
+
+        // If audio is suspended and buffer is full, resume
+        if (m_output->state() == QAudio::SuspendedState) {
+            if (m_buffer.length() >= BUFFER_SIZE) {
+                qDebug() << "Resuming...";
+                m_output->resume();
+            }
+        }
+    }
+}
+
+void AudioOutput::flush()
+{
+    // Flushing buffers is a bit tricky...
+    // Don't modify this unless you're sure
+    this->stop();
+    m_output->reset();
+    this->start();
+}
+
+void AudioOutput::stop()
+{
+    if (m_output && m_output->state() != QAudio::StoppedState) {
+        // Stop audio output
+        m_output->stop();
+        m_buffer.clear();
+        this->close();
+    }
+}
+
+static void apply_s16le_volume(float volume, uchar *data, int datalen)
+{
+    int samples = datalen/2;
+    float mult = pow(10.0,0.05*volume);
+
+    for (int i=0; i<samples; i++) {
+        qint16 val = qFromLittleEndian<qint16>(data+i*2)*mult;
+        qToLittleEndian<qint16>(val, data+i*2);
+    }
+}
+
+qint64 AudioOutput::readData(char *data, qint64 maxlen)
+{
+    // Calculate output length, always full samples
+    int outlen = qMin(m_buffer.length(), (int)maxlen);
+    if (outlen%2 != 0) {
+        outlen += 1;
+    }
+
+    memcpy(data, m_buffer.data(), outlen);
+    apply_s16le_volume(m_volume, (uchar *)data, outlen);
+    m_buffer.remove(0, outlen);
+    return outlen;
+}
+
+qint64 AudioOutput::writeData(const char *data, qint64 len)
+{
+    Q_UNUSED(data);
+    Q_UNUSED(len);
+
+    return 0;
+}
+
+qint64 AudioOutput::bytesAvailable() const
+{
+    return m_buffer.length() + QIODevice::bytesAvailable();
+}
+
+bool AudioOutput::isSequential() const
+{
+    return true;
+}
+
+void AudioOutput::notified()
+{
+}
+
+void AudioOutput::stateChanged(QAudio::State state)
+{
+    // Start buffering again in case of underrun...
+    // Required on Windows, otherwise it stalls idle
+    if (state == QAudio::IdleState && m_output->error() == QAudio::UnderrunError) {
+        // This check is required, because Mac OS X underruns often
+        if (m_buffer.length() < BUFFER_SIZE) {
+            m_output->suspend();
+        }
+    }
+    qWarning() << "state = " << state;
+}
diff --git a/AirTV-Qt/audiooutput.h b/AirTV-Qt/audiooutput.h
new file mode 100644 (file)
index 0000000..70b67bb
--- /dev/null
@@ -0,0 +1,51 @@
+#ifndef AUDIOOUTPUT_H
+#define AUDIOOUTPUT_H
+
+#include <QObject>
+#include <QIODevice>
+#include <QByteArray>
+#include <QAudioFormat>
+#include <QAudioDeviceInfo>
+#include <QAudioOutput>
+#include <QIODevice>
+
+class AudioOutput : public QIODevice
+{
+    Q_OBJECT
+public:
+    explicit AudioOutput(QObject *parent = 0);
+    bool init(int bits, int channels, int samplerate);
+    bool setDevice(QAudioDeviceInfo deviceInfo);
+
+    void start();
+    void setVolume(float volume);
+    void output(const char *data, int datalen);
+    void flush();
+    void stop();
+
+    qint64 readData(char *data, qint64 maxlen);
+    qint64 writeData(const char *data, qint64 len);
+    qint64 bytesAvailable() const;
+    bool isSequential() const;
+
+private:
+    void reinit();
+
+private:
+    bool             m_initialized;
+    QByteArray       m_buffer;
+    QAudioFormat     m_format;
+    QAudioDeviceInfo m_deviceInfo;
+    QAudioOutput*    m_output;
+    float            m_volume;
+
+signals:
+
+public slots:
+
+private slots:
+    void notified();
+    void stateChanged(QAudio::State state);
+};
+
+#endif // AUDIOOUTPUT_H
diff --git a/AirTV-Qt/images/airtv.svg b/AirTV-Qt/images/airtv.svg
new file mode 100644 (file)
index 0000000..978b181
--- /dev/null
@@ -0,0 +1,98 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!-- Generator: Adobe Illustrator 10.0.3, SVG Export Plug-In . SVG Version: 3.0.0 Build 77)  -->
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd" [
+       <!ENTITY ns_flows "http://ns.adobe.com/Flows/1.0/">
+       <!ENTITY ns_svg "http://www.w3.org/2000/svg">
+       <!ENTITY ns_xlink "http://www.w3.org/1999/xlink">
+]>
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:a="http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/" width="128" height="128" viewBox="0 0 128 128" overflow="visible" enable-background="new 0 0 128 128" xml:space="preserve">
+       <g id="Layer_1">
+               <g>
+                       <g>
+                               <path fill="#333333" d="M118.442,15.26c-1.162,1.161-3.046,1.161-4.207,0s-1.161-3.045,0-4.206c1.161-1.162,3.045-1.162,4.207,0      C119.604,12.215,119.604,14.099,118.442,15.26z"/>
+                               <path fill="#333333" d="M86.631,44.443l-1.577-1.577l29.708-29.709l1.577,1.577L86.631,44.443z"/>
+                       </g>
+                       <g>
+                               <path fill="#333333" d="M89.872,3.186c0,1.643-1.333,2.976-2.975,2.976s-2.974-1.333-2.974-2.976      c0-1.642,1.332-2.973,2.974-2.973C88.54,0.213,89.872,1.544,89.872,3.186z"/>
+                               <path fill="#333333" d="M88.014,46.316h-2.231V4.302h2.231V46.316z"/>
+                       </g>
+                       <path fill="#333333" d="M112.619,125.717c0,1.144-0.919,2.07-2.052,2.07H10.736c-1.133,0-2.05-0.927-2.05-2.07l0.478-84.611     c0-1.145,0.918-2.068,2.05-2.068h99.832c1.132,0,2.051,0.924,2.051,2.068L112.619,125.717z"/>
+                       <linearGradient id="XMLID_1_" gradientUnits="userSpaceOnUse" x1="60.8911" y1="29.6812" x2="60.8911" y2="99.7845">
+                               <stop offset="0" style="stop-color:#FFFFFF"/>
+                               <stop offset="0.3678" style="stop-color:#9D9D9D"/>
+                               <stop offset="0.8052" style="stop-color:#2D2D2D"/>
+                               <stop offset="1" style="stop-color:#000000"/>
+                               <a:midPointStop offset="0" style="stop-color:#FFFFFF"/>
+                               <a:midPointStop offset="0.479" style="stop-color:#FFFFFF"/>
+                               <a:midPointStop offset="1" style="stop-color:#000000"/>
+                       </linearGradient>
+                       <path opacity="0.81" fill="url(#XMLID_1_)" a:adobe-blending-mode="screen" d="M110.616,124.004     c0,1.086-0.882,1.968-1.968,1.968H12.656c-1.087,0-1.968-0.882-1.968-1.968l0.478-81.006c0-1.088,0.882-1.969,1.969-1.969h95.991     c1.086,0,1.969,0.881,1.969,1.969L110.616,124.004z"/>
+                       <g>
+                               <linearGradient id="XMLID_2_" gradientUnits="userSpaceOnUse" x1="61.5024" y1="18.5396" x2="61.5024" y2="110.5096">
+                                       <stop offset="0" style="stop-color:#000000"/>
+                                       <stop offset="1" style="stop-color:#B5B5B5"/>
+                                       <a:midPointStop offset="0" style="stop-color:#000000"/>
+                                       <a:midPointStop offset="0.5" style="stop-color:#000000"/>
+                                       <a:midPointStop offset="1" style="stop-color:#B5B5B5"/>
+                               </linearGradient>
+                               <path fill="url(#XMLID_2_)" d="M102.646,107.807c0,0.934-0.753,1.687-1.685,1.687h-78.92c-0.931,0-1.684-0.753-1.684-1.687      V48.068c0-0.931,0.753-1.685,1.684-1.685h78.92c0.932,0,1.685,0.754,1.685,1.685V107.807z"/>
+                               
+                                       <radialGradient id="XMLID_3_" cx="58.7769" cy="122.3877" r="52.3604" fx="58.7769" fy="122.3877" gradientUnits="userSpaceOnUse">
+                                       <stop offset="0" style="stop-color:#B8BBDA"/>
+                                       <stop offset="1" style="stop-color:#0D2D7D"/>
+                                       <a:midPointStop offset="0" style="stop-color:#B8BBDA"/>
+                                       <a:midPointStop offset="0.5" style="stop-color:#B8BBDA"/>
+                                       <a:midPointStop offset="1" style="stop-color:#0D2D7D"/>
+                               </radialGradient>
+                               <path fill="url(#XMLID_3_)" d="M100.328,106.127c0,0.876-0.711,1.587-1.589,1.587H24.266c-0.878,0-1.589-0.711-1.589-1.587      V49.75c0-0.877,0.711-1.589,1.589-1.589h74.474c0.878,0,1.589,0.712,1.589,1.589V106.127z"/>
+                       </g>
+                       
+                               <radialGradient id="XMLID_4_" cx="36.2217" cy="60.2163" r="57.7388" fx="36.2217" fy="60.2163" gradientTransform="matrix(1.0211, 0, 0, 0.9264, 27.8623, -8.8409)" gradientUnits="userSpaceOnUse">
+                               <stop offset="0" style="stop-color:#B8BBDA"/>
+                               <stop offset="1" style="stop-color:#0D2D7D"/>
+                               <a:midPointStop offset="0" style="stop-color:#B8BBDA"/>
+                               <a:midPointStop offset="0.5" style="stop-color:#B8BBDA"/>
+                               <a:midPointStop offset="1" style="stop-color:#0D2D7D"/>
+                       </radialGradient>
+                       <path opacity="0.78" fill="url(#XMLID_4_)" d="M23.57,59.344c0,11.951,17.039,21.64,38.059,21.64     c21.018,0,38.057-9.688,38.057-21.64c0-3.993-1.909-7.729-5.227-10.94H28.798C25.479,51.614,23.57,55.351,23.57,59.344z"/>
+                       <g>
+                               <linearGradient id="XMLID_5_" gradientUnits="userSpaceOnUse" x1="98.6885" y1="125.7139" x2="98.6885" y2="118.7914">
+                                       <stop offset="0" style="stop-color:#FFFFFF"/>
+                                       <stop offset="0.8483" style="stop-color:#00CD00"/>
+                                       <stop offset="1" style="stop-color:#00BD00"/>
+                                       <a:midPointStop offset="0" style="stop-color:#FFFFFF"/>
+                                       <a:midPointStop offset="0.5" style="stop-color:#FFFFFF"/>
+                                       <a:midPointStop offset="0.8483" style="stop-color:#00CD00"/>
+                                       <a:midPointStop offset="0.5" style="stop-color:#00CD00"/>
+                                       <a:midPointStop offset="1" style="stop-color:#00BD00"/>
+                               </linearGradient>
+                               <path fill="url(#XMLID_5_)" d="M102.397,118.534c0,2.048-1.659,3.708-3.708,3.708s-3.71-1.66-3.71-3.708      c0-2.049,1.661-3.71,3.71-3.71S102.397,116.485,102.397,118.534z"/>
+                               <linearGradient id="XMLID_6_" gradientUnits="userSpaceOnUse" x1="94.1318" y1="111.6963" x2="96.9031" y2="115.8532">
+                                       <stop offset="0.0112" style="stop-color:#009500"/>
+                                       <stop offset="0.2978" style="stop-color:#009000"/>
+                                       <stop offset="1" style="stop-color:#005B00"/>
+                                       <a:midPointStop offset="0.0112" style="stop-color:#009500"/>
+                                       <a:midPointStop offset="0.5" style="stop-color:#009500"/>
+                                       <a:midPointStop offset="0.2978" style="stop-color:#009000"/>
+                                       <a:midPointStop offset="0.5" style="stop-color:#009000"/>
+                                       <a:midPointStop offset="1" style="stop-color:#005B00"/>
+                               </linearGradient>
+                               <path fill="url(#XMLID_6_)" d="M94.804,118.534c0,2.142,1.742,3.884,3.886,3.884c2.143,0,3.886-1.742,3.886-3.884      c0-2.144-1.743-3.888-3.886-3.888C96.546,114.646,94.804,116.391,94.804,118.534z M95.157,118.534      c0-1.949,1.585-3.533,3.532-3.533s3.532,1.584,3.532,3.533c0,1.946-1.585,3.532-3.532,3.532S95.157,120.48,95.157,118.534z"/>
+                               <linearGradient id="XMLID_7_" gradientUnits="userSpaceOnUse" x1="98.5879" y1="115.1816" x2="98.5879" y2="119.1344">
+                                       <stop offset="0" style="stop-color:#FFFFFF"/>
+                                       <stop offset="0.1147" style="stop-color:#E9FAE9"/>
+                                       <stop offset="0.3539" style="stop-color:#B0EDB0"/>
+                                       <stop offset="0.6936" style="stop-color:#57D957"/>
+                                       <stop offset="1" style="stop-color:#00C500"/>
+                                       <a:midPointStop offset="0" style="stop-color:#FFFFFF"/>
+                                       <a:midPointStop offset="0.5424" style="stop-color:#FFFFFF"/>
+                                       <a:midPointStop offset="1" style="stop-color:#00C500"/>
+                               </linearGradient>
+                               <path fill="url(#XMLID_7_)" d="M98.706,118.675c1.291-0.954,2.505-1.275,3.038-1.378c-0.513-1.155-1.671-1.961-3.016-1.961      c-1.82,0-3.297,1.475-3.297,3.295c0,0.287,0.036,0.563,0.104,0.828C96.07,119.559,97.377,119.657,98.706,118.675z"/>
+                       </g>
+                       <path opacity="0.81" fill="#666666" d="M77.539,120.482h-36.61v6.461h36.61V120.482z"/>
+                       <path d="M77.539,120.109H40.556v7.205h37.356v-7.205H77.539z M77.169,120.854c0,0.619,0,5.097,0,5.719     c-0.722,0-35.148,0-35.869,0c0-0.622,0-5.1,0-5.719C42.021,120.854,76.447,120.854,77.169,120.854z"/>
+               </g>
+               <path fill="none" d="M128,128H0V0h128V128z"/>
+       </g>
+</svg>
\ No newline at end of file
diff --git a/AirTV-Qt/main.cpp b/AirTV-Qt/main.cpp
new file mode 100644 (file)
index 0000000..0eaf1ce
--- /dev/null
@@ -0,0 +1,30 @@
+#include <QtGui>
+#include <QtSingleApplication>
+
+#include "mainapplication.h"
+#include "videowidget.h"
+#include "raopservice.h"
+
+int main(int argc, char *argv[])
+{
+    QtSingleApplication a(argc, argv);
+    if (a.isRunning()) {
+        return 0;
+    }
+    a.setApplicationName("AirTV");
+
+    if (!QSystemTrayIcon::isSystemTrayAvailable())  {
+        QMessageBox::critical(0, QObject::tr("Systray"),
+                              QObject::tr("I couldn't detect any system tray "
+                                          "on this system."));
+        return 1;
+    }
+    QApplication::setQuitOnLastWindowClosed(false);
+
+    MainApplication m;
+    QObject::connect(&m, SIGNAL(quitRequested()), &a, SLOT(quit()));
+    QObject::connect(&a, SIGNAL(aboutToQuit()), &m, SLOT(aboutToQuit()));
+    m.start();
+
+    return a.exec();
+}
diff --git a/AirTV-Qt/mainapplication.cpp b/AirTV-Qt/mainapplication.cpp
new file mode 100644 (file)
index 0000000..477f782
--- /dev/null
@@ -0,0 +1,46 @@
+#include "mainapplication.h"
+
+#include <QDebug>
+
+MainApplication::MainApplication(QObject *parent) :
+    QObject(parent)
+{
+    raopService = new RaopService(0);
+    trayIconMenu = new QMenu(0);
+
+    // Initialize the service
+    raopService->init();
+
+    quitAction = new QAction(tr("&Quit"), trayIconMenu);
+    connect(quitAction, SIGNAL(triggered()), this, SIGNAL(quitRequested()));
+    trayIconMenu->addAction(quitAction);
+
+    // Construct the actual system tray icon
+    trayIcon = new QSystemTrayIcon(this);
+    trayIcon->setContextMenu(trayIconMenu);
+    trayIcon->setIcon(QIcon(":icons/airtv.svg"));
+}
+
+MainApplication::~MainApplication()
+{
+    trayIcon->setContextMenu(0);
+    delete trayIconMenu;
+    delete raopService;
+}
+
+void MainApplication::start()
+{
+    raopService->start();
+    trayIcon->show();
+}
+
+void MainApplication::stop()
+{
+    raopService->stop();
+    trayIcon->hide();
+}
+
+void MainApplication::aboutToQuit()
+{
+    this->stop();
+}
diff --git a/AirTV-Qt/mainapplication.h b/AirTV-Qt/mainapplication.h
new file mode 100644 (file)
index 0000000..eccdfb2
--- /dev/null
@@ -0,0 +1,36 @@
+#ifndef MAINAPPLICATION_H
+#define MAINAPPLICATION_H
+
+#include <QObject>
+#include <QSystemTrayIcon>
+#include <QMenu>
+#include <QAction>
+
+#include "raopservice.h"
+
+class MainApplication : public QObject
+{
+    Q_OBJECT
+public:
+    explicit MainApplication(QObject *parent = 0);
+    ~MainApplication();
+
+    void start();
+    void stop();
+
+private:
+    RaopService *raopService;
+
+    QSystemTrayIcon *trayIcon;
+    QMenu *trayIconMenu;
+    QAction *quitAction;
+
+signals:
+    void quitRequested();
+
+public slots:
+    void aboutToQuit();
+
+};
+
+#endif // MAINAPPLICATION_H
diff --git a/AirTV-Qt/mainwindow.ui b/AirTV-Qt/mainwindow.ui
new file mode 100644 (file)
index 0000000..6050363
--- /dev/null
@@ -0,0 +1,24 @@
+<ui version="4.0">
+ <class>MainWindow</class>
+ <widget class="QMainWindow" name="MainWindow" >
+  <property name="geometry" >
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>400</width>
+    <height>300</height>
+   </rect>
+  </property>
+  <property name="windowTitle" >
+   <string>MainWindow</string>
+  </property>
+  <widget class="QMenuBar" name="menuBar" />
+  <widget class="QToolBar" name="mainToolBar" />
+  <widget class="QWidget" name="centralWidget" />
+  <widget class="QStatusBar" name="statusBar" />
+ </widget>
+ <layoutDefault spacing="6" margin="11" />
+ <pixmapfunction></pixmapfunction>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/AirTV-Qt/qtsingleapplication/INSTALL.TXT b/AirTV-Qt/qtsingleapplication/INSTALL.TXT
new file mode 100644 (file)
index 0000000..bbb74a9
--- /dev/null
@@ -0,0 +1,254 @@
+INSTALLATION INSTRUCTIONS
+
+These instructions refer to the package you are installing as
+some-package.tar.gz or some-package.zip. The .zip file is intended for use
+on Windows.
+
+The directory you choose for the installation will be referred to as
+your-install-dir.
+
+Note to Qt Visual Studio Integration users: In the instructions below,
+instead of building from command line with nmake, you can use the menu
+command 'Qt->Open Solution from .pro file' on the .pro files in the
+example and plugin directories, and then build from within Visual
+Studio.
+
+Unpacking and installation
+--------------------------
+
+1.  Unpacking the archive (if you have not done so already).
+
+    On Unix and Mac OS X (in a terminal window):
+
+       cd your-install-dir
+       gunzip some-package.tar.gz
+       tar xvf some-package.tar
+
+    This creates the subdirectory some-package containing the files.
+
+    On Windows:
+
+    Unpack the .zip archive by right-clicking it in explorer and
+    choosing "Extract All...". If your version of Windows does not
+    have zip support, you can use the infozip tools available
+    from www.info-zip.org.
+
+    If you are using the infozip tools (in a command prompt window):
+       cd your-install-dir
+       unzip some-package.zip
+
+2.  Configuring the package.
+
+    The configure script is called "configure" on unix/mac and
+    "configure.bat" on Windows. It should be run from a command line
+    after cd'ing to the package directory. 
+
+    You can choose whether you want to use the component by including
+    its source code directly into your project, or build the component
+    as a dynamic shared library (DLL) that is loaded into the
+    application at run-time. The latter may be preferable for
+    technical or licensing (LGPL) reasons. If you want to build a DLL,
+    run the configure script with the argument "-library". Also see
+    the note about usage below.
+
+    (Components that are Qt plugins, e.g. styles and image formats,
+    are by default built as a plugin DLL.)
+
+    The configure script will prompt you in some cases for further
+    information. Answer these questions and carefully read the license text
+    before accepting the license conditions. The package cannot be used if
+    you do not accept the license conditions.
+
+3.  Building the component and examples (when required).
+
+    If a DLL is to be built, or if you would like to build the
+    examples, next give the commands
+
+        qmake
+        make          [or nmake if your are using Microsoft Visual C++]
+
+    The example program(s) can be found in the directory called
+    "examples" or "example".
+
+    Components that are Qt plugins, e.g. styles and image formats, are
+    ready to be used as soon as they are built, so the rest of this
+    installation instruction can be skipped.
+
+4.  Building the Qt Designer plugin (optional).
+
+    Some of the widget components are provided with plugins for Qt
+    Designer. To build and install the plugin, cd into the
+    some-package/plugin directory and give the commands
+
+       qmake
+       make           [or nmake if your are using Microsoft Visual C++]
+
+    Restart Qt Designer to make it load the new widget plugin.
+
+    Note: If you are using the built-in Qt Designer from the Qt Visual
+    Studio Integration, you will need to manually copy the plugin DLL
+    file, i.e. copy
+       %QTDIR%\plugins\designer\some-component.dll 
+    to the Qt Visual Studio Integration plugin path, typically:
+       C:\Program Files\Trolltech\Qt VS Integration\plugins
+
+    Note: If you for some reason are using a Qt Designer that is built
+    in debug mode, you will need to build the plugin in debug mode
+    also. Edit the file plugin.pro in the plugin directory, changing
+    'release' to 'debug' in the CONFIG line, before running qmake.
+
+
+
+Solutions components are intended to be used directly from the package
+directory during development, so there is no 'make install' procedure.
+
+
+Using a component in your project
+---------------------------------
+
+To use this component in your project, add the following line to the
+project's .pro file (or do the equivalent in your IDE):
+
+    include(your-install-dir/some-package/src/some-package.pri)
+
+This adds the package's sources and headers to the SOURCES and HEADERS
+project variables respectively (or, if the component has been
+configured as a DLL, it adds that library to the LIBS variable), and
+updates INCLUDEPATH to contain the package's src
+directory. Additionally, the .pri file may include some dependencies
+needed by the package.
+
+To include a header file from the package in your sources, you can now
+simply use:
+
+    #include <SomeClass>
+
+or alternatively, in pre-Qt 4 style:
+
+    #include <some-class.h>
+
+Refer to the documentation to see the classes and headers this
+components provides.
+
+
+
+Install documentation (optional)
+--------------------------------
+
+The HTML documentation for the package's classes is located in the
+your-install-dir/some-package/doc/html/index.html. You can open this
+file and read the documentation with any web browser.
+
+To install the documentation into Qt Assistant (for Qt version 4.4 and
+later):
+
+1.  In Assistant, open the Edit->Preferences dialog and choose the
+    Documentation tab. Click the Add... button and select the file
+       your-install-dir/some-package/doc/html/some-package.qch
+    
+For Qt versions prior to 4.4, do instead the following:
+
+1.  The directory your-install-dir/some-package/doc/html contains a
+    file called some-package.dcf. Execute the following commands in a
+    shell, command prompt or terminal window:
+
+       cd your-install-dir/some-package/doc/html/
+       assistant -addContentFile some-package.dcf
+
+The next time you start Qt Assistant, you can access the package's
+documentation.
+
+
+Removing the documentation from assistant
+-----------------------------------------
+
+If you have installed the documentation into Qt Assistant, and want to uninstall it, do as follows, for Qt version 4.4 and later:
+
+1.  In Assistant, open the Edit->Preferences dialog and choose the
+    Documentation tab. In the list of Registered Documentation, select
+    the item com.nokia.qtsolutions.some-package_version, and click
+    the Remove button.
+
+For Qt versions prior to 4.4, do instead the following:
+
+1.  The directory your-install-dir/some-package/doc/html contains a
+    file called some-package.dcf. Execute the following commands in a
+    shell, command prompt or terminal window:
+
+       cd your-install-dir/some-package/doc/html/
+       assistant -removeContentFile some-package.dcf
+
+
+
+Using the component as a DLL
+----------------------------
+
+1. Normal components
+
+    The shared library (DLL) is built and placed in the
+    some-package/lib directory. It is intended to be used directly
+    from there during development. When appropriate, both debug and
+    release versions are built, since the run-time linker will in some
+    cases refuse to load a debug-built DLL into a release-built
+    application or vice versa.
+
+    The following steps are taken by default to help the dynamic
+    linker to locate the DLL at run-time (during development):
+
+    Unix: The some-package.pri file will add linker instructions to
+    add the some-package/lib directory to the rpath of the
+    executable. (When distributing, or if your system does not support
+    rpath, you can copy the shared library to another place that is
+    searched by the dynamic linker, e.g. the "lib" directory of your
+    Qt installation.)
+
+    Mac: The full path to the library is hardcoded into the library
+    itself, from where it is copied into the executable at link time,
+    and ready by the dynamic linker at run-time. (When distributing,
+    you will want to edit these hardcoded paths in the same way as for
+    the Qt DLLs. Refer to the document "Deploying an Application on
+    Mac OS X" in the Qt Reference Documentation.)
+
+    Windows: the .dll file(s) are copied into the "bin" directory of
+    your Qt installation. The Qt installation will already have set up
+    that directory to be searched by the dynamic linker.
+
+
+2. Plugins
+
+    For Qt Solutions plugins (e.g. image formats), both debug and
+    release versions of the plugin are built by default when
+    appropriate, since in some cases the release Qt library will not
+    load a debug plugin, and vice versa. The plugins are automatically
+    copied into the plugins directory of your Qt installation when
+    built, so no further setup is required.
+
+    Plugins may also be built statically, i.e. as a library that will be
+    linked into your application executable, and so will not need to
+    be redistributed as a separate plugin DLL to end users. Static
+    building is required if Qt itself is built statically. To do it,
+    just add "static" to the CONFIG variable in the plugin/plugin.pro
+    file before building. Refer to the "Static Plugins" section in the
+    chapter "How to Create Qt Plugins" for explanation of how to use a
+    static plugin in your application. The source code of the example
+    program(s) will also typically contain the relevant instructions
+    as comments.
+
+
+
+Uninstalling
+------------
+
+    The following command will remove any fils that have been
+    automatically placed outside the package directory itself during
+    installation and building
+
+       make distclean [or nmake if your are using Microsoft Visual C++]
+
+    If Qt Assistant documentation or Qt Designer plugins have been
+    installed, they can be uninstalled manually, ref. above.
+
+
+Enjoy! :)
+
+- The Qt Solutions Team.
diff --git a/AirTV-Qt/qtsingleapplication/README.TXT b/AirTV-Qt/qtsingleapplication/README.TXT
new file mode 100644 (file)
index 0000000..06abb09
--- /dev/null
@@ -0,0 +1,33 @@
+Qt Solutions Component: Single Application
+
+The QtSingleApplication component provides support for
+applications that can be only started once per user.
+
+
+
+Version history:
+
+2.0: - Version 1.3 ported to Qt 4.
+
+2.1: - Fix compilation problem on Mac.
+
+2.2: - Really fix the Mac compilation problem.
+     - Mac: fix crash due to wrong object releasing.
+     - Mac: Fix memory leak.
+
+2.3: - Windows: Force creation of internal widget to make it work
+     with Qt 4.2.
+
+2.4: - Fix the system for automatic window raising on message
+     reception. NOTE: minor API change.
+
+2.5: - Mac: Fix isRunning() to work and report correctly.
+
+2.6: - - initialize() is now obsolete, no longer necessary to call
+     it
+     - - Fixed race condition where multiple instances migth be started
+     - - QtSingleCoreApplication variant provided for non-GUI (console)
+     usage
+     - Complete reimplementation. Visible changes:
+     - LGPL release.
+
diff --git a/AirTV-Qt/qtsingleapplication/buildlib/buildlib.pro b/AirTV-Qt/qtsingleapplication/buildlib/buildlib.pro
new file mode 100644 (file)
index 0000000..37dddcd
--- /dev/null
@@ -0,0 +1,13 @@
+TEMPLATE=lib
+CONFIG += qt dll qtsingleapplication-buildlib
+mac:CONFIG += absolute_library_soname
+win32|mac:!wince*:!win32-msvc:!macx-xcode:CONFIG += debug_and_release build_all
+include(../src/qtsingleapplication.pri)
+TARGET = $$QTSINGLEAPPLICATION_LIBNAME
+DESTDIR = $$QTSINGLEAPPLICATION_LIBDIR
+win32 {
+    DLLDESTDIR = $$[QT_INSTALL_BINS]
+    QMAKE_DISTCLEAN += $$[QT_INSTALL_BINS]\\$${QTSINGLEAPPLICATION_LIBNAME}.dll
+}
+target.path = $$DESTDIR
+INSTALLS += target
diff --git a/AirTV-Qt/qtsingleapplication/common.pri b/AirTV-Qt/qtsingleapplication/common.pri
new file mode 100644 (file)
index 0000000..8f5fc80
--- /dev/null
@@ -0,0 +1,6 @@
+infile(config.pri, SOLUTIONS_LIBRARY, yes): CONFIG += qtsingleapplication-uselib
+TEMPLATE += fakelib
+QTSINGLEAPPLICATION_LIBNAME = $$qtLibraryTarget(QtSolutions_SingleApplication-head)
+TEMPLATE -= fakelib
+QTSINGLEAPPLICATION_LIBDIR = $$PWD/lib
+unix:qtsingleapplication-uselib:!qtsingleapplication-buildlib:QMAKE_RPATHDIR += $$QTSINGLEAPPLICATION_LIBDIR
diff --git a/AirTV-Qt/qtsingleapplication/configure b/AirTV-Qt/qtsingleapplication/configure
new file mode 100755 (executable)
index 0000000..3c4edff
--- /dev/null
@@ -0,0 +1,25 @@
+#!/bin/sh
+
+if [ "x$1" != "x" -a "x$1" != "x-library" ]; then
+    echo "Usage: $0 [-library]"
+    echo 
+    echo "-library: Build the component as a dynamic library (DLL). Default is to"
+    echo "          include the component source code directly in the application."
+    echo 
+    exit 0
+fi
+
+rm -f config.pri
+if [ "x$1" = "x-library" ]; then
+    echo "Configuring to build this component as a dynamic library."
+    echo "SOLUTIONS_LIBRARY = yes" > config.pri
+fi
+
+echo
+echo "This component is now configured."
+echo
+echo "To build the component library (if requested) and example(s),"
+echo "run qmake and your make command."
+echo
+echo "To remove or reconfigure, run make distclean."
+echo
diff --git a/AirTV-Qt/qtsingleapplication/configure.bat b/AirTV-Qt/qtsingleapplication/configure.bat
new file mode 100644 (file)
index 0000000..72c1b83
--- /dev/null
@@ -0,0 +1,39 @@
+@echo off\r
+\r
+rem\r
+rem "Main"\r
+rem\r
+\r
+if not "%1"=="" (\r
+    if not "%1"=="-library" (\r
+        call :PrintUsage\r
+        goto EOF\r
+    )\r
+)\r
+\r
+if exist config.pri. del config.pri\r
+if "%1"=="-library" (\r
+    echo Configuring to build this component as a dynamic library.\r
+    echo SOLUTIONS_LIBRARY = yes > config.pri\r
+)\r
+\r
+echo .\r
+echo This component is now configured.\r
+echo .\r
+echo To build the component library (if requested) and example(s),\r
+echo run qmake and your make or nmake command.\r
+echo .\r
+echo To remove or reconfigure, run make (nmake) distclean.\r
+echo .\r
+\r
+:PrintUsage\r
+echo Usage: configure.bat [-library]\r
+echo .\r
+echo -library: Build the component as a dynamic library (DLL). Default is to\r
+echo           include the component source directly in the application.\r
+echo           A DLL may be preferable for technical or licensing (LGPL) reasons.\r
+echo .\r
+goto EOF\r
+\r
+\r
+:EOF\r
diff --git a/AirTV-Qt/qtsingleapplication/doc/html/classic.css b/AirTV-Qt/qtsingleapplication/doc/html/classic.css
new file mode 100644 (file)
index 0000000..b8cae8e
--- /dev/null
@@ -0,0 +1,284 @@
+BODY,H1,H2,H3,H4,H5,H6,P,CENTER,TD,TH,UL,DL,DIV {
+  font-family: Arial, Geneva, Helvetica, sans-serif;
+}
+H1 {
+  text-align: center;
+  font-size: 160%;
+}
+H2 {
+  font-size: 120%;
+}
+H3 {
+  font-size: 100%;
+}
+
+h3.fn,span.fn
+{
+  background-color: #eee;
+  border-width: 1px;
+  border-style: solid;
+  border-color: #ddd;
+  font-weight: bold;
+  padding: 6px 0px 6px 10px;
+  margin: 42px 0px 0px 0px;
+}
+
+hr {
+  border: 0;
+  color: #a0a0a0;
+  background-color: #ccc;
+  height: 1px;
+  width: 100%;
+  text-align: left;
+  margin: 34px 0px 34px 0px;
+}
+
+table.valuelist {
+       border-width: 1px 1px 1px 1px;
+       border-style: solid;
+       border-color: #dddddd;
+       border-collapse: collapse;
+       background-color: #f0f0f0;
+}
+
+table.indextable {
+       border-width: 1px 1px 1px 1px;
+       border-style: solid;
+       border-collapse: collapse;
+       background-color: #f0f0f0;
+    border-color:#555;
+    font-size: 100%;
+}
+
+table td.largeindex {
+       border-width: 1px 1px 1px 1px;
+       border-collapse: collapse;
+       background-color: #f0f0f0;
+    border-color:#555;
+    font-size: 120%;
+}
+
+table.valuelist th {
+       border-width: 1px 1px 1px 2px;
+       padding: 4px;
+       border-style: solid;
+       border-color: #666;
+    color:white;
+    background-color:#666;
+}
+
+th.titleheader  {
+       border-width: 1px 0px 1px 0px;
+       padding: 2px;
+       border-style: solid;
+       border-color: #666;
+    color:white;
+    background-color:#555;
+    background-image:url('images/gradient.png')};
+    background-repeat: repeat-x;
+    font-size: 100%;
+}
+
+
+th.largeheader {
+       border-width: 1px 0px 1px 0px;
+       padding: 4px;
+       border-style: solid;
+       border-color: #444;
+    color:white;
+    background-color:#555555;
+    font-size: 120%;
+}
+
+p {
+
+  margin-left: 4px;
+  margin-top: 8px;
+  margin-bottom: 8px;
+}
+
+a:link
+{
+  color: #0046ad;
+  text-decoration: none
+}
+
+a:visited
+{
+  color: #672967;
+  text-decoration: none
+}
+
+a.obsolete
+{
+  color: #661100;
+  text-decoration: none
+}
+
+a.compat
+{
+  color: #661100;
+  text-decoration: none
+}
+
+a.obsolete:visited
+{
+  color: #995500;
+  text-decoration: none
+}
+
+a.compat:visited
+{
+  color: #995500;
+  text-decoration: none
+}
+
+body
+{
+  background: #ffffff;
+  color: black
+}
+
+table.generic, table.annotated
+{
+  border-width: 1px;
+  border-color:#bbb;
+  border-style:solid;  
+  border-collapse:collapse;
+}
+
+table td.memItemLeft {
+  width: 180px;
+  padding: 2px 0px 0px 8px;
+  margin: 4px;
+  border-width: 1px;
+  border-color: #E0E0E0;
+  border-style: none;
+  font-size: 100%;
+  white-space: nowrap
+}
+
+table td.memItemRight {
+  padding: 2px 8px 0px 8px;
+  margin: 4px;
+  border-width: 1px;
+  border-color: #E0E0E0;
+  border-style: none;
+  font-size: 100%;
+}
+
+table tr.odd {
+  background: #f0f0f0;
+  color: black;
+}
+
+table tr.even {
+  background: #e4e4e4;
+  color: black;
+}
+
+table.annotated th {
+  padding: 3px;
+  text-align: left
+}
+
+table.annotated td {
+  padding: 3px;
+}
+
+table tr pre
+{
+  padding-top: 0px;
+  padding-bottom: 0px;
+  padding-left: 0px;
+  padding-right: 0px;
+  border: none;
+  background: none
+}
+
+tr.qt-style
+{
+  background: #96E066;
+  color: black
+}
+
+body pre
+{
+  padding: 0.2em;
+  border: #e7e7e7 1px solid;
+  background: #f1f1f1;
+  color: black
+}
+
+table tr.qt-code pre
+{
+  padding: 0.2em;
+  border: #e7e7e7 1px solid;
+  background: #f1f1f1;
+  color: black
+}
+
+span.preprocessor, span.preprocessor a
+{
+  color: darkblue;
+}
+
+span.comment
+{
+  color: darkred;
+  font-style: italic
+}
+
+span.string,span.char
+{
+  color: darkgreen;
+}
+
+.title
+{
+    text-align: center
+}
+
+.subtitle
+{
+    font-size: 0.8em
+}
+
+.small-subtitle
+{
+    font-size: 0.65em
+}
+
+.qmlitem {
+    padding: 0;
+}
+
+.qmlname {
+    white-space: nowrap;
+}
+
+.qmltype {
+    text-align: center;
+    font-size: 160%;
+}
+
+.qmlproto {
+    background-color: #eee;
+    border-width: 1px;
+    border-style: solid;
+    border-color: #ddd;
+    font-weight: bold;
+    padding: 6px 10px 6px 10px;
+    margin: 42px 0px 0px 0px;
+}
+
+.qmlreadonly {
+    float: right;
+    color: red
+}
+
+.qmldoc {
+}
+
+*.qmlitem p {
+}
diff --git a/AirTV-Qt/qtsingleapplication/doc/html/images/qt-logo.png b/AirTV-Qt/qtsingleapplication/doc/html/images/qt-logo.png
new file mode 100644 (file)
index 0000000..794162f
Binary files /dev/null and b/AirTV-Qt/qtsingleapplication/doc/html/images/qt-logo.png differ
diff --git a/AirTV-Qt/qtsingleapplication/doc/html/index.html b/AirTV-Qt/qtsingleapplication/doc/html/index.html
new file mode 100644 (file)
index 0000000..af9dab1
--- /dev/null
@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="iso-8859-1"?>
+<!DOCTYPE html
+    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<!-- index.qdoc -->
+<head>
+  <title>Single Application</title>
+  <link href="classic.css" rel="stylesheet" type="text/css" />
+</head>
+<body>
+<table border="0" cellpadding="0" cellspacing="0" width="100%">
+<tr>
+<td align="left" valign="top" width="32"><img src="images/qt-logo.png" align="left" width="57" height="67" border="0" /></td>
+<td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a></td>
+</tr></table><h1 class="title">Single Application<br /><span class="subtitle"></span>
+</h1>
+<a name="description"></a>
+<h2>Description</h2>
+<p>The <a href="qtsingleapplication.html">QtSingleApplication</a> component provides support for applications that can be only started once per user.</p>
+<p>For some applications it is useful or even critical that they are started only once by any user. Future attempts to start the application should activate any already running instance, and possibly perform requested actions, e.g&#x2e; loading a file, in that instance.</p>
+<p>The <a href="qtsingleapplication.html">QtSingleApplication</a> class provides an interface to detect a running instance, and to send command strings to that instance. For console (non-GUI) applications, the <a href="qtsinglecoreapplication.html">QtSingleCoreApplication</a> variant is provided, which avoids dependency on <a href="http://qt.nokia.com/doc/4.6/qtgui.html">QtGui</a>.</p>
+<a name="classes"></a>
+<h2>Classes</h2>
+<ul>
+<li><a href="qtsingleapplication.html">QtSingleApplication</a></li>
+<li><a href="qtsinglecoreapplication.html">QtSingleCoreApplication</a></li>
+</ul>
+<a name="examples"></a>
+<h2>Examples</h2>
+<ul>
+<li><a href="qtsingleapplication-example-trivial.html">A Trivial Example</a></li>
+<li><a href="qtsingleapplication-example-loader.html">Loading Documents</a></li>
+<li><a href="qtsinglecoreapplication-example-console.html">A Non-GUI Example</a></li>
+</ul>
+<a name="tested-platforms"></a>
+<h2>Tested platforms</h2>
+<ul>
+<li>Qt 4.4, 4.5 / Windows XP / MSVC.NET 2005</li>
+<li>Qt 4.4, 4.5 / Linux / gcc</li>
+<li>Qt 4.4, 4.5 / MacOS X 10.5 / gcc</li>
+</ul>
+<p /><address><hr /><div align="center">
+<table width="100%" cellspacing="0" border="0"><tr class="address">
+<td width="30%" align="left">Copyright &copy; 2010 Nokia Corporation and/or its subsidiary(-ies)</td>
+<td width="40%" align="center"><a href="http://qt.nokia.com/doc/trademarks.html">Trademarks</a></td>
+<td width="30%" align="right"><div align="right">Qt Solutions</div></td>
+</tr></table></div></address></body>
+</html>
diff --git a/AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication-example-loader.html b/AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication-example-loader.html
new file mode 100644 (file)
index 0000000..c305ae5
--- /dev/null
@@ -0,0 +1,177 @@
+<?xml version="1.0" encoding="iso-8859-1"?>
+<!DOCTYPE html
+    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<!-- loader.qdoc -->
+<head>
+  <title>Loading Documents</title>
+  <link href="classic.css" rel="stylesheet" type="text/css" />
+</head>
+<body>
+<table border="0" cellpadding="0" cellspacing="0" width="100%">
+<tr>
+<td align="left" valign="top" width="32"><img src="images/qt-logo.png" align="left" width="57" height="67" border="0" /></td>
+<td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a></td>
+</tr></table><h1 class="title">Loading Documents<br /><span class="subtitle"></span>
+</h1>
+<p>The application in this example loads or prints the documents passed as commandline parameters to further instances of this application.</p>
+<pre><span class="comment"> /****************************************************************************
+ **
+ ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ ** All rights reserved.
+ **
+ ** Contact: Nokia Corporation (qt-info@nokia.com)
+ **
+ ** This file is part of a Qt Solutions component.
+ **
+ ** You may use this file under the terms of the BSD license as follows:
+ **
+ ** &quot;Redistribution and use in source and binary forms, with or without
+ ** modification, are permitted provided that the following conditions are
+ ** met:
+ **   * Redistributions of source code must retain the above copyright
+ **     notice, this list of conditions and the following disclaimer.
+ **   * Redistributions in binary form must reproduce the above copyright
+ **     notice, this list of conditions and the following disclaimer in
+ **     the documentation and/or other materials provided with the
+ **     distribution.
+ **   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+ **     the names of its contributors may be used to endorse or promote
+ **     products derived from this software without specific prior written
+ **     permission.
+ **
+ ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ ** &quot;AS IS&quot; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.&quot;
+ **
+ ****************************************************************************/</span>
+
+ #include &lt;qtsingleapplication.h&gt;
+ #include &lt;QtCore/QFile&gt;
+ #include &lt;QtGui/QMainWindow&gt;
+ #include &lt;QtGui/QPrinter&gt;
+ #include &lt;QtGui/QPainter&gt;
+ #include &lt;QtGui/QTextEdit&gt;
+ #include &lt;QtGui/QMdiArea&gt;
+ #include &lt;QtCore/QTextStream&gt;
+
+ class MainWindow : public QMainWindow
+ {
+     Q_OBJECT
+ public:
+     MainWindow();
+
+ public slots:
+     void handleMessage(const QString&amp; message);
+
+ signals:
+     void needToShow();
+
+ private:
+     QMdiArea *workspace;
+ };</pre>
+<p>The user interface in this application is a <a href="http://qt.nokia.com/doc/4.6/qmainwindow.html">QMainWindow</a> subclass with a <a href="http://qt.nokia.com/doc/4.6/qmdiarea.html">QMdiArea</a> as the central widget. It implements a slot <tt>handleMessage()</tt> that will be connected to the messageReceived() signal of the <a href="qtsingleapplication.html">QtSingleApplication</a> class.</p>
+<pre> MainWindow::MainWindow()
+ {
+     workspace = new QMdiArea(this);
+
+     setCentralWidget(workspace);
+ }</pre>
+<p>The <a href="http://qt.nokia.com/doc/4.6/designer-to-know.html">MainWindow</a> constructor creates a minimal user interface.</p>
+<pre> void MainWindow::handleMessage(const QString&amp; message)
+ {
+     enum Action {
+         Nothing,
+         Open,
+         Print
+     } action;
+
+     action = Nothing;
+     QString filename = message;
+     if (message.toLower().startsWith(&quot;/print &quot;)) {
+         filename = filename.mid(7);
+         action = Print;
+     } else if (!message.isEmpty()) {
+         action = Open;
+     }
+     if (action == Nothing) {
+         emit needToShow();
+         return;
+     }
+
+     QFile file(filename);
+     QString contents;
+     if (file.open(QIODevice::ReadOnly))
+         contents = file.readAll();
+     else
+         contents = &quot;[[Error: Could not load file &quot; + filename + &quot;]]&quot;;
+
+     QTextEdit *view = new QTextEdit;
+     view-&gt;setPlainText(contents);
+
+     switch(action) {</pre>
+<p>The handleMessage() slot interprets the message passed in as a filename that can be prepended with <i>/print</i> to indicate that the file should just be printed rather than loaded.</p>
+<pre>     case Print:
+         {
+             QPrinter printer;
+             view-&gt;print(&amp;printer);
+             delete view;
+         }
+         break;
+
+     case Open:
+         {
+             workspace-&gt;addSubWindow(view);
+             view-&gt;setWindowTitle(message);
+             view-&gt;show();
+             emit needToShow();
+         }
+         break;
+     default:
+         break;
+     };
+ }</pre>
+<p>Loading the file will also activate the window.</p>
+<pre> #include &quot;main.moc&quot;
+
+ int main(int argc, char **argv)
+ {
+     QtSingleApplication instance(&quot;File loader QtSingleApplication example&quot;, argc, argv);
+     QString message;
+     for (int a = 1; a &lt; argc; ++a) {
+         message += argv[a];
+         if (a &lt; argc-1)
+             message += &quot; &quot;;
+     }
+
+     if (instance.sendMessage(message))
+         return 0;</pre>
+<p>The <tt>main</tt> entry point function creates a <a href="qtsingleapplication.html">QtSingleApplication</a> object, and creates a message to send to a running instance of the application. If the message was sent successfully the process exits immediately.</p>
+<pre>     MainWindow mw;
+     mw.handleMessage(message);
+     mw.show();
+
+     QObject::connect(&amp;instance, SIGNAL(messageReceived(const QString&amp;)),
+                      &amp;mw, SLOT(handleMessage(const QString&amp;)));
+
+     instance.setActivationWindow(&amp;mw, false);
+     QObject::connect(&amp;mw, SIGNAL(needToShow()), &amp;instance, SLOT(activateWindow()));
+
+     return instance.exec();
+ }</pre>
+<p>If the message could not be sent the application starts up. Note that <tt>false</tt> is passed to the call to setActivationWindow() to prevent automatic activation for every message received, e.g&#x2e; when the application should just print a file. Instead, the message handling function determines whether activation is requested, and signals that by emitting the needToShow() signal. This is then simply connected directly to <a href="qtsingleapplication.html">QtSingleApplication</a>'s activateWindow() slot.</p>
+<p /><address><hr /><div align="center">
+<table width="100%" cellspacing="0" border="0"><tr class="address">
+<td width="30%" align="left">Copyright &copy; 2010 Nokia Corporation and/or its subsidiary(-ies)</td>
+<td width="40%" align="center"><a href="http://qt.nokia.com/doc/trademarks.html">Trademarks</a></td>
+<td width="30%" align="right"><div align="right">Qt Solutions</div></td>
+</tr></table></div></address></body>
+</html>
diff --git a/AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication-example-trivial.html b/AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication-example-trivial.html
new file mode 100644 (file)
index 0000000..b3a1910
--- /dev/null
@@ -0,0 +1,103 @@
+<?xml version="1.0" encoding="iso-8859-1"?>
+<!DOCTYPE html
+    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<!-- trivial.qdoc -->
+<head>
+  <title>A Trivial Example</title>
+  <link href="classic.css" rel="stylesheet" type="text/css" />
+</head>
+<body>
+<table border="0" cellpadding="0" cellspacing="0" width="100%">
+<tr>
+<td align="left" valign="top" width="32"><img src="images/qt-logo.png" align="left" width="57" height="67" border="0" /></td>
+<td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a></td>
+</tr></table><h1 class="title">A Trivial Example<br /><span class="subtitle"></span>
+</h1>
+<p>The application in this example has a log-view that displays messages sent by further instances of the same application.</p>
+<p>The example demonstrates the use of the <a href="qtsingleapplication.html">QtSingleApplication</a> class to detect and communicate with a running instance of the application using the sendMessage() API. The messageReceived() signal is used to display received messages in a <a href="http://qt.nokia.com/doc/4.6/qtextedit.html">QTextEdit</a> log.</p>
+<pre><span class="comment"> /****************************************************************************
+ **
+ ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ ** All rights reserved.
+ **
+ ** Contact: Nokia Corporation (qt-info@nokia.com)
+ **
+ ** This file is part of a Qt Solutions component.
+ **
+ ** You may use this file under the terms of the BSD license as follows:
+ **
+ ** &quot;Redistribution and use in source and binary forms, with or without
+ ** modification, are permitted provided that the following conditions are
+ ** met:
+ **   * Redistributions of source code must retain the above copyright
+ **     notice, this list of conditions and the following disclaimer.
+ **   * Redistributions in binary form must reproduce the above copyright
+ **     notice, this list of conditions and the following disclaimer in
+ **     the documentation and/or other materials provided with the
+ **     distribution.
+ **   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+ **     the names of its contributors may be used to endorse or promote
+ **     products derived from this software without specific prior written
+ **     permission.
+ **
+ ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ ** &quot;AS IS&quot; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.&quot;
+ **
+ ****************************************************************************/</span>
+
+ #include &lt;qtsingleapplication.h&gt;
+ #include &lt;QtGui/QTextEdit&gt;
+
+ class TextEdit : public QTextEdit
+ {
+     Q_OBJECT
+ public:
+     TextEdit(QWidget *parent = 0)
+         : QTextEdit(parent)
+     {}
+ public slots:
+     void append(const QString &amp;str)
+     {
+         QTextEdit::append(str);
+     }
+ };
+
+ #include &quot;main.moc&quot;
+
+ int main(int argc, char **argv)
+ {
+     QtSingleApplication instance(argc, argv);</pre>
+<p>The example has only the <tt>main</tt> entry point function. A <a href="qtsingleapplication.html">QtSingleApplication</a> object is created immediately.</p>
+<pre>     if (instance.sendMessage(&quot;Wake up!&quot;))
+         return 0;</pre>
+<p>If another instance of this application is already running, sendMessage() will succeed, and this instance just exits immediately.</p>
+<pre>     TextEdit logview;
+     logview.setReadOnly(true);
+     logview.show();</pre>
+<p>Otherwise the instance continues as normal and creates the user interface.</p>
+<pre>     instance.setActivationWindow(&amp;logview);
+
+     QObject::connect(&amp;instance, SIGNAL(messageReceived(const QString&amp;)),
+                      &amp;logview, SLOT(append(const QString&amp;)));
+
+     return instance.exec();</pre>
+<p>The <tt>logview</tt> object is also set as the application's activation window. Every time a message is received, the window will be raised and activated automatically.</p>
+<p>The messageReceived() signal is also connected to the <a href="http://qt.nokia.com/doc/4.6/qtextedit.html">QTextEdit</a>'s append() slot. Every message received from further instances of this application will be displayed in the log.</p>
+<p>Finally the event loop is entered.</p>
+<p /><address><hr /><div align="center">
+<table width="100%" cellspacing="0" border="0"><tr class="address">
+<td width="30%" align="left">Copyright &copy; 2010 Nokia Corporation and/or its subsidiary(-ies)</td>
+<td width="40%" align="center"><a href="http://qt.nokia.com/doc/trademarks.html">Trademarks</a></td>
+<td width="30%" align="right"><div align="right">Qt Solutions</div></td>
+</tr></table></div></address></body>
+</html>
diff --git a/AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication-members.html b/AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication-members.html
new file mode 100644 (file)
index 0000000..c995ce3
--- /dev/null
@@ -0,0 +1,235 @@
+<?xml version="1.0" encoding="iso-8859-1"?>
+<!DOCTYPE html
+    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<!-- qtsingleapplication.cpp -->
+<head>
+  <title>List of All Members for QtSingleApplication</title>
+  <link href="classic.css" rel="stylesheet" type="text/css" />
+</head>
+<body>
+<table border="0" cellpadding="0" cellspacing="0" width="100%">
+<tr>
+<td align="left" valign="top" width="32"><img src="images/qt-logo.png" align="left" width="57" height="67" border="0" /></td>
+<td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a></td>
+</tr></table><h1 class="title">List of All Members for QtSingleApplication</h1>
+<p>This is the complete list of members for <a href="qtsingleapplication.html">QtSingleApplication</a>, including inherited members.</p>
+<p><table class="propsummary" width="100%" border="0" cellpadding="0" cellspacing="0">
+<tr><td width="45%" valign="top"><ul>
+<li><div class="fn">enum <b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#ColorSpec-enum">ColorSpec</a></b></div></li>
+<li><div class="fn">enum <b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#Encoding-enum">Encoding</a></b></div></li>
+<li><div class="fn">typedef <b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#EventFilter-typedef">EventFilter</a></b></div></li>
+<li><div class="fn">typedef <b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#QS60MainApplicationFactory-typedef">QS60MainApplicationFactory</a></b></div></li>
+<li><div class="fn">enum <b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#Type-enum">Type</a></b></div></li>
+<li><div class="fn"><b><a href="qtsingleapplication.html#QtSingleApplication">QtSingleApplication</a></b> ( int &amp;, char **, bool )</div></li>
+<li><div class="fn"><b><a href="qtsingleapplication.html#QtSingleApplication-2">QtSingleApplication</a></b> ( const QString &amp;, int &amp;, char ** )</div></li>
+<li><div class="fn"><b><a href="qtsingleapplication.html#QtSingleApplication-3">QtSingleApplication</a></b> ( int &amp;, char **, Type )</div></li>
+<li><div class="fn"><b><a href="qtsingleapplication.html#QtSingleApplication-4">QtSingleApplication</a></b> ( Display *, Qt::HANDLE, Qt::HANDLE )</div></li>
+<li><div class="fn"><b><a href="qtsingleapplication.html#QtSingleApplication-5">QtSingleApplication</a></b> ( Display *, int &amp;, char **, Qt::HANDLE, Qt::HANDLE )</div></li>
+<li><div class="fn"><b><a href="qtsingleapplication.html#QtSingleApplication-6">QtSingleApplication</a></b> ( Display *, const QString &amp;, int, char **, Qt::HANDLE, Qt::HANDLE )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#aboutQt">aboutQt</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#aboutToQuit">aboutToQuit</a></b> ()</div></li>
+<li><div class="fn"><b><a href="qtsingleapplication.html#activateWindow">activateWindow</a></b> ()</div></li>
+<li><div class="fn"><b><a href="qtsingleapplication.html#activationWindow">activationWindow</a></b> () const : QWidget *</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#activeModalWidget">activeModalWidget</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#activePopupWidget">activePopupWidget</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#activeWindow">activeWindow</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#addLibraryPath">addLibraryPath</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#alert">alert</a></b> ( QWidget *, int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#allWidgets">allWidgets</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationDirPath">applicationDirPath</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationFilePath">applicationFilePath</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationName-prop">applicationName</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationPid">applicationPid</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationVersion-prop">applicationVersion</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#arguments">arguments</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#autoMaximizeThreshold-prop">autoMaximizeThreshold</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#autoSipEnabled-prop">autoSipEnabled</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#beep">beep</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#blockSignals">blockSignals</a></b> ( bool )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#changeOverrideCursor">changeOverrideCursor</a></b> ( const QCursor &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#childEvent">childEvent</a></b> ( QChildEvent * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#children">children</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#clipboard">clipboard</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#closeAllWindows">closeAllWindows</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#closingDown">closingDown</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#colorSpec">colorSpec</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#commitData">commitData</a></b> ( QSessionManager &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#commitDataRequest">commitDataRequest</a></b> ( QSessionManager &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#connect">connect</a></b> ( const QObject *, const char *, const QObject *, const char *, Qt::ConnectionType )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#connect-2">connect</a></b> ( const QObject *, const char *, const char *, Qt::ConnectionType ) const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#connectNotify">connectNotify</a></b> ( const char * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#cursorFlashTime-prop">cursorFlashTime</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#customEvent">customEvent</a></b> ( QEvent * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#d_ptr-var">d_ptr</a></b> : </div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#deleteLater">deleteLater</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#desktop">desktop</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#desktopSettingsAware">desktopSettingsAware</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#destroyed">destroyed</a></b> ( QObject * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#disconnect">disconnect</a></b> ( const QObject *, const char *, const QObject *, const char * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#disconnect-2">disconnect</a></b> ( const char *, const QObject *, const char * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#disconnect-3">disconnect</a></b> ( const QObject *, const char * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#disconnectNotify">disconnectNotify</a></b> ( const char * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#doubleClickInterval-prop">doubleClickInterval</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#dumpObjectInfo">dumpObjectInfo</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#dumpObjectTree">dumpObjectTree</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#dynamicPropertyNames">dynamicPropertyNames</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#event">event</a></b> ( QEvent * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#eventFilter">eventFilter</a></b> ( QObject *, QEvent * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#exec">exec</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#exit">exit</a></b> ( int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#filterEvent">filterEvent</a></b> ( void *, long * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#findChild">findChild</a></b> ( const QString &amp; ) const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#findChildren">findChildren</a></b> ( const QString &amp; ) const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#findChildren-2">findChildren</a></b> ( const QRegExp &amp; ) const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#flush">flush</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#focusChanged">focusChanged</a></b> ( QWidget *, QWidget * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#focusWidget">focusWidget</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#font">font</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#font-2">font</a></b> ( const QWidget * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#font-3">font</a></b> ( const char * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#fontDatabaseChanged">fontDatabaseChanged</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#fontMetrics">fontMetrics</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#globalStrut-prop">globalStrut</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#hasPendingEvents">hasPendingEvents</a></b> ()</div></li>
+<li><div class="fn"><b><a href="qtsingleapplication.html#id">id</a></b> () const : QString</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#inherits">inherits</a></b> ( const char * ) const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#inputContext">inputContext</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#installEventFilter">installEventFilter</a></b> ( QObject * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#installTranslator">installTranslator</a></b> ( QTranslator * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#instance">instance</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#isEffectEnabled">isEffectEnabled</a></b> ( Qt::UIEffect )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#isLeftToRight">isLeftToRight</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#isRightToLeft">isRightToLeft</a></b> ()</div></li>
+<li><div class="fn"><b><a href="qtsingleapplication.html#isRunning">isRunning</a></b> () : bool</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#isSessionRestored">isSessionRestored</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#isWidgetType">isWidgetType</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#keyboardInputDirection">keyboardInputDirection</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#keyboardInputInterval-prop">keyboardInputInterval</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#keyboardInputLocale">keyboardInputLocale</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#keyboardModifiers">keyboardModifiers</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#keypadNavigationEnabled">keypadNavigationEnabled</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#killTimer">killTimer</a></b> ( int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#lastWindowClosed">lastWindowClosed</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#layoutDirection-prop">layoutDirection</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#libraryPaths">libraryPaths</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#macEventFilter">macEventFilter</a></b> ( EventHandlerCallRef, EventRef )</div></li>
+<li><div class="fn"><b><a href="qtsingleapplication.html#messageReceived">messageReceived</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#metaObject">metaObject</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#mouseButtons">mouseButtons</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#moveToThread">moveToThread</a></b> ( QThread * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#navigationMode">navigationMode</a></b> ()</div></li>
+</ul></td><td valign="top"><ul>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#notify">notify</a></b> ( QObject *, QEvent * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#objectName-prop">objectName</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#organizationDomain-prop">organizationDomain</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#organizationName-prop">organizationName</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#overrideCursor">overrideCursor</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#palette">palette</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#palette-2">palette</a></b> ( const QWidget * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#palette-3">palette</a></b> ( const char * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#parent">parent</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#postEvent">postEvent</a></b> ( QObject *, QEvent * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#postEvent-2">postEvent</a></b> ( QObject *, QEvent *, int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#processEvents">processEvents</a></b> ( QFlags&lt;QEventLoop::ProcessEventsFlag&gt; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#processEvents-2">processEvents</a></b> ( QFlags&lt;QEventLoop::ProcessEventsFlag&gt;, int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#property">property</a></b> ( const char * ) const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#quit">quit</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#quitOnLastWindowClosed-prop">quitOnLastWindowClosed</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#qwsDecoration">qwsDecoration</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#qwsEventFilter">qwsEventFilter</a></b> ( QWSEvent * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#qwsSetCustomColors">qwsSetCustomColors</a></b> ( QRgb *, int, int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#qwsSetDecoration">qwsSetDecoration</a></b> ( QDecoration * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#qwsSetDecoration-2">qwsSetDecoration</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#receivers">receivers</a></b> ( const char * ) const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#removeEventFilter">removeEventFilter</a></b> ( QObject * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#removeLibraryPath">removeLibraryPath</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#removePostedEvents">removePostedEvents</a></b> ( QObject * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#removePostedEvents-2">removePostedEvents</a></b> ( QObject *, int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#removeTranslator">removeTranslator</a></b> ( QTranslator * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#restoreOverrideCursor">restoreOverrideCursor</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#saveState">saveState</a></b> ( QSessionManager &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#saveStateRequest">saveStateRequest</a></b> ( QSessionManager &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#sendEvent">sendEvent</a></b> ( QObject *, QEvent * )</div></li>
+<li><div class="fn"><b><a href="qtsingleapplication.html#sendMessage">sendMessage</a></b> ( const QString &amp;, int ) : bool</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#sendPostedEvents">sendPostedEvents</a></b> ( QObject *, int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#sendPostedEvents-2">sendPostedEvents</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#sender">sender</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#sessionId">sessionId</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#sessionKey">sessionKey</a></b> () const</div></li>
+<li><div class="fn"><b><a href="qtsingleapplication.html#setActivationWindow">setActivationWindow</a></b> ( QWidget *, bool )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#setActiveWindow">setActiveWindow</a></b> ( QWidget * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationName-prop">setApplicationName</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationVersion-prop">setApplicationVersion</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#setAttribute">setAttribute</a></b> ( Qt::ApplicationAttribute, bool )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#autoMaximizeThreshold-prop">setAutoMaximizeThreshold</a></b> ( const int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#autoSipEnabled-prop">setAutoSipEnabled</a></b> ( const bool )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#setColorSpec">setColorSpec</a></b> ( int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#cursorFlashTime-prop">setCursorFlashTime</a></b> ( int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#setDesktopSettingsAware">setDesktopSettingsAware</a></b> ( bool )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#doubleClickInterval-prop">setDoubleClickInterval</a></b> ( int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#setEffectEnabled">setEffectEnabled</a></b> ( Qt::UIEffect, bool )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#setEventFilter">setEventFilter</a></b> ( EventFilter )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#setFont">setFont</a></b> ( const QFont &amp;, const char * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#globalStrut-prop">setGlobalStrut</a></b> ( const QSize &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#setGraphicsSystem">setGraphicsSystem</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#setInputContext">setInputContext</a></b> ( QInputContext * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#keyboardInputInterval-prop">setKeyboardInputInterval</a></b> ( int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#layoutDirection-prop">setLayoutDirection</a></b> ( Qt::LayoutDirection )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#setLibraryPaths">setLibraryPaths</a></b> ( const QStringList &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#setNavigationMode">setNavigationMode</a></b> ( Qt::NavigationMode )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#objectName-prop">setObjectName</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#organizationDomain-prop">setOrganizationDomain</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#organizationName-prop">setOrganizationName</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#setOverrideCursor">setOverrideCursor</a></b> ( const QCursor &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#setPalette">setPalette</a></b> ( const QPalette &amp;, const char * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#setParent">setParent</a></b> ( QObject * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#setProperty">setProperty</a></b> ( const char *, const QVariant &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#quitOnLastWindowClosed-prop">setQuitOnLastWindowClosed</a></b> ( bool )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#startDragDistance-prop">setStartDragDistance</a></b> ( int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#startDragTime-prop">setStartDragTime</a></b> ( int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#setStyle">setStyle</a></b> ( QStyle * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#setStyle-2">setStyle</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#styleSheet-prop">setStyleSheet</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#wheelScrollLines-prop">setWheelScrollLines</a></b> ( int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#windowIcon-prop">setWindowIcon</a></b> ( const QIcon &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#signalsBlocked">signalsBlocked</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#startDragDistance-prop">startDragDistance</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#startDragTime-prop">startDragTime</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#startTimer">startTimer</a></b> ( int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#startingUp">startingUp</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#staticMetaObject-var">staticMetaObject</a></b> : </div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#staticQtMetaObject-var">staticQtMetaObject</a></b> : </div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#style">style</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#styleSheet-prop">styleSheet</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#symbianEventFilter">symbianEventFilter</a></b> ( const QSymbianEvent * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#symbianProcessEvent">symbianProcessEvent</a></b> ( const QSymbianEvent * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#syncX">syncX</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#testAttribute">testAttribute</a></b> ( Qt::ApplicationAttribute )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#thread">thread</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#timerEvent">timerEvent</a></b> ( QTimerEvent * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#topLevelAt">topLevelAt</a></b> ( const QPoint &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#topLevelAt-2">topLevelAt</a></b> ( int, int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#topLevelWidgets">topLevelWidgets</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#tr">tr</a></b> ( const char *, const char *, int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#trUtf8">trUtf8</a></b> ( const char *, const char *, int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#translate">translate</a></b> ( const char *, const char *, const char *, Encoding, int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#translate-2">translate</a></b> ( const char *, const char *, const char *, Encoding )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#type">type</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#wheelScrollLines-prop">wheelScrollLines</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#widgetAt">widgetAt</a></b> ( const QPoint &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#widgetAt-4">widgetAt</a></b> ( int, int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#winEventFilter">winEventFilter</a></b> ( MSG *, long * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#windowIcon-prop">windowIcon</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#x11EventFilter">x11EventFilter</a></b> ( XEvent * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qapplication.html#x11ProcessEvent">x11ProcessEvent</a></b> ( XEvent * )</div></li>
+</ul>
+</td></tr>
+</table></p>
+<p /><address><hr /><div align="center">
+<table width="100%" cellspacing="0" border="0"><tr class="address">
+<td width="30%" align="left">Copyright &copy; 2010 Nokia Corporation and/or its subsidiary(-ies)</td>
+<td width="40%" align="center"><a href="http://qt.nokia.com/doc/trademarks.html">Trademarks</a></td>
+<td width="30%" align="right"><div align="right">Qt Solutions</div></td>
+</tr></table></div></address></body>
+</html>
diff --git a/AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication-obsolete.html b/AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication-obsolete.html
new file mode 100644 (file)
index 0000000..0d07dfa
--- /dev/null
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="iso-8859-1"?>
+<!DOCTYPE html
+    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<!-- qtsingleapplication.cpp -->
+<head>
+  <title>Obsolete Members for QtSingleApplication</title>
+  <link href="classic.css" rel="stylesheet" type="text/css" />
+</head>
+<body>
+<table border="0" cellpadding="0" cellspacing="0" width="100%">
+<tr>
+<td align="left" valign="top" width="32"><img src="images/qt-logo.png" align="left" width="57" height="67" border="0" /></td>
+<td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a></td>
+</tr></table><h1 class="title">Obsolete Members for QtSingleApplication</h1>
+<p><b>The following class members are obsolete.</b> They are provided to keep old source code working. We strongly advise against using them in new code.</p>
+<p><ul><li><a href="qtsingleapplication.html">QtSingleApplication class reference</a></li></ul></p>
+<h2>Public Functions</h2>
+<table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width="100%">
+<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><b><a href="qtsingleapplication-obsolete.html#initialize">initialize</a></b> ( bool <i>dummy</i> = true )&nbsp;&nbsp;<tt> (obsolete)</tt></td></tr>
+</table>
+<hr />
+<h2>Member Function Documentation</h2>
+<h3 class="fn"><a name="initialize"></a>void QtSingleApplication::initialize ( bool <i>dummy</i> = true )</h3>
+<p /><address><hr /><div align="center">
+<table width="100%" cellspacing="0" border="0"><tr class="address">
+<td width="30%" align="left">Copyright &copy; 2010 Nokia Corporation and/or its subsidiary(-ies)</td>
+<td width="40%" align="center"><a href="http://qt.nokia.com/doc/trademarks.html">Trademarks</a></td>
+<td width="30%" align="right"><div align="right">Qt Solutions</div></td>
+</tr></table></div></address></body>
+</html>
diff --git a/AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication.dcf b/AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication.dcf
new file mode 100644 (file)
index 0000000..d81f87f
--- /dev/null
@@ -0,0 +1,40 @@
+<!DOCTYPE DCF>
+<DCF ref="index.html" icon="qtsingleapplication.png" imagedir="../../gif" title="Qt Solutions: Single Application Documentation">
+<section ref="classes.html" title="Classes">
+    <section ref="qtsingleapplication.html" title="QtSingleApplication Class Reference">
+        <keyword ref="qtsingleapplication.html">QtSingleApplication</keyword>
+        <keyword ref="qtsingleapplication.html#activateWindow">activateWindow</keyword>
+        <keyword ref="qtsingleapplication.html#activationWindow">activationWindow</keyword>
+        <keyword ref="qtsingleapplication.html#id">id</keyword>
+        <keyword ref="qtsingleapplication.html#isRunning">isRunning</keyword>
+        <keyword ref="qtsingleapplication.html#messageReceived">messageReceived</keyword>
+        <keyword ref="qtsingleapplication.html#sendMessage">sendMessage</keyword>
+        <keyword ref="qtsingleapplication.html#setActivationWindow">setActivationWindow</keyword>
+        <section ref="qtsingleapplication-members.html" title="List of all members"/>
+        <section ref="qtsingleapplication-obsolete.html" title="Obsolete members"/>
+    </section>
+    <section ref="qtsinglecoreapplication.html" title="QtSingleCoreApplication Class Reference">
+        <keyword ref="qtsinglecoreapplication.html">QtSingleCoreApplication</keyword>
+        <keyword ref="qtsinglecoreapplication.html#id">id</keyword>
+        <keyword ref="qtsinglecoreapplication.html#isRunning">isRunning</keyword>
+        <keyword ref="qtsinglecoreapplication.html#messageReceived">messageReceived</keyword>
+        <keyword ref="qtsinglecoreapplication.html#sendMessage">sendMessage</keyword>
+        <section ref="qtsinglecoreapplication-members.html" title="List of all members"/>
+    </section>
+</section>
+<section ref="overviews.html" title="Overviews">
+    <section ref="qtsinglecoreapplication-example-console.html" title="A non-GUI example">
+        <keyword ref="qtsinglecoreapplication-example-console.html">A non-GUI example</keyword>
+    </section>
+    <section ref="qtsingleapplication-example-trivial.html" title="A Trivial Example">
+        <keyword ref="qtsingleapplication-example-trivial.html">A Trivial Example</keyword>
+    </section>
+    <section ref="qtsingleapplication-example-loader.html" title="Loading Documents">
+        <keyword ref="qtsingleapplication-example-loader.html">Loading Documents</keyword>
+    </section>
+    <section ref="index.html" title="Single Application">
+        <keyword ref="index.html">Single Application</keyword>
+    </section>
+</section>
+<section ref="examples.html" title="Tutorial &amp; Examples"/>
+</DCF>
diff --git a/AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication.html b/AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication.html
new file mode 100644 (file)
index 0000000..2754a3b
--- /dev/null
@@ -0,0 +1,162 @@
+<?xml version="1.0" encoding="iso-8859-1"?>
+<!DOCTYPE html
+    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<!-- qtsingleapplication.cpp -->
+<head>
+  <title>QtSingleApplication Class Reference</title>
+  <link href="classic.css" rel="stylesheet" type="text/css" />
+</head>
+<body>
+<table border="0" cellpadding="0" cellspacing="0" width="100%">
+<tr>
+<td align="left" valign="top" width="32"><img src="images/qt-logo.png" align="left" width="57" height="67" border="0" /></td>
+<td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a></td>
+</tr></table><h1 class="title">QtSingleApplication Class Reference</h1>
+<p>The QtSingleApplication class provides an API to detect and communicate with running instances of an application. <a href="#details">More...</a></p>
+<pre> #include &lt;QtSingleApplication&gt;</pre><p>Inherits <a href="http://qt.nokia.com/doc/4.6/qapplication.html">QApplication</a>.</p>
+<ul>
+<li><a href="qtsingleapplication-members.html">List of all members, including inherited members</a></li>
+<li><a href="qtsingleapplication-obsolete.html">Obsolete members</a></li>
+</ul>
+<hr />
+<a name="public-functions"></a>
+<h2>Public Functions</h2>
+<table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width="100%">
+<tr><td class="memItemLeft" align="right" valign="top"></td><td class="memItemRight" valign="bottom"><b><a href="qtsingleapplication.html#QtSingleApplication">QtSingleApplication</a></b> ( int &amp; <i>argc</i>, char ** <i>argv</i>, bool <i>GUIenabled</i> = true )</td></tr>
+<tr><td class="memItemLeft" align="right" valign="top"></td><td class="memItemRight" valign="bottom"><b><a href="qtsingleapplication.html#QtSingleApplication-2">QtSingleApplication</a></b> ( const QString &amp; <i>appId</i>, int &amp; <i>argc</i>, char ** <i>argv</i> )</td></tr>
+<tr><td class="memItemLeft" align="right" valign="top"></td><td class="memItemRight" valign="bottom"><b><a href="qtsingleapplication.html#QtSingleApplication-3">QtSingleApplication</a></b> ( int &amp; <i>argc</i>, char ** <i>argv</i>, Type <i>type</i> )</td></tr>
+<tr><td class="memItemLeft" align="right" valign="top"></td><td class="memItemRight" valign="bottom"><b><a href="qtsingleapplication.html#QtSingleApplication-4">QtSingleApplication</a></b> ( Display * <i>dpy</i>, Qt::HANDLE <i>visual</i> = 0, Qt::HANDLE <i>cmap</i> = 0 )</td></tr>
+<tr><td class="memItemLeft" align="right" valign="top"></td><td class="memItemRight" valign="bottom"><b><a href="qtsingleapplication.html#QtSingleApplication-5">QtSingleApplication</a></b> ( Display * <i>dpy</i>, int &amp; <i>argc</i>, char ** <i>argv</i>, Qt::HANDLE <i>visual</i> = 0, Qt::HANDLE <i>cmap</i> = 0 )</td></tr>
+<tr><td class="memItemLeft" align="right" valign="top"></td><td class="memItemRight" valign="bottom"><b><a href="qtsingleapplication.html#QtSingleApplication-6">QtSingleApplication</a></b> ( Display * <i>dpy</i>, const QString &amp; <i>appId</i>, int <i>argc</i>, char ** <i>argv</i>, Qt::HANDLE <i>visual</i> = 0, Qt::HANDLE <i>cmap</i> = 0 )</td></tr>
+<tr><td class="memItemLeft" align="right" valign="top">QWidget * </td><td class="memItemRight" valign="bottom"><b><a href="qtsingleapplication.html#activationWindow">activationWindow</a></b> () const</td></tr>
+<tr><td class="memItemLeft" align="right" valign="top">QString </td><td class="memItemRight" valign="bottom"><b><a href="qtsingleapplication.html#id">id</a></b> () const</td></tr>
+<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><b><a href="qtsingleapplication.html#isRunning">isRunning</a></b> ()</td></tr>
+<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><b><a href="qtsingleapplication.html#setActivationWindow">setActivationWindow</a></b> ( QWidget * <i>aw</i>, bool <i>activateOnMessage</i> = true )</td></tr>
+</table>
+<ul>
+<li><div bar="2" class="fn"></div>16 public functions inherited from <a href="http://qt.nokia.com/doc/4.6/qapplication.html#public-functions">QApplication</a></li>
+<li><div bar="2" class="fn"></div>4 public functions inherited from <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#public-functions">QCoreApplication</a></li>
+<li><div bar="2" class="fn"></div>29 public functions inherited from <a href="http://qt.nokia.com/doc/4.6/qobject.html#public-functions">QObject</a></li>
+</ul>
+<hr />
+<a name="public-slots"></a>
+<h2>Public Slots</h2>
+<table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width="100%">
+<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><b><a href="qtsingleapplication.html#activateWindow">activateWindow</a></b> ()</td></tr>
+<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><b><a href="qtsingleapplication.html#sendMessage">sendMessage</a></b> ( const QString &amp; <i>message</i>, int <i>timeout</i> = 5000 )</td></tr>
+</table>
+<ul>
+<li><div bar="2" class="fn"></div>7 public slots inherited from <a href="http://qt.nokia.com/doc/4.6/qapplication.html#public-slots">QApplication</a></li>
+<li><div bar="2" class="fn"></div>1 public slot inherited from <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#public-slots">QCoreApplication</a></li>
+<li><div bar="2" class="fn"></div>1 public slot inherited from <a href="http://qt.nokia.com/doc/4.6/qobject.html#public-slots">QObject</a></li>
+</ul>
+<hr />
+<a name="signals"></a>
+<h2>Signals</h2>
+<table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width="100%">
+<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><b><a href="qtsingleapplication.html#messageReceived">messageReceived</a></b> ( const QString &amp; <i>message</i> )</td></tr>
+</table>
+<ul>
+<li><div bar="2" class="fn"></div>5 signals inherited from <a href="http://qt.nokia.com/doc/4.6/qapplication.html#signals">QApplication</a></li>
+<li><div bar="2" class="fn"></div>1 signal inherited from <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#signals">QCoreApplication</a></li>
+<li><div bar="2" class="fn"></div>1 signal inherited from <a href="http://qt.nokia.com/doc/4.6/qobject.html#signals">QObject</a></li>
+</ul>
+<h3>Additional Inherited Members</h3>
+<ul>
+<li><div class="fn"></div>13 properties inherited from <a href="http://qt.nokia.com/doc/4.6/qapplication.html#properties">QApplication</a></li>
+<li><div class="fn"></div>4 properties inherited from <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#properties">QCoreApplication</a></li>
+<li><div class="fn"></div>1 property inherited from <a href="http://qt.nokia.com/doc/4.6/qobject.html#properties">QObject</a></li>
+<li><div class="fn"></div>1 public type inherited from <a href="http://qt.nokia.com/doc/4.6/qobject.html#public-variables">QObject</a></li>
+<li><div class="fn"></div>73 static public members inherited from <a href="http://qt.nokia.com/doc/4.6/qapplication.html#static-public-members">QApplication</a></li>
+<li><div class="fn"></div>38 static public members inherited from <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#static-public-members">QCoreApplication</a></li>
+<li><div class="fn"></div>4 static public members inherited from <a href="http://qt.nokia.com/doc/4.6/qobject.html#static-public-members">QObject</a></li>
+<li><div class="fn"></div>1 protected function inherited from <a href="http://qt.nokia.com/doc/4.6/qapplication.html#protected-functions">QApplication</a></li>
+<li><div class="fn"></div>1 protected function inherited from <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#protected-functions">QCoreApplication</a></li>
+<li><div class="fn"></div>7 protected functions inherited from <a href="http://qt.nokia.com/doc/4.6/qobject.html#protected-functions">QObject</a></li>
+<li><div class="fn"></div>2 protected variables inherited from <a href="http://qt.nokia.com/doc/4.6/qobject.html#protected-variables">QObject</a></li>
+</ul>
+<a name="details"></a>
+<hr />
+<h2>Detailed Description</h2>
+<p>The QtSingleApplication class provides an API to detect and communicate with running instances of an application.</p>
+<p>This class allows you to create applications where only one instance should be running at a time. I.e&#x2e;, if the user tries to launch another instance, the already running instance will be activated instead. Another usecase is a client-server system, where the first started instance will assume the role of server, and the later instances will act as clients of that server.</p>
+<p>By default, the full path of the executable file is used to determine whether two processes are instances of the same application. You can also provide an explicit identifier string that will be compared instead.</p>
+<p>The application should create the QtSingleApplication object early in the startup phase, and call <a href="qtsingleapplication.html#isRunning">isRunning</a>() to find out if another instance of this application is already running. If <a href="qtsingleapplication.html#isRunning">isRunning</a>() returns false, it means that no other instance is running, and this instance has assumed the role as the running instance. In this case, the application should continue with the initialization of the application user interface before entering the event loop with <a href="http://qt.nokia.com/doc/4.6/qapplication.html#exec">exec</a>(), as normal.</p>
+<p>The <a href="qtsingleapplication.html#messageReceived">messageReceived</a>() signal will be emitted when the running application receives messages from another instance of the same application. When a message is received it might be helpful to the user to raise the application so that it becomes visible. To facilitate this, QtSingleApplication provides the <a href="qtsingleapplication.html#setActivationWindow">setActivationWindow</a>() function and the <a href="qtsingleapplication.html#activateWindow">activateWindow</a>() slot.</p>
+<p>If <a href="qtsingleapplication.html#isRunning">isRunning</a>() returns true, another instance is already running. It may be alerted to the fact that another instance has started by using the <a href="qtsingleapplication.html#sendMessage">sendMessage</a>() function. Also data such as startup parameters (e.g&#x2e; the name of the file the user wanted this new instance to open) can be passed to the running instance with this function. Then, the application should terminate (or enter client mode).</p>
+<p>If <a href="qtsingleapplication.html#isRunning">isRunning</a>() returns true, but <a href="qtsingleapplication.html#sendMessage">sendMessage</a>() fails, that is an indication that the running instance is frozen.</p>
+<p>Here's an example that shows how to convert an existing application to use QtSingleApplication. It is very simple and does not make use of all QtSingleApplication's functionality (see the examples for that).</p>
+<pre><span class="comment"> // Original</span>
+ int main(int argc, char **argv)
+ {
+     QApplication app(argc, argv);
+
+     MyMainWidget mmw;
+     mmw.show();
+     return app.exec();
+ }
+
+<span class="comment"> // Single instance</span>
+ int main(int argc, char **argv)
+ {
+     QtSingleApplication app(argc, argv);
+
+     if (app.isRunning())
+         return !app.sendMessage(someDataString);
+
+     MyMainWidget mmw;
+     app.setActivationWindow(&amp;mmw);
+     mmw.show();
+     return app.exec();
+ }</pre>
+<p>Once this QtSingleApplication instance is destroyed (normally when the process exits or crashes), when the user next attempts to run the application this instance will not, of course, be encountered. The next instance to call <a href="qtsingleapplication.html#isRunning">isRunning</a>() or <a href="qtsingleapplication.html#sendMessage">sendMessage</a>() will assume the role as the new running instance.</p>
+<p>For console (non-GUI) applications, <a href="qtsinglecoreapplication.html">QtSingleCoreApplication</a> may be used instead of this class, to avoid the dependency on the <a href="http://qt.nokia.com/doc/4.6/qtgui.html">QtGui</a> library.</p>
+<p>See also <a href="qtsinglecoreapplication.html">QtSingleCoreApplication</a>.</p>
+<hr />
+<h2>Member Function Documentation</h2>
+<h3 class="fn"><a name="QtSingleApplication"></a>QtSingleApplication::QtSingleApplication ( int &amp; <i>argc</i>, char ** <i>argv</i>, bool <i>GUIenabled</i> = true )</h3>
+<p>Creates a <a href="qtsingleapplication.html">QtSingleApplication</a> object. The application identifier will be <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationFilePath">QCoreApplication::applicationFilePath</a>(). <i>argc</i>, <i>argv</i>, and <i>GUIenabled</i> are passed on to the QAppliation constructor.</p>
+<p>If you are creating a console application (i.e&#x2e; setting <i>GUIenabled</i> to false), you may consider using <a href="qtsinglecoreapplication.html">QtSingleCoreApplication</a> instead.</p>
+<h3 class="fn"><a name="QtSingleApplication-2"></a>QtSingleApplication::QtSingleApplication ( const <a href="http://qt.nokia.com/doc/4.6/qstring.html">QString</a> &amp; <i>appId</i>, int &amp; <i>argc</i>, char ** <i>argv</i> )</h3>
+<p>Creates a <a href="qtsingleapplication.html">QtSingleApplication</a> object with the application identifier <i>appId</i>. <i>argc</i> and <i>argv</i> are passed on to the QAppliation constructor.</p>
+<h3 class="fn"><a name="QtSingleApplication-3"></a>QtSingleApplication::QtSingleApplication ( int &amp; <i>argc</i>, char ** <i>argv</i>, <a href="http://qt.nokia.com/doc/4.6/qapplication.html#Type-enum">Type</a> <i>type</i> )</h3>
+<p>Creates a <a href="qtsingleapplication.html">QtSingleApplication</a> object. The application identifier will be <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationFilePath">QCoreApplication::applicationFilePath</a>(). <i>argc</i>, <i>argv</i>, and <i>type</i> are passed on to the QAppliation constructor.</p>
+<h3 class="fn"><a name="QtSingleApplication-4"></a>QtSingleApplication::QtSingleApplication ( Display * <i>dpy</i>, <a href="http://qt.nokia.com/doc/4.6/qt.html#HANDLE-typedef">Qt::HANDLE</a> <i>visual</i> = 0, <a href="http://qt.nokia.com/doc/4.6/qt.html#HANDLE-typedef">Qt::HANDLE</a> <i>cmap</i> = 0 )</h3>
+<p>Special constructor for X11, ref. the documentation of <a href="http://qt.nokia.com/doc/4.6/qapplication.html">QApplication</a>'s corresponding constructor. The application identifier will be <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationFilePath">QCoreApplication::applicationFilePath</a>(). <i>dpy</i>, <i>visual</i>, and <i>cmap</i> are passed on to the <a href="http://qt.nokia.com/doc/4.6/qapplication.html">QApplication</a> constructor.</p>
+<h3 class="fn"><a name="QtSingleApplication-5"></a>QtSingleApplication::QtSingleApplication ( Display * <i>dpy</i>, int &amp; <i>argc</i>, char ** <i>argv</i>, <a href="http://qt.nokia.com/doc/4.6/qt.html#HANDLE-typedef">Qt::HANDLE</a> <i>visual</i> = 0, <a href="http://qt.nokia.com/doc/4.6/qt.html#HANDLE-typedef">Qt::HANDLE</a> <i>cmap</i> = 0 )</h3>
+<p>Special constructor for X11, ref. the documentation of <a href="http://qt.nokia.com/doc/4.6/qapplication.html">QApplication</a>'s corresponding constructor. The application identifier will be <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationFilePath">QCoreApplication::applicationFilePath</a>(). <i>dpy</i>, <i>argc</i>, <i>argv</i>, <i>visual</i>, and <i>cmap</i> are passed on to the <a href="http://qt.nokia.com/doc/4.6/qapplication.html">QApplication</a> constructor.</p>
+<h3 class="fn"><a name="QtSingleApplication-6"></a>QtSingleApplication::QtSingleApplication ( Display * <i>dpy</i>, const <a href="http://qt.nokia.com/doc/4.6/qstring.html">QString</a> &amp; <i>appId</i>, int <i>argc</i>, char ** <i>argv</i>, <a href="http://qt.nokia.com/doc/4.6/qt.html#HANDLE-typedef">Qt::HANDLE</a> <i>visual</i> = 0, <a href="http://qt.nokia.com/doc/4.6/qt.html#HANDLE-typedef">Qt::HANDLE</a> <i>cmap</i> = 0 )</h3>
+<p>Special constructor for X11, ref. the documentation of <a href="http://qt.nokia.com/doc/4.6/qapplication.html">QApplication</a>'s corresponding constructor. The application identifier will be <i>appId</i>. <i>dpy</i>, <i>argc</i>, <i>argv</i>, <i>visual</i>, and <i>cmap</i> are passed on to the <a href="http://qt.nokia.com/doc/4.6/qapplication.html">QApplication</a> constructor.</p>
+<h3 class="fn"><a name="activateWindow"></a>void QtSingleApplication::activateWindow ()&nbsp;&nbsp;<tt> [slot]</tt></h3>
+<p>De-minimizes, raises, and activates this application's activation window. This function does nothing if no activation window has been set.</p>
+<p>This is a convenience function to show the user that this application instance has been activated when he has tried to start another instance.</p>
+<p>This function should typically be called in response to the <a href="qtsingleapplication.html#messageReceived">messageReceived</a>() signal. By default, that will happen automatically, if an activation window has been set.</p>
+<p>See also <a href="qtsingleapplication.html#setActivationWindow">setActivationWindow</a>(), <a href="qtsingleapplication.html#messageReceived">messageReceived</a>(), and <a href="qtsingleapplication-obsolete.html#initialize" class="obsolete">initialize</a>().</p>
+<h3 class="fn"><a name="activationWindow"></a><a href="http://qt.nokia.com/doc/4.6/qwidget.html">QWidget</a> * QtSingleApplication::activationWindow () const</h3>
+<p>Returns the applications activation window if one has been set by calling <a href="qtsingleapplication.html#setActivationWindow">setActivationWindow</a>(), otherwise returns 0.</p>
+<p>See also <a href="qtsingleapplication.html#setActivationWindow">setActivationWindow</a>().</p>
+<h3 class="fn"><a name="id"></a><a href="http://qt.nokia.com/doc/4.6/qstring.html">QString</a> QtSingleApplication::id () const</h3>
+<p>Returns the application identifier. Two processes with the same identifier will be regarded as instances of the same application.</p>
+<h3 class="fn"><a name="isRunning"></a>bool QtSingleApplication::isRunning ()</h3>
+<p>Returns true if another instance of this application is running; otherwise false.</p>
+<p>This function does not find instances of this application that are being run by a different user (on Windows: that are running in another session).</p>
+<p>See also <a href="qtsingleapplication.html#sendMessage">sendMessage</a>().</p>
+<h3 class="fn"><a name="messageReceived"></a>void QtSingleApplication::messageReceived ( const <a href="http://qt.nokia.com/doc/4.6/qstring.html">QString</a> &amp; <i>message</i> )&nbsp;&nbsp;<tt> [signal]</tt></h3>
+<p>This signal is emitted when the current instance receives a <i>message</i> from another instance of this application.</p>
+<p>See also <a href="qtsingleapplication.html#sendMessage">sendMessage</a>(), <a href="qtsingleapplication.html#setActivationWindow">setActivationWindow</a>(), and <a href="qtsingleapplication.html#activateWindow">activateWindow</a>().</p>
+<h3 class="fn"><a name="sendMessage"></a>bool QtSingleApplication::sendMessage ( const <a href="http://qt.nokia.com/doc/4.6/qstring.html">QString</a> &amp; <i>message</i>, int <i>timeout</i> = 5000 )&nbsp;&nbsp;<tt> [slot]</tt></h3>
+<p>Tries to send the text <i>message</i> to the currently running instance. The <a href="qtsingleapplication.html">QtSingleApplication</a> object in the running instance will emit the <a href="qtsingleapplication.html#messageReceived">messageReceived</a>() signal when it receives the message.</p>
+<p>This function returns true if the message has been sent to, and processed by, the current instance. If there is no instance currently running, or if the running instance fails to process the message within <i>timeout</i> milliseconds, this function return false.</p>
+<p>See also <a href="qtsingleapplication.html#isRunning">isRunning</a>() and <a href="qtsingleapplication.html#messageReceived">messageReceived</a>().</p>
+<h3 class="fn"><a name="setActivationWindow"></a>void QtSingleApplication::setActivationWindow ( <a href="http://qt.nokia.com/doc/4.6/qwidget.html">QWidget</a> * <i>aw</i>, bool <i>activateOnMessage</i> = true )</h3>
+<p>Sets the activation window of this application to <i>aw</i>. The activation window is the widget that will be activated by <a href="qtsingleapplication.html#activateWindow">activateWindow</a>(). This is typically the application's main window.</p>
+<p>If <i>activateOnMessage</i> is true (the default), the window will be activated automatically every time a message is received, just prior to the <a href="qtsingleapplication.html#messageReceived">messageReceived</a>() signal being emitted.</p>
+<p>See also <a href="qtsingleapplication.html#activationWindow">activationWindow</a>(), <a href="qtsingleapplication.html#activateWindow">activateWindow</a>(), and <a href="qtsingleapplication.html#messageReceived">messageReceived</a>().</p>
+<p /><address><hr /><div align="center">
+<table width="100%" cellspacing="0" border="0"><tr class="address">
+<td width="30%" align="left">Copyright &copy; 2010 Nokia Corporation and/or its subsidiary(-ies)</td>
+<td width="40%" align="center"><a href="http://qt.nokia.com/doc/trademarks.html">Trademarks</a></td>
+<td width="30%" align="right"><div align="right">Qt Solutions</div></td>
+</tr></table></div></address></body>
+</html>
diff --git a/AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication.index b/AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication.index
new file mode 100644 (file)
index 0000000..56052c2
--- /dev/null
@@ -0,0 +1,90 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE QDOCINDEX>
+<INDEX url="" title="Qt Solutions: Single Application Documentation" version="">
+    <namespace access="public" threadsafety="unspecified" status="commendable" name="" href="" location="" module="">
+        <class access="public" threadsafety="unspecified" status="commendable" name="QtSingleCoreApplication" href="qtsinglecoreapplication.html" location="qtsinglecoreapplication.h" bases="QCoreApplication" module="">
+            <function access="public" threadsafety="unspecified" status="commendable" name="QtSingleCoreApplication" fullname="QtSingleCoreApplication::QtSingleCoreApplication" href="qtsinglecoreapplication.html#QtSingleCoreApplication" location="qtsinglecoreapplication.h" virtual="non" meta="constructor" const="false" static="false" overload="false" type="" signature="QtSingleCoreApplication(int &amp; argc, char ** argv)">
+                <parameter left="int &amp;" right="" name="argc" default=""/>
+                <parameter left="char **" right="" name="argv" default=""/>
+            </function>
+            <function access="public" threadsafety="unspecified" status="commendable" name="QtSingleCoreApplication" fullname="QtSingleCoreApplication::QtSingleCoreApplication" href="qtsinglecoreapplication.html#QtSingleCoreApplication-2" location="qtsinglecoreapplication.h" virtual="non" meta="constructor" const="false" static="false" overload="true" overload-number="2" type="" signature="QtSingleCoreApplication(const QString &amp; appId, int &amp; argc, char ** argv)">
+                <parameter left="const QString &amp;" right="" name="appId" default=""/>
+                <parameter left="int &amp;" right="" name="argc" default=""/>
+                <parameter left="char **" right="" name="argv" default=""/>
+            </function>
+            <function access="public" threadsafety="unspecified" status="commendable" name="isRunning" fullname="QtSingleCoreApplication::isRunning" href="qtsinglecoreapplication.html#isRunning" location="qtsinglecoreapplication.h" virtual="non" meta="plain" const="false" static="false" overload="false" type="bool" signature="isRunning()"/>
+            <function access="public" threadsafety="unspecified" status="commendable" name="id" fullname="QtSingleCoreApplication::id" href="qtsinglecoreapplication.html#id" location="qtsinglecoreapplication.h" virtual="non" meta="plain" const="true" static="false" overload="false" type="QString" signature="id() const"/>
+            <function access="public" threadsafety="unspecified" status="commendable" name="sendMessage" fullname="QtSingleCoreApplication::sendMessage" href="qtsinglecoreapplication.html#sendMessage" location="qtsinglecoreapplication.h" virtual="non" meta="slot" const="false" static="false" overload="false" type="bool" signature="sendMessage(const QString &amp; message, int timeout)">
+                <parameter left="const QString &amp;" right="" name="message" default=""/>
+                <parameter left="int" right="" name="timeout" default="5000"/>
+            </function>
+            <function access="public" threadsafety="unspecified" status="commendable" name="messageReceived" fullname="QtSingleCoreApplication::messageReceived" href="qtsinglecoreapplication.html#messageReceived" location="qtsinglecoreapplication.h" virtual="non" meta="signal" const="false" static="false" overload="false" type="void" signature="messageReceived(const QString &amp; message)">
+                <parameter left="const QString &amp;" right="" name="message" default=""/>
+            </function>
+        </class>
+        <class access="public" threadsafety="unspecified" status="commendable" name="QtSingleApplication" href="qtsingleapplication.html" location="qtsingleapplication.h" bases="QApplication" module="">
+            <function access="public" threadsafety="unspecified" status="commendable" name="QtSingleApplication" fullname="QtSingleApplication::QtSingleApplication" href="qtsingleapplication.html#QtSingleApplication" location="qtsingleapplication.h" virtual="non" meta="constructor" const="false" static="false" overload="false" type="" signature="QtSingleApplication(int &amp; argc, char ** argv, bool GUIenabled)">
+                <parameter left="int &amp;" right="" name="argc" default=""/>
+                <parameter left="char **" right="" name="argv" default=""/>
+                <parameter left="bool" right="" name="GUIenabled" default="true"/>
+            </function>
+            <function access="public" threadsafety="unspecified" status="commendable" name="QtSingleApplication" fullname="QtSingleApplication::QtSingleApplication" href="qtsingleapplication.html#QtSingleApplication-2" location="qtsingleapplication.h" virtual="non" meta="constructor" const="false" static="false" overload="true" overload-number="2" type="" signature="QtSingleApplication(const QString &amp; appId, int &amp; argc, char ** argv)">
+                <parameter left="const QString &amp;" right="" name="appId" default=""/>
+                <parameter left="int &amp;" right="" name="argc" default=""/>
+                <parameter left="char **" right="" name="argv" default=""/>
+            </function>
+            <function access="public" threadsafety="unspecified" status="commendable" name="QtSingleApplication" fullname="QtSingleApplication::QtSingleApplication" href="qtsingleapplication.html#QtSingleApplication-3" location="qtsingleapplication.h" virtual="non" meta="constructor" const="false" static="false" overload="true" overload-number="3" type="" signature="QtSingleApplication(int &amp; argc, char ** argv, Type type)">
+                <parameter left="int &amp;" right="" name="argc" default=""/>
+                <parameter left="char **" right="" name="argv" default=""/>
+                <parameter left="Type" right="" name="type" default=""/>
+            </function>
+            <function access="public" threadsafety="unspecified" status="commendable" name="QtSingleApplication" fullname="QtSingleApplication::QtSingleApplication" href="qtsingleapplication.html#QtSingleApplication-4" location="qtsingleapplication.h" virtual="non" meta="constructor" const="false" static="false" overload="true" overload-number="4" type="" signature="QtSingleApplication(Display * dpy, Qt::HANDLE visual, Qt::HANDLE cmap)">
+                <parameter left="Display *" right="" name="dpy" default=""/>
+                <parameter left="Qt::HANDLE" right="" name="visual" default="0"/>
+                <parameter left="Qt::HANDLE" right="" name="cmap" default="0"/>
+            </function>
+            <function access="public" threadsafety="unspecified" status="commendable" name="QtSingleApplication" fullname="QtSingleApplication::QtSingleApplication" href="qtsingleapplication.html#QtSingleApplication-5" location="qtsingleapplication.h" virtual="non" meta="constructor" const="false" static="false" overload="true" overload-number="5" type="" signature="QtSingleApplication(Display * dpy, int &amp; argc, char ** argv, Qt::HANDLE visual, Qt::HANDLE cmap)">
+                <parameter left="Display *" right="" name="dpy" default=""/>
+                <parameter left="int &amp;" right="" name="argc" default=""/>
+                <parameter left="char **" right="" name="argv" default=""/>
+                <parameter left="Qt::HANDLE" right="" name="visual" default="0"/>
+                <parameter left="Qt::HANDLE" right="" name="cmap" default="0"/>
+            </function>
+            <function access="public" threadsafety="unspecified" status="commendable" name="QtSingleApplication" fullname="QtSingleApplication::QtSingleApplication" href="qtsingleapplication.html#QtSingleApplication-6" location="qtsingleapplication.h" virtual="non" meta="constructor" const="false" static="false" overload="true" overload-number="6" type="" signature="QtSingleApplication(Display * dpy, const QString &amp; appId, int argc, char ** argv, Qt::HANDLE visual, Qt::HANDLE cmap)">
+                <parameter left="Display *" right="" name="dpy" default=""/>
+                <parameter left="const QString &amp;" right="" name="appId" default=""/>
+                <parameter left="int" right="" name="argc" default=""/>
+                <parameter left="char **" right="" name="argv" default=""/>
+                <parameter left="Qt::HANDLE" right="" name="visual" default="0"/>
+                <parameter left="Qt::HANDLE" right="" name="cmap" default="0"/>
+            </function>
+            <function access="public" threadsafety="unspecified" status="commendable" name="isRunning" fullname="QtSingleApplication::isRunning" href="qtsingleapplication.html#isRunning" location="qtsingleapplication.h" virtual="non" meta="plain" const="false" static="false" overload="false" type="bool" signature="isRunning()"/>
+            <function access="public" threadsafety="unspecified" status="commendable" name="id" fullname="QtSingleApplication::id" href="qtsingleapplication.html#id" location="qtsingleapplication.h" virtual="non" meta="plain" const="true" static="false" overload="false" type="QString" signature="id() const"/>
+            <function access="public" threadsafety="unspecified" status="commendable" name="setActivationWindow" fullname="QtSingleApplication::setActivationWindow" href="qtsingleapplication.html#setActivationWindow" location="qtsingleapplication.h" virtual="non" meta="plain" const="false" static="false" overload="false" type="void" signature="setActivationWindow(QWidget * aw, bool activateOnMessage)">
+                <parameter left="QWidget *" right="" name="aw" default=""/>
+                <parameter left="bool" right="" name="activateOnMessage" default="true"/>
+            </function>
+            <function access="public" threadsafety="unspecified" status="commendable" name="activationWindow" fullname="QtSingleApplication::activationWindow" href="qtsingleapplication.html#activationWindow" location="qtsingleapplication.h" virtual="non" meta="plain" const="true" static="false" overload="false" type="QWidget *" signature="activationWindow() const"/>
+            <function access="public" threadsafety="unspecified" status="obsolete" name="initialize" fullname="QtSingleApplication::initialize" href="qtsingleapplication-obsolete.html#initialize" location="qtsingleapplication.h" virtual="non" meta="plain" const="false" static="false" overload="false" type="void" signature="initialize(bool dummy)">
+                <parameter left="bool" right="" name="dummy" default="true"/>
+            </function>
+            <function access="public" threadsafety="unspecified" status="commendable" name="sendMessage" fullname="QtSingleApplication::sendMessage" href="qtsingleapplication.html#sendMessage" location="qtsingleapplication.h" virtual="non" meta="slot" const="false" static="false" overload="false" type="bool" signature="sendMessage(const QString &amp; message, int timeout)">
+                <parameter left="const QString &amp;" right="" name="message" default=""/>
+                <parameter left="int" right="" name="timeout" default="5000"/>
+            </function>
+            <function access="public" threadsafety="unspecified" status="commendable" name="activateWindow" fullname="QtSingleApplication::activateWindow" href="qtsingleapplication.html#activateWindow" location="qtsingleapplication.h" virtual="non" meta="slot" const="false" static="false" overload="false" type="void" signature="activateWindow()"/>
+            <function access="public" threadsafety="unspecified" status="commendable" name="messageReceived" fullname="QtSingleApplication::messageReceived" href="qtsingleapplication.html#messageReceived" location="qtsingleapplication.h" virtual="non" meta="signal" const="false" static="false" overload="false" type="void" signature="messageReceived(const QString &amp; message)">
+                <parameter left="const QString &amp;" right="" name="message" default=""/>
+            </function>
+        </class>
+        <page access="public" status="commendable" name="index.html" href="index.html" subtype="page" title="Single Application" fulltitle="Single Application" subtitle="" location="index.qdoc">
+            <contents name="description" title="Description" level="1"/>
+            <contents name="classes" title="Classes" level="1"/>
+            <contents name="examples" title="Examples" level="1"/>
+            <contents name="tested-platforms" title="Tested platforms" level="1"/>
+        </page>
+        <page access="public" status="commendable" name="qtsingleapplication-example-trivial.html" href="qtsingleapplication-example-trivial.html" subtype="page" title="A Trivial Example" fulltitle="A Trivial Example" subtitle="" location="trivial.qdoc"/>
+        <page access="public" status="commendable" name="qtsinglecoreapplication-example-console.html" href="qtsinglecoreapplication-example-console.html" subtype="page" title="A non-GUI example" fulltitle="A non-GUI example" subtitle="" location="console.qdoc"/>
+        <page access="public" status="commendable" name="qtsingleapplication-example-loader.html" href="qtsingleapplication-example-loader.html" subtype="page" title="Loading Documents" fulltitle="Loading Documents" subtitle="" location="loader.qdoc"/>
+    </namespace>
+</INDEX>
diff --git a/AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication.qhp b/AirTV-Qt/qtsingleapplication/doc/html/qtsingleapplication.qhp
new file mode 100644 (file)
index 0000000..ff42d9d
--- /dev/null
@@ -0,0 +1,53 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<QtHelpProject version="1.0">
+    <namespace>com.nokia.qtsolutions.qtsingleapplication_head</namespace>
+    <virtualFolder>qdoc</virtualFolder>
+    <customFilter name="Qt Solutions: Single Application">
+        <filterAttribute>qt</filterAttribute>
+        <filterAttribute>solutions</filterAttribute>
+        <filterAttribute>qtsingleapplication</filterAttribute>
+    </customFilter>
+    <filterSection>
+        <filterAttribute>qt</filterAttribute>
+        <filterAttribute>solutions</filterAttribute>
+        <filterAttribute>qtsingleapplication</filterAttribute>
+        <toc>
+            <section ref="index.html" title="Qt Solutions: Single Application Documentation">
+                <section ref="qtsingleapplication-example-trivial.html" title="A Trivial Example"/>
+                <section ref="qtsinglecoreapplication-example-console.html" title="A non-GUI example"/>
+                <section ref="qtsingleapplication-example-loader.html" title="Loading Documents"/>
+                <section ref="index.html" title="Single Application"/>
+            </section>
+        </toc>
+        <keywords>
+            <keyword name="A Trivial Example" id="A Trivial Example" ref="qtsingleapplication-example-trivial.html"/>
+            <keyword name="A non-GUI example" id="A non-GUI example" ref="qtsinglecoreapplication-example-console.html"/>
+            <keyword name="Loading Documents" id="Loading Documents" ref="qtsingleapplication-example-loader.html"/>
+            <keyword name="QtSingleApplication" id="QtSingleApplication" ref="qtsingleapplication.html"/>
+            <keyword name="activateWindow" id="QtSingleApplication::activateWindow" ref="qtsingleapplication.html#activateWindow"/>
+            <keyword name="activationWindow" id="QtSingleApplication::activationWindow" ref="qtsingleapplication.html#activationWindow"/>
+            <keyword name="id" id="QtSingleApplication::id" ref="qtsingleapplication.html#id"/>
+            <keyword name="initialize" id="QtSingleApplication::initialize" ref="qtsingleapplication-obsolete.html#initialize"/>
+            <keyword name="isRunning" id="QtSingleApplication::isRunning" ref="qtsingleapplication.html#isRunning"/>
+            <keyword name="messageReceived" id="QtSingleApplication::messageReceived" ref="qtsingleapplication.html#messageReceived"/>
+            <keyword name="sendMessage" id="QtSingleApplication::sendMessage" ref="qtsingleapplication.html#sendMessage"/>
+            <keyword name="setActivationWindow" id="QtSingleApplication::setActivationWindow" ref="qtsingleapplication.html#setActivationWindow"/>
+            <keyword name="QtSingleCoreApplication" id="QtSingleCoreApplication" ref="qtsinglecoreapplication.html"/>
+            <keyword name="id" id="QtSingleCoreApplication::id" ref="qtsinglecoreapplication.html#id"/>
+            <keyword name="isRunning" id="QtSingleCoreApplication::isRunning" ref="qtsinglecoreapplication.html#isRunning"/>
+            <keyword name="messageReceived" id="QtSingleCoreApplication::messageReceived" ref="qtsinglecoreapplication.html#messageReceived"/>
+            <keyword name="sendMessage" id="QtSingleCoreApplication::sendMessage" ref="qtsinglecoreapplication.html#sendMessage"/>
+            <keyword name="Single Application" id="Single Application" ref="index.html"/>
+        </keywords>
+        <files>
+            <file>qtsingleapplication.html</file>
+            <file>index.html</file>
+            <file>qtsingleapplication-example-trivial.html</file>
+            <file>qtsinglecoreapplication.html</file>
+            <file>qtsingleapplication-example-loader.html</file>
+            <file>qtsinglecoreapplication-example-console.html</file>
+            <file>classic.css</file>
+            <file>images/qt-logo.png</file>
+        </files>
+    </filterSection>
+</QtHelpProject>
diff --git a/AirTV-Qt/qtsingleapplication/doc/html/qtsinglecoreapplication-example-console.html b/AirTV-Qt/qtsingleapplication/doc/html/qtsinglecoreapplication-example-console.html
new file mode 100644 (file)
index 0000000..5c4f642
--- /dev/null
@@ -0,0 +1,120 @@
+<?xml version="1.0" encoding="iso-8859-1"?>
+<!DOCTYPE html
+    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<!-- console.qdoc -->
+<head>
+  <title>A non-GUI example</title>
+  <link href="classic.css" rel="stylesheet" type="text/css" />
+</head>
+<body>
+<table border="0" cellpadding="0" cellspacing="0" width="100%">
+<tr>
+<td align="left" valign="top" width="32"><img src="images/qt-logo.png" align="left" width="57" height="67" border="0" /></td>
+<td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a></td>
+</tr></table><h1 class="title">A non-GUI example<br /><span class="subtitle"></span>
+</h1>
+<p>This example shows how to use the single-application functionality in a console application. It does not require the <tt>QtGui</tt> library at all.</p>
+<p>The only differences from the GUI application usage demonstrated in the other examples are:</p>
+<p>1) The <tt>.pro</tt> file should include <tt>qtsinglecoreapplication.pri</tt> instead of <tt>qtsingleapplication.pri</tt></p>
+<p>2) The class name is <tt>QtSingleCoreApplication</tt> instead of <tt>QtSingleApplication</tt>.</p>
+<p>3) No calls are made regarding window activation, for obvious reasons.</p>
+<p>console.pro:</p>
+<pre> TEMPLATE   = app
+ CONFIG    += console
+ SOURCES   += main.cpp
+ include(../../src/qtsinglecoreapplication.pri)
+ QT -= gui</pre>
+<p>main.cpp:</p>
+<pre><span class="comment"> /****************************************************************************
+ **
+ ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ ** All rights reserved.
+ **
+ ** Contact: Nokia Corporation (qt-info@nokia.com)
+ **
+ ** This file is part of a Qt Solutions component.
+ **
+ ** You may use this file under the terms of the BSD license as follows:
+ **
+ ** &quot;Redistribution and use in source and binary forms, with or without
+ ** modification, are permitted provided that the following conditions are
+ ** met:
+ **   * Redistributions of source code must retain the above copyright
+ **     notice, this list of conditions and the following disclaimer.
+ **   * Redistributions in binary form must reproduce the above copyright
+ **     notice, this list of conditions and the following disclaimer in
+ **     the documentation and/or other materials provided with the
+ **     distribution.
+ **   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+ **     the names of its contributors may be used to endorse or promote
+ **     products derived from this software without specific prior written
+ **     permission.
+ **
+ ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ ** &quot;AS IS&quot; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.&quot;
+ **
+ ****************************************************************************/</span>
+
+ #include &quot;qtsinglecoreapplication.h&quot;
+ #include &lt;QtCore/QDebug&gt;
+
+ void report(const QString&amp; msg)
+ {
+     qDebug(&quot;[%i] %s&quot;, (int)QCoreApplication::applicationPid(), qPrintable(msg));
+ }
+
+ class MainClass : public QObject
+ {
+     Q_OBJECT
+ public:
+     MainClass()
+         : QObject()
+         {}
+
+ public slots:
+     void handleMessage(const QString&amp; message)
+         {
+             report( &quot;Message received: \&quot;&quot; + message + &quot;\&quot;&quot;);
+         }
+ };
+
+ int main(int argc, char **argv)
+ {
+     report(&quot;Starting up&quot;);
+
+     QtSingleCoreApplication app(argc, argv);
+
+     if (app.isRunning()) {
+         QString msg(QString(&quot;Hi master, I am %1.&quot;).arg(QCoreApplication::applicationPid()));
+         bool sentok = app.sendMessage(msg, 2000);
+         QString rep(&quot;Another instance is running, so I will exit.&quot;);
+         rep += sentok ? &quot; Message sent ok.&quot; : &quot; Message sending failed; the other instance may be frozen.&quot;;
+         report(rep);
+         return 0;
+     } else {
+         report(&quot;No other instance is running; so I will.&quot;);
+         MainClass mainObj;
+         QObject::connect(&amp;app, SIGNAL(messageReceived(const QString&amp;)),
+                          &amp;mainObj, SLOT(handleMessage(const QString&amp;)));
+         return app.exec();
+     }
+ }
+
+ #include &quot;main.moc&quot;</pre>
+<p /><address><hr /><div align="center">
+<table width="100%" cellspacing="0" border="0"><tr class="address">
+<td width="30%" align="left">Copyright &copy; 2010 Nokia Corporation and/or its subsidiary(-ies)</td>
+<td width="40%" align="center"><a href="http://qt.nokia.com/doc/trademarks.html">Trademarks</a></td>
+<td width="30%" align="right"><div align="right">Qt Solutions</div></td>
+</tr></table></div></address></body>
+</html>
diff --git a/AirTV-Qt/qtsingleapplication/doc/html/qtsinglecoreapplication-members.html b/AirTV-Qt/qtsingleapplication/doc/html/qtsinglecoreapplication-members.html
new file mode 100644 (file)
index 0000000..69fb858
--- /dev/null
@@ -0,0 +1,126 @@
+<?xml version="1.0" encoding="iso-8859-1"?>
+<!DOCTYPE html
+    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<!-- qtsinglecoreapplication.cpp -->
+<head>
+  <title>List of All Members for QtSingleCoreApplication</title>
+  <link href="classic.css" rel="stylesheet" type="text/css" />
+</head>
+<body>
+<table border="0" cellpadding="0" cellspacing="0" width="100%">
+<tr>
+<td align="left" valign="top" width="32"><img src="images/qt-logo.png" align="left" width="57" height="67" border="0" /></td>
+<td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a></td>
+</tr></table><h1 class="title">List of All Members for QtSingleCoreApplication</h1>
+<p>This is the complete list of members for <a href="qtsinglecoreapplication.html">QtSingleCoreApplication</a>, including inherited members.</p>
+<p><table class="propsummary" width="100%" border="0" cellpadding="0" cellspacing="0">
+<tr><td width="45%" valign="top"><ul>
+<li><div class="fn">enum <b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#Encoding-enum">Encoding</a></b></div></li>
+<li><div class="fn">typedef <b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#EventFilter-typedef">EventFilter</a></b></div></li>
+<li><div class="fn"><b><a href="qtsinglecoreapplication.html#QtSingleCoreApplication">QtSingleCoreApplication</a></b> ( int &amp;, char ** )</div></li>
+<li><div class="fn"><b><a href="qtsinglecoreapplication.html#QtSingleCoreApplication-2">QtSingleCoreApplication</a></b> ( const QString &amp;, int &amp;, char ** )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#aboutToQuit">aboutToQuit</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#addLibraryPath">addLibraryPath</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationDirPath">applicationDirPath</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationFilePath">applicationFilePath</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationName-prop">applicationName</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationPid">applicationPid</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationVersion-prop">applicationVersion</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#arguments">arguments</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#blockSignals">blockSignals</a></b> ( bool )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#childEvent">childEvent</a></b> ( QChildEvent * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#children">children</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#closingDown">closingDown</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#connect">connect</a></b> ( const QObject *, const char *, const QObject *, const char *, Qt::ConnectionType )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#connect-2">connect</a></b> ( const QObject *, const char *, const char *, Qt::ConnectionType ) const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#connectNotify">connectNotify</a></b> ( const char * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#customEvent">customEvent</a></b> ( QEvent * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#d_ptr-var">d_ptr</a></b> : </div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#deleteLater">deleteLater</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#destroyed">destroyed</a></b> ( QObject * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#disconnect">disconnect</a></b> ( const QObject *, const char *, const QObject *, const char * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#disconnect-2">disconnect</a></b> ( const char *, const QObject *, const char * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#disconnect-3">disconnect</a></b> ( const QObject *, const char * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#disconnectNotify">disconnectNotify</a></b> ( const char * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#dumpObjectInfo">dumpObjectInfo</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#dumpObjectTree">dumpObjectTree</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#dynamicPropertyNames">dynamicPropertyNames</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#event">event</a></b> ( QEvent * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#eventFilter">eventFilter</a></b> ( QObject *, QEvent * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#exec">exec</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#exit">exit</a></b> ( int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#filterEvent">filterEvent</a></b> ( void *, long * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#findChild">findChild</a></b> ( const QString &amp; ) const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#findChildren">findChildren</a></b> ( const QString &amp; ) const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#findChildren-2">findChildren</a></b> ( const QRegExp &amp; ) const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#flush">flush</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#hasPendingEvents">hasPendingEvents</a></b> ()</div></li>
+<li><div class="fn"><b><a href="qtsinglecoreapplication.html#id">id</a></b> () const : QString</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#inherits">inherits</a></b> ( const char * ) const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#installEventFilter">installEventFilter</a></b> ( QObject * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#installTranslator">installTranslator</a></b> ( QTranslator * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#instance">instance</a></b> ()</div></li>
+<li><div class="fn"><b><a href="qtsinglecoreapplication.html#isRunning">isRunning</a></b> () : bool</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#isWidgetType">isWidgetType</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#killTimer">killTimer</a></b> ( int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#libraryPaths">libraryPaths</a></b> ()</div></li>
+</ul></td><td valign="top"><ul>
+<li><div class="fn"><b><a href="qtsinglecoreapplication.html#messageReceived">messageReceived</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#metaObject">metaObject</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#moveToThread">moveToThread</a></b> ( QThread * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#notify">notify</a></b> ( QObject *, QEvent * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#objectName-prop">objectName</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#organizationDomain-prop">organizationDomain</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#organizationName-prop">organizationName</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#parent">parent</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#postEvent">postEvent</a></b> ( QObject *, QEvent * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#postEvent-2">postEvent</a></b> ( QObject *, QEvent *, int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#processEvents">processEvents</a></b> ( QFlags&lt;QEventLoop::ProcessEventsFlag&gt; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#processEvents-2">processEvents</a></b> ( QFlags&lt;QEventLoop::ProcessEventsFlag&gt;, int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#property">property</a></b> ( const char * ) const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#quit">quit</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#receivers">receivers</a></b> ( const char * ) const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#removeEventFilter">removeEventFilter</a></b> ( QObject * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#removeLibraryPath">removeLibraryPath</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#removePostedEvents">removePostedEvents</a></b> ( QObject * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#removePostedEvents-2">removePostedEvents</a></b> ( QObject *, int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#removeTranslator">removeTranslator</a></b> ( QTranslator * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#sendEvent">sendEvent</a></b> ( QObject *, QEvent * )</div></li>
+<li><div class="fn"><b><a href="qtsinglecoreapplication.html#sendMessage">sendMessage</a></b> ( const QString &amp;, int ) : bool</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#sendPostedEvents">sendPostedEvents</a></b> ( QObject *, int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#sendPostedEvents-2">sendPostedEvents</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#sender">sender</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationName-prop">setApplicationName</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationVersion-prop">setApplicationVersion</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#setAttribute">setAttribute</a></b> ( Qt::ApplicationAttribute, bool )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#setEventFilter">setEventFilter</a></b> ( EventFilter )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#setLibraryPaths">setLibraryPaths</a></b> ( const QStringList &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#objectName-prop">setObjectName</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#organizationDomain-prop">setOrganizationDomain</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#organizationName-prop">setOrganizationName</a></b> ( const QString &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#setParent">setParent</a></b> ( QObject * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#setProperty">setProperty</a></b> ( const char *, const QVariant &amp; )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#signalsBlocked">signalsBlocked</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#startTimer">startTimer</a></b> ( int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#startingUp">startingUp</a></b> ()</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#staticMetaObject-var">staticMetaObject</a></b> : </div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#staticQtMetaObject-var">staticQtMetaObject</a></b> : </div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#testAttribute">testAttribute</a></b> ( Qt::ApplicationAttribute )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#thread">thread</a></b> () const</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#timerEvent">timerEvent</a></b> ( QTimerEvent * )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#tr">tr</a></b> ( const char *, const char *, int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qobject.html#trUtf8">trUtf8</a></b> ( const char *, const char *, int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#translate">translate</a></b> ( const char *, const char *, const char *, Encoding, int )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#translate-2">translate</a></b> ( const char *, const char *, const char *, Encoding )</div></li>
+<li><div class="fn"><b><a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#winEventFilter">winEventFilter</a></b> ( MSG *, long * )</div></li>
+</ul>
+</td></tr>
+</table></p>
+<p /><address><hr /><div align="center">
+<table width="100%" cellspacing="0" border="0"><tr class="address">
+<td width="30%" align="left">Copyright &copy; 2010 Nokia Corporation and/or its subsidiary(-ies)</td>
+<td width="40%" align="center"><a href="http://qt.nokia.com/doc/trademarks.html">Trademarks</a></td>
+<td width="30%" align="right"><div align="right">Qt Solutions</div></td>
+</tr></table></div></address></body>
+</html>
diff --git a/AirTV-Qt/qtsingleapplication/doc/html/qtsinglecoreapplication.html b/AirTV-Qt/qtsingleapplication/doc/html/qtsinglecoreapplication.html
new file mode 100644 (file)
index 0000000..a20cf2f
--- /dev/null
@@ -0,0 +1,98 @@
+<?xml version="1.0" encoding="iso-8859-1"?>
+<!DOCTYPE html
+    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<!-- qtsinglecoreapplication.cpp -->
+<head>
+  <title>QtSingleCoreApplication Class Reference</title>
+  <link href="classic.css" rel="stylesheet" type="text/css" />
+</head>
+<body>
+<table border="0" cellpadding="0" cellspacing="0" width="100%">
+<tr>
+<td align="left" valign="top" width="32"><img src="images/qt-logo.png" align="left" width="57" height="67" border="0" /></td>
+<td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a></td>
+</tr></table><h1 class="title">QtSingleCoreApplication Class Reference</h1>
+<p>A variant of the <a href="qtsingleapplication.html">QtSingleApplication</a> class for non-GUI applications. <a href="#details">More...</a></p>
+<pre> #include &lt;QtSingleCoreApplication&gt;</pre><p>Inherits <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html">QCoreApplication</a>.</p>
+<ul>
+<li><a href="qtsinglecoreapplication-members.html">List of all members, including inherited members</a></li>
+</ul>
+<hr />
+<a name="public-functions"></a>
+<h2>Public Functions</h2>
+<table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width="100%">
+<tr><td class="memItemLeft" align="right" valign="top"></td><td class="memItemRight" valign="bottom"><b><a href="qtsinglecoreapplication.html#QtSingleCoreApplication">QtSingleCoreApplication</a></b> ( int &amp; <i>argc</i>, char ** <i>argv</i> )</td></tr>
+<tr><td class="memItemLeft" align="right" valign="top"></td><td class="memItemRight" valign="bottom"><b><a href="qtsinglecoreapplication.html#QtSingleCoreApplication-2">QtSingleCoreApplication</a></b> ( const QString &amp; <i>appId</i>, int &amp; <i>argc</i>, char ** <i>argv</i> )</td></tr>
+<tr><td class="memItemLeft" align="right" valign="top">QString </td><td class="memItemRight" valign="bottom"><b><a href="qtsinglecoreapplication.html#id">id</a></b> () const</td></tr>
+<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><b><a href="qtsinglecoreapplication.html#isRunning">isRunning</a></b> ()</td></tr>
+</table>
+<ul>
+<li><div bar="2" class="fn"></div>4 public functions inherited from <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#public-functions">QCoreApplication</a></li>
+<li><div bar="2" class="fn"></div>29 public functions inherited from <a href="http://qt.nokia.com/doc/4.6/qobject.html#public-functions">QObject</a></li>
+</ul>
+<hr />
+<a name="public-slots"></a>
+<h2>Public Slots</h2>
+<table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width="100%">
+<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><b><a href="qtsinglecoreapplication.html#sendMessage">sendMessage</a></b> ( const QString &amp; <i>message</i>, int <i>timeout</i> = 5000 )</td></tr>
+</table>
+<ul>
+<li><div bar="2" class="fn"></div>1 public slot inherited from <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#public-slots">QCoreApplication</a></li>
+<li><div bar="2" class="fn"></div>1 public slot inherited from <a href="http://qt.nokia.com/doc/4.6/qobject.html#public-slots">QObject</a></li>
+</ul>
+<hr />
+<a name="signals"></a>
+<h2>Signals</h2>
+<table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width="100%">
+<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><b><a href="qtsinglecoreapplication.html#messageReceived">messageReceived</a></b> ( const QString &amp; <i>message</i> )</td></tr>
+</table>
+<ul>
+<li><div bar="2" class="fn"></div>1 signal inherited from <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#signals">QCoreApplication</a></li>
+<li><div bar="2" class="fn"></div>1 signal inherited from <a href="http://qt.nokia.com/doc/4.6/qobject.html#signals">QObject</a></li>
+</ul>
+<h3>Additional Inherited Members</h3>
+<ul>
+<li><div class="fn"></div>4 properties inherited from <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#properties">QCoreApplication</a></li>
+<li><div class="fn"></div>1 property inherited from <a href="http://qt.nokia.com/doc/4.6/qobject.html#properties">QObject</a></li>
+<li><div class="fn"></div>1 public type inherited from <a href="http://qt.nokia.com/doc/4.6/qobject.html#public-variables">QObject</a></li>
+<li><div class="fn"></div>38 static public members inherited from <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#static-public-members">QCoreApplication</a></li>
+<li><div class="fn"></div>4 static public members inherited from <a href="http://qt.nokia.com/doc/4.6/qobject.html#static-public-members">QObject</a></li>
+<li><div class="fn"></div>1 protected function inherited from <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#protected-functions">QCoreApplication</a></li>
+<li><div class="fn"></div>7 protected functions inherited from <a href="http://qt.nokia.com/doc/4.6/qobject.html#protected-functions">QObject</a></li>
+<li><div class="fn"></div>2 protected variables inherited from <a href="http://qt.nokia.com/doc/4.6/qobject.html#protected-variables">QObject</a></li>
+</ul>
+<a name="details"></a>
+<hr />
+<h2>Detailed Description</h2>
+<p>A variant of the <a href="qtsingleapplication.html">QtSingleApplication</a> class for non-GUI applications.</p>
+<p>This class is a variant of <a href="qtsingleapplication.html">QtSingleApplication</a> suited for use in console (non-GUI) applications. It is an extension of <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html">QCoreApplication</a> (instead of <a href="http://qt.nokia.com/doc/4.6/qapplication.html">QApplication</a>). It does not require the <a href="http://qt.nokia.com/doc/4.6/qtgui.html">QtGui</a> library.</p>
+<p>The API and usage is identical to <a href="qtsingleapplication.html">QtSingleApplication</a>, except that functions relating to the &quot;activation window&quot; are not present, for obvious reasons. Please refer to the <a href="qtsingleapplication.html">QtSingleApplication</a> documentation for explanation of the usage.</p>
+<p>A QtSingleCoreApplication instance can communicate to a <a href="qtsingleapplication.html">QtSingleApplication</a> instance if they share the same application id. Hence, this class can be used to create a light-weight command-line tool that sends commands to a GUI application.</p>
+<p>See also <a href="qtsingleapplication.html">QtSingleApplication</a>.</p>
+<hr />
+<h2>Member Function Documentation</h2>
+<h3 class="fn"><a name="QtSingleCoreApplication"></a>QtSingleCoreApplication::QtSingleCoreApplication ( int &amp; <i>argc</i>, char ** <i>argv</i> )</h3>
+<p>Creates a <a href="qtsinglecoreapplication.html">QtSingleCoreApplication</a> object. The application identifier will be <a href="http://qt.nokia.com/doc/4.6/qcoreapplication.html#applicationFilePath">QCoreApplication::applicationFilePath</a>(). <i>argc</i> and <i>argv</i> are passed on to the QCoreAppliation constructor.</p>
+<h3 class="fn"><a name="QtSingleCoreApplication-2"></a>QtSingleCoreApplication::QtSingleCoreApplication ( const <a href="http://qt.nokia.com/doc/4.6/qstring.html">QString</a> &amp; <i>appId</i>, int &amp; <i>argc</i>, char ** <i>argv</i> )</h3>
+<p>Creates a <a href="qtsinglecoreapplication.html">QtSingleCoreApplication</a> object with the application identifier <i>appId</i>. <i>argc</i> and <i>argv</i> are passed on to the QCoreAppliation constructor.</p>
+<h3 class="fn"><a name="id"></a><a href="http://qt.nokia.com/doc/4.6/qstring.html">QString</a> QtSingleCoreApplication::id () const</h3>
+<p>Returns the application identifier. Two processes with the same identifier will be regarded as instances of the same application.</p>
+<h3 class="fn"><a name="isRunning"></a>bool QtSingleCoreApplication::isRunning ()</h3>
+<p>Returns true if another instance of this application is running; otherwise false.</p>
+<p>This function does not find instances of this application that are being run by a different user (on Windows: that are running in another session).</p>
+<p>See also <a href="qtsinglecoreapplication.html#sendMessage">sendMessage</a>().</p>
+<h3 class="fn"><a name="messageReceived"></a>void QtSingleCoreApplication::messageReceived ( const <a href="http://qt.nokia.com/doc/4.6/qstring.html">QString</a> &amp; <i>message</i> )&nbsp;&nbsp;<tt> [signal]</tt></h3>
+<p>This signal is emitted when the current instance receives a <i>message</i> from another instance of this application.</p>
+<p>See also <a href="qtsinglecoreapplication.html#sendMessage">sendMessage</a>().</p>
+<h3 class="fn"><a name="sendMessage"></a>bool QtSingleCoreApplication::sendMessage ( const <a href="http://qt.nokia.com/doc/4.6/qstring.html">QString</a> &amp; <i>message</i>, int <i>timeout</i> = 5000 )&nbsp;&nbsp;<tt> [slot]</tt></h3>
+<p>Tries to send the text <i>message</i> to the currently running instance. The <a href="qtsinglecoreapplication.html">QtSingleCoreApplication</a> object in the running instance will emit the <a href="qtsinglecoreapplication.html#messageReceived">messageReceived</a>() signal when it receives the message.</p>
+<p>This function returns true if the message has been sent to, and processed by, the current instance. If there is no instance currently running, or if the running instance fails to process the message within <i>timeout</i> milliseconds, this function return false.</p>
+<p>See also <a href="qtsinglecoreapplication.html#isRunning">isRunning</a>() and <a href="qtsinglecoreapplication.html#messageReceived">messageReceived</a>().</p>
+<p /><address><hr /><div align="center">
+<table width="100%" cellspacing="0" border="0"><tr class="address">
+<td width="30%" align="left">Copyright &copy; 2010 Nokia Corporation and/or its subsidiary(-ies)</td>
+<td width="40%" align="center"><a href="http://qt.nokia.com/doc/trademarks.html">Trademarks</a></td>
+<td width="30%" align="right"><div align="right">Qt Solutions</div></td>
+</tr></table></div></address></body>
+</html>
diff --git a/AirTV-Qt/qtsingleapplication/doc/images/qt-logo.png b/AirTV-Qt/qtsingleapplication/doc/images/qt-logo.png
new file mode 100644 (file)
index 0000000..794162f
Binary files /dev/null and b/AirTV-Qt/qtsingleapplication/doc/images/qt-logo.png differ
diff --git a/AirTV-Qt/qtsingleapplication/doc/index.qdoc b/AirTV-Qt/qtsingleapplication/doc/index.qdoc
new file mode 100644 (file)
index 0000000..9c3308d
--- /dev/null
@@ -0,0 +1,47 @@
+/*!
+       \page index.html
+       \title Single Application
+
+       \section1 Description
+       
+                       The QtSingleApplication component provides support
+                       for applications that can be only started once per user.
+               
+
+       
+                       For some applications it is useful or even critical that they are started
+                       only once by any user. Future attempts to start the application should
+                       activate any already running instance, and possibly perform requested
+                       actions, e.g. loading a file, in that instance.
+
+                       The QtSingleApplication class provides an interface to detect a running
+                       instance, and to send command strings to that instance.
+                       For console (non-GUI) applications, the QtSingleCoreApplication variant is provided, which avoids dependency on QtGui.
+
+               
+
+       
+               \section1 Classes
+           \list
+        \i  QtSingleApplication \i  QtSingleCoreApplication\endlist
+       
+               \section1 Examples
+           \list
+        \i  \link qtsingleapplication-example-trivial.html A Trivial Example \endlink  \i  \link qtsingleapplication-example-loader.html Loading Documents \endlink  \i  \link qtsinglecoreapplication-example-console.html A Non-GUI Example \endlink \endlist
+       
+       
+
+       
+
+       
+               \section1 Tested platforms
+               \list
+               \i Qt 4.4, 4.5 / Windows XP / MSVC.NET 2005
+                   \i Qt 4.4, 4.5 / Linux / gcc
+                   \i Qt 4.4, 4.5 / MacOS X 10.5 / gcc
+                   \endlist
+
+       
+
+       
+       */
\ No newline at end of file
diff --git a/AirTV-Qt/qtsingleapplication/examples/console/console.pro b/AirTV-Qt/qtsingleapplication/examples/console/console.pro
new file mode 100644 (file)
index 0000000..e0390e2
--- /dev/null
@@ -0,0 +1,5 @@
+TEMPLATE   = app
+CONFIG    += console
+SOURCES   += main.cpp
+include(../../src/qtsinglecoreapplication.pri)
+QT -= gui
diff --git a/AirTV-Qt/qtsingleapplication/examples/console/console.qdoc b/AirTV-Qt/qtsingleapplication/examples/console/console.qdoc
new file mode 100644 (file)
index 0000000..7bef07c
--- /dev/null
@@ -0,0 +1,64 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of a Qt Solutions component.
+**
+** You may use this file under the terms of the BSD license as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+**   * Redistributions of source code must retain the above copyright
+**     notice, this list of conditions and the following disclaimer.
+**   * Redistributions in binary form must reproduce the above copyright
+**     notice, this list of conditions and the following disclaimer in
+**     the documentation and/or other materials provided with the
+**     distribution.
+**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+**     the names of its contributors may be used to endorse or promote
+**     products derived from this software without specific prior written
+**     permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+****************************************************************************/
+
+/*! \page qtsinglecoreapplication-example-console.html
+    \title A non-GUI example
+
+    This example shows how to use the single-application functionality
+    in a console application. It does not require the \c QtGui library
+    at all.
+
+    The only differences from the GUI application usage demonstrated
+    in the other examples are:
+
+    1) The \c.pro file should include \c qtsinglecoreapplication.pri
+       instead of \c qtsingleapplication.pri
+
+    2) The class name is \c QtSingleCoreApplication instead of \c
+       QtSingleApplication.
+
+    3) No calls are made regarding window activation, for obvious reasons.
+
+    console.pro:
+    \quotefile console/console.pro
+
+    main.cpp:
+    \quotefile console/main.cpp
+
+*/
diff --git a/AirTV-Qt/qtsingleapplication/examples/console/main.cpp b/AirTV-Qt/qtsingleapplication/examples/console/main.cpp
new file mode 100644 (file)
index 0000000..de4816a
--- /dev/null
@@ -0,0 +1,88 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of a Qt Solutions component.
+**
+** You may use this file under the terms of the BSD license as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+**   * Redistributions of source code must retain the above copyright
+**     notice, this list of conditions and the following disclaimer.
+**   * Redistributions in binary form must reproduce the above copyright
+**     notice, this list of conditions and the following disclaimer in
+**     the documentation and/or other materials provided with the
+**     distribution.
+**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+**     the names of its contributors may be used to endorse or promote
+**     products derived from this software without specific prior written
+**     permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+****************************************************************************/
+
+
+#include "qtsinglecoreapplication.h"
+#include <QtCore/QDebug>
+
+
+void report(const QString& msg)
+{
+    qDebug("[%i] %s", (int)QCoreApplication::applicationPid(), qPrintable(msg));
+}
+
+class MainClass : public QObject
+{
+    Q_OBJECT
+public:
+    MainClass()
+        : QObject()
+        {}
+
+public slots:
+    void handleMessage(const QString& message)
+        {
+            report( "Message received: \"" + message + "\"");
+        }
+};
+
+int main(int argc, char **argv)
+{
+    report("Starting up");
+
+    QtSingleCoreApplication app(argc, argv);
+
+    if (app.isRunning()) {
+        QString msg(QString("Hi master, I am %1.").arg(QCoreApplication::applicationPid()));
+        bool sentok = app.sendMessage(msg, 2000);
+        QString rep("Another instance is running, so I will exit.");
+        rep += sentok ? " Message sent ok." : " Message sending failed; the other instance may be frozen.";
+        report(rep);
+        return 0;
+    } else {
+        report("No other instance is running; so I will.");
+        MainClass mainObj;
+        QObject::connect(&app, SIGNAL(messageReceived(const QString&)),
+                         &mainObj, SLOT(handleMessage(const QString&)));
+        return app.exec();
+    }
+}
+
+
+#include "main.moc"
diff --git a/AirTV-Qt/qtsingleapplication/examples/examples.pro b/AirTV-Qt/qtsingleapplication/examples/examples.pro
new file mode 100644 (file)
index 0000000..36b8fd3
--- /dev/null
@@ -0,0 +1,4 @@
+TEMPLATE = subdirs
+SUBDIRS         = trivial \
+          loader  \
+           console
diff --git a/AirTV-Qt/qtsingleapplication/examples/loader/file1.qsl b/AirTV-Qt/qtsingleapplication/examples/loader/file1.qsl
new file mode 100644 (file)
index 0000000..50fcd26
--- /dev/null
@@ -0,0 +1 @@
+File 1
diff --git a/AirTV-Qt/qtsingleapplication/examples/loader/file2.qsl b/AirTV-Qt/qtsingleapplication/examples/loader/file2.qsl
new file mode 100644 (file)
index 0000000..4475433
--- /dev/null
@@ -0,0 +1 @@
+File 2
diff --git a/AirTV-Qt/qtsingleapplication/examples/loader/loader.pro b/AirTV-Qt/qtsingleapplication/examples/loader/loader.pro
new file mode 100644 (file)
index 0000000..673497a
--- /dev/null
@@ -0,0 +1,5 @@
+TEMPLATE       = app
+
+include(../../src/qtsingleapplication.pri)
+
+SOURCES                += main.cpp
diff --git a/AirTV-Qt/qtsingleapplication/examples/loader/loader.qdoc b/AirTV-Qt/qtsingleapplication/examples/loader/loader.qdoc
new file mode 100644 (file)
index 0000000..2ae59e3
--- /dev/null
@@ -0,0 +1,80 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of a Qt Solutions component.
+**
+** You may use this file under the terms of the BSD license as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+**   * Redistributions of source code must retain the above copyright
+**     notice, this list of conditions and the following disclaimer.
+**   * Redistributions in binary form must reproduce the above copyright
+**     notice, this list of conditions and the following disclaimer in
+**     the documentation and/or other materials provided with the
+**     distribution.
+**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+**     the names of its contributors may be used to endorse or promote
+**     products derived from this software without specific prior written
+**     permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+****************************************************************************/
+
+/*! \page qtsingleapplication-example-loader.html
+    \title Loading Documents
+
+    The application in this example loads or prints the documents 
+    passed as commandline parameters to further instances of this
+    application.
+
+    \quotefromfile loader/main.cpp
+    \printuntil };
+    The user interface in this application is a QMainWindow subclass
+    with a QMdiArea as the central widget. It implements a slot
+    \c handleMessage() that will be connected to the messageReceived()
+    signal of the QtSingleApplication class.
+
+    \printuntil }
+    The MainWindow constructor creates a minimal user interface.
+
+    \printto case Print:
+    The handleMessage() slot interprets the message passed in as a
+    filename that can be prepended with \e /print to indicate that
+    the file should just be printed rather than loaded.
+
+    \printto #include
+    Loading the file will also activate the window.
+
+    \printto mw
+    The \c main entry point function creates a QtSingleApplication
+    object, and creates a message to send to a running instance
+    of the application. If the message was sent successfully the
+    process exits immediately.
+
+    \printuntil }
+    If the message could not be sent the application starts up.  Note
+    that \c false is passed to the call to setActivationWindow() to
+    prevent automatic activation for every message received, e.g. when
+    the application should just print a file. Instead, the message
+    handling function determines whether activation is requested, and
+    signals that by emitting the needToShow() signal. This is then
+    simply connected directly to QtSingleApplication's
+    activateWindow() slot.
+*/
diff --git a/AirTV-Qt/qtsingleapplication/examples/loader/main.cpp b/AirTV-Qt/qtsingleapplication/examples/loader/main.cpp
new file mode 100644 (file)
index 0000000..7bc5686
--- /dev/null
@@ -0,0 +1,151 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of a Qt Solutions component.
+**
+** You may use this file under the terms of the BSD license as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+**   * Redistributions of source code must retain the above copyright
+**     notice, this list of conditions and the following disclaimer.
+**   * Redistributions in binary form must reproduce the above copyright
+**     notice, this list of conditions and the following disclaimer in
+**     the documentation and/or other materials provided with the
+**     distribution.
+**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+**     the names of its contributors may be used to endorse or promote
+**     products derived from this software without specific prior written
+**     permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+****************************************************************************/
+
+#include <qtsingleapplication.h>
+#include <QtCore/QFile>
+#include <QtGui/QMainWindow>
+#include <QtGui/QPrinter>
+#include <QtGui/QPainter>
+#include <QtGui/QTextEdit>
+#include <QtGui/QMdiArea>
+#include <QtCore/QTextStream>
+
+class MainWindow : public QMainWindow
+{
+    Q_OBJECT
+public:
+    MainWindow();
+
+public slots:
+    void handleMessage(const QString& message);
+
+signals:
+    void needToShow();
+
+private:
+    QMdiArea *workspace;
+};
+
+MainWindow::MainWindow()
+{
+    workspace = new QMdiArea(this);
+
+    setCentralWidget(workspace);
+}
+
+void MainWindow::handleMessage(const QString& message)
+{
+    enum Action {
+       Nothing,
+       Open,
+       Print
+    } action;
+
+    action = Nothing;
+    QString filename = message;
+    if (message.toLower().startsWith("/print ")) {
+       filename = filename.mid(7);
+       action = Print;
+    } else if (!message.isEmpty()) {
+       action = Open;
+    }
+    if (action == Nothing) {
+        emit needToShow();
+       return;
+    }
+
+    QFile file(filename);
+    QString contents;
+    if (file.open(QIODevice::ReadOnly))
+        contents = file.readAll();
+    else
+        contents = "[[Error: Could not load file " + filename + "]]";
+
+    QTextEdit *view = new QTextEdit;
+    view->setPlainText(contents);
+
+    switch(action) {
+    case Print:
+       {
+           QPrinter printer;
+            view->print(&printer);
+            delete view;
+        }
+       break;
+
+    case Open:
+       {
+           workspace->addSubWindow(view);
+           view->setWindowTitle(message);
+           view->show();
+            emit needToShow();
+       }
+       break;
+    default:
+       break;
+    };
+}
+
+#include "main.moc"
+
+int main(int argc, char **argv)
+{
+    QtSingleApplication instance("File loader QtSingleApplication example", argc, argv);
+    QString message;
+    for (int a = 1; a < argc; ++a) {
+       message += argv[a];
+       if (a < argc-1)
+           message += " ";
+    }
+
+    if (instance.sendMessage(message))
+       return 0;
+
+    MainWindow mw;
+    mw.handleMessage(message);
+    mw.show();
+
+    QObject::connect(&instance, SIGNAL(messageReceived(const QString&)),
+                    &mw, SLOT(handleMessage(const QString&)));
+
+    instance.setActivationWindow(&mw, false);
+    QObject::connect(&mw, SIGNAL(needToShow()), &instance, SLOT(activateWindow()));
+
+    return instance.exec();
+}
diff --git a/AirTV-Qt/qtsingleapplication/examples/trivial/main.cpp b/AirTV-Qt/qtsingleapplication/examples/trivial/main.cpp
new file mode 100644 (file)
index 0000000..8552fe3
--- /dev/null
@@ -0,0 +1,77 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of a Qt Solutions component.
+**
+** You may use this file under the terms of the BSD license as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+**   * Redistributions of source code must retain the above copyright
+**     notice, this list of conditions and the following disclaimer.
+**   * Redistributions in binary form must reproduce the above copyright
+**     notice, this list of conditions and the following disclaimer in
+**     the documentation and/or other materials provided with the
+**     distribution.
+**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+**     the names of its contributors may be used to endorse or promote
+**     products derived from this software without specific prior written
+**     permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+****************************************************************************/
+
+#include <qtsingleapplication.h>
+#include <QtGui/QTextEdit>
+
+class TextEdit : public QTextEdit
+{
+    Q_OBJECT
+public:
+    TextEdit(QWidget *parent = 0)
+        : QTextEdit(parent)
+    {}
+public slots:
+    void append(const QString &str)
+    {
+        QTextEdit::append(str);
+    }
+};
+
+#include "main.moc"
+
+
+
+int main(int argc, char **argv)
+{
+    QtSingleApplication instance(argc, argv);
+    if (instance.sendMessage("Wake up!"))
+       return 0;
+
+    TextEdit logview;
+    logview.setReadOnly(true);
+    logview.show();
+
+    instance.setActivationWindow(&logview);
+
+    QObject::connect(&instance, SIGNAL(messageReceived(const QString&)),
+                    &logview, SLOT(append(const QString&)));
+
+    return instance.exec();
+}
diff --git a/AirTV-Qt/qtsingleapplication/examples/trivial/trivial.pro b/AirTV-Qt/qtsingleapplication/examples/trivial/trivial.pro
new file mode 100644 (file)
index 0000000..673497a
--- /dev/null
@@ -0,0 +1,5 @@
+TEMPLATE       = app
+
+include(../../src/qtsingleapplication.pri)
+
+SOURCES                += main.cpp
diff --git a/AirTV-Qt/qtsingleapplication/examples/trivial/trivial.qdoc b/AirTV-Qt/qtsingleapplication/examples/trivial/trivial.qdoc
new file mode 100644 (file)
index 0000000..3185199
--- /dev/null
@@ -0,0 +1,75 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of a Qt Solutions component.
+**
+** You may use this file under the terms of the BSD license as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+**   * Redistributions of source code must retain the above copyright
+**     notice, this list of conditions and the following disclaimer.
+**   * Redistributions in binary form must reproduce the above copyright
+**     notice, this list of conditions and the following disclaimer in
+**     the documentation and/or other materials provided with the
+**     distribution.
+**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+**     the names of its contributors may be used to endorse or promote
+**     products derived from this software without specific prior written
+**     permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+****************************************************************************/
+
+/*! \page qtsingleapplication-example-trivial.html
+    \title A Trivial Example
+
+    The application in this example has a log-view that displays
+    messages sent by further instances of the same application.
+
+    The example demonstrates the use of the QtSingleApplication
+    class to detect and communicate with a running instance of
+    the application using the sendMessage() API. The messageReceived()
+    signal is used to display received messages in a QTextEdit log.
+
+    \quotefromfile trivial/main.cpp
+    \printuntil instance
+    The example has only the \c main entry point function.
+    A QtSingleApplication object is created immediately.
+
+    \printuntil return 
+    If another instance of this application is already running,
+    sendMessage() will succeed, and this instance just exits
+    immediately.
+
+    \printuntil show()
+    Otherwise the instance continues as normal and creates the
+    user interface.
+
+    \printuntil return instance.exec();
+    The \c logview object is also set as the application's activation
+    window. Every time a message is received, the window will be raised
+    and activated automatically.
+
+    The messageReceived() signal is also connected to the QTextEdit's
+    append() slot. Every message received from further instances of
+    this application will be displayed in the log.
+
+    Finally the event loop is entered.
+*/
diff --git a/AirTV-Qt/qtsingleapplication/qtsingleapplication.pro b/AirTV-Qt/qtsingleapplication/qtsingleapplication.pro
new file mode 100644 (file)
index 0000000..07257c5
--- /dev/null
@@ -0,0 +1,5 @@
+TEMPLATE=subdirs
+CONFIG += ordered
+include(common.pri)
+qtsingleapplication-uselib:SUBDIRS=buildlib
+SUBDIRS+=examples
diff --git a/AirTV-Qt/qtsingleapplication/src/QtLockedFile b/AirTV-Qt/qtsingleapplication/src/QtLockedFile
new file mode 100644 (file)
index 0000000..16b48ba
--- /dev/null
@@ -0,0 +1 @@
+#include "qtlockedfile.h"
diff --git a/AirTV-Qt/qtsingleapplication/src/QtSingleApplication b/AirTV-Qt/qtsingleapplication/src/QtSingleApplication
new file mode 100644 (file)
index 0000000..d111bf7
--- /dev/null
@@ -0,0 +1 @@
+#include "qtsingleapplication.h"
diff --git a/AirTV-Qt/qtsingleapplication/src/qtlocalpeer.cpp b/AirTV-Qt/qtsingleapplication/src/qtlocalpeer.cpp
new file mode 100644 (file)
index 0000000..382d182
--- /dev/null
@@ -0,0 +1,199 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of a Qt Solutions component.
+**
+** You may use this file under the terms of the BSD license as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+**   * Redistributions of source code must retain the above copyright
+**     notice, this list of conditions and the following disclaimer.
+**   * Redistributions in binary form must reproduce the above copyright
+**     notice, this list of conditions and the following disclaimer in
+**     the documentation and/or other materials provided with the
+**     distribution.
+**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+**     the names of its contributors may be used to endorse or promote
+**     products derived from this software without specific prior written
+**     permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+****************************************************************************/
+
+
+#include "qtlocalpeer.h"
+#include <QtCore/QCoreApplication>
+#include <QtCore/QTime>
+
+#if defined(Q_OS_WIN)
+#include <QtCore/QLibrary>
+#include <QtCore/qt_windows.h>
+typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*);
+static PProcessIdToSessionId pProcessIdToSessionId = 0;
+#endif
+#if defined(Q_OS_UNIX)
+#include <time.h>
+#endif
+
+namespace QtLP_Private {
+#include "qtlockedfile.cpp"
+#if defined(Q_OS_WIN)
+#include "qtlockedfile_win.cpp"
+#else
+#include "qtlockedfile_unix.cpp"
+#endif
+}
+
+const char* QtLocalPeer::ack = "ack";
+
+QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId)
+    : QObject(parent), id(appId)
+{
+    QString prefix = id;
+    if (id.isEmpty()) {
+        id = QCoreApplication::applicationFilePath();
+#if defined(Q_OS_WIN)
+        id = id.toLower();
+#endif
+        prefix = id.section(QLatin1Char('/'), -1);
+    }
+    prefix.remove(QRegExp("[^a-zA-Z]"));
+    prefix.truncate(6);
+
+    QByteArray idc = id.toUtf8();
+    quint16 idNum = qChecksum(idc.constData(), idc.size());
+    socketName = QLatin1String("qtsingleapp-") + prefix
+                 + QLatin1Char('-') + QString::number(idNum, 16);
+
+#if defined(Q_OS_WIN)
+    if (!pProcessIdToSessionId) {
+        QLibrary lib("kernel32");
+        pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId");
+    }
+    if (pProcessIdToSessionId) {
+        DWORD sessionId = 0;
+        pProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
+        socketName += QLatin1Char('-') + QString::number(sessionId, 16);
+    }
+#else
+    socketName += QLatin1Char('-') + QString::number(::getuid(), 16);
+#endif
+
+    server = new QLocalServer(this);
+    QString lockName = QDir(QDir::tempPath()).absolutePath()
+                       + QLatin1Char('/') + socketName
+                       + QLatin1String("-lockfile");
+    lockFile.setFileName(lockName);
+    lockFile.open(QIODevice::ReadWrite);
+}
+
+
+
+bool QtLocalPeer::isClient()
+{
+    if (lockFile.isLocked())
+        return false;
+
+    if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false))
+        return true;
+
+    bool res = server->listen(socketName);
+#if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0))
+    // ### Workaround
+    if (!res && server->serverError() == QAbstractSocket::AddressInUseError) {
+        QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName);
+        res = server->listen(socketName);
+    }
+#endif
+    if (!res)
+        qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));
+    QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection()));
+    return false;
+}
+
+
+bool QtLocalPeer::sendMessage(const QString &message, int timeout)
+{
+    if (!isClient())
+        return false;
+
+    QLocalSocket socket;
+    bool connOk = false;
+    for(int i = 0; i < 2; i++) {
+        // Try twice, in case the other instance is just starting up
+        socket.connectToServer(socketName);
+        connOk = socket.waitForConnected(timeout/2);
+        if (connOk || i)
+            break;
+        int ms = 250;
+#if defined(Q_OS_WIN)
+        Sleep(DWORD(ms));
+#else
+        struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
+        nanosleep(&ts, NULL);
+#endif
+    }
+    if (!connOk)
+        return false;
+
+    QByteArray uMsg(message.toUtf8());
+    QDataStream ds(&socket);
+    ds.writeBytes(uMsg.constData(), uMsg.size());
+    bool res = socket.waitForBytesWritten(timeout);
+    if (res) {
+        res &= socket.waitForReadyRead(timeout);   // wait for ack
+        if (res)
+            res &= (socket.read(qstrlen(ack)) == ack);
+    }
+    return res;
+}
+
+
+void QtLocalPeer::receiveConnection()
+{
+    QLocalSocket* socket = server->nextPendingConnection();
+    if (!socket)
+        return;
+
+    while (socket->bytesAvailable() < (int)sizeof(quint32))
+        socket->waitForReadyRead();
+    QDataStream ds(socket);
+    QByteArray uMsg;
+    quint32 remaining;
+    ds >> remaining;
+    uMsg.resize(remaining);
+    int got = 0;
+    char* uMsgBuf = uMsg.data();
+    do {
+        got = ds.readRawData(uMsgBuf, remaining);
+        remaining -= got;
+        uMsgBuf += got;
+    } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
+    if (got < 0) {
+        qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData());
+        delete socket;
+        return;
+    }
+    QString message(QString::fromUtf8(uMsg));
+    socket->write(ack, qstrlen(ack));
+    socket->waitForBytesWritten(1000);
+    delete socket;
+    emit messageReceived(message); //### (might take a long time to return)
+}
diff --git a/AirTV-Qt/qtsingleapplication/src/qtlocalpeer.h b/AirTV-Qt/qtsingleapplication/src/qtlocalpeer.h
new file mode 100644 (file)
index 0000000..e834b73
--- /dev/null
@@ -0,0 +1,76 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of a Qt Solutions component.
+**
+** You may use this file under the terms of the BSD license as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+**   * Redistributions of source code must retain the above copyright
+**     notice, this list of conditions and the following disclaimer.
+**   * Redistributions in binary form must reproduce the above copyright
+**     notice, this list of conditions and the following disclaimer in
+**     the documentation and/or other materials provided with the
+**     distribution.
+**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+**     the names of its contributors may be used to endorse or promote
+**     products derived from this software without specific prior written
+**     permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+****************************************************************************/
+
+#ifndef QTLOCALPEER_H
+#define QTLOCALPEER_H
+
+#include <QtNetwork/QLocalServer>
+#include <QtNetwork/QLocalSocket>
+#include <QtCore/QDir>
+
+#include "qtlockedfile.h"
+
+class QtLocalPeer : public QObject
+{
+    Q_OBJECT
+
+public:
+    QtLocalPeer(QObject *parent = 0, const QString &appId = QString());
+    bool isClient();
+    bool sendMessage(const QString &message, int timeout);
+    QString applicationId() const
+        { return id; }
+
+Q_SIGNALS:
+    void messageReceived(const QString &message);
+
+protected Q_SLOTS:
+    void receiveConnection();
+
+protected:
+    QString id;
+    QString socketName;
+    QLocalServer* server;
+    QtLP_Private::QtLockedFile lockFile;
+
+private:
+    static const char* ack;
+};
+
+#endif // QTLOCALPEER_H
diff --git a/AirTV-Qt/qtsingleapplication/src/qtlockedfile.cpp b/AirTV-Qt/qtsingleapplication/src/qtlockedfile.cpp
new file mode 100644 (file)
index 0000000..3e73ba6
--- /dev/null
@@ -0,0 +1,192 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of a Qt Solutions component.
+**
+** You may use this file under the terms of the BSD license as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+**   * Redistributions of source code must retain the above copyright
+**     notice, this list of conditions and the following disclaimer.
+**   * Redistributions in binary form must reproduce the above copyright
+**     notice, this list of conditions and the following disclaimer in
+**     the documentation and/or other materials provided with the
+**     distribution.
+**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+**     the names of its contributors may be used to endorse or promote
+**     products derived from this software without specific prior written
+**     permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+****************************************************************************/
+
+#include "qtlockedfile.h"
+
+/*!
+    \class QtLockedFile
+
+    \brief The QtLockedFile class extends QFile with advisory locking
+    functions.
+
+    A file may be locked in read or write mode. Multiple instances of
+    \e QtLockedFile, created in multiple processes running on the same
+    machine, may have a file locked in read mode. Exactly one instance
+    may have it locked in write mode. A read and a write lock cannot
+    exist simultaneously on the same file.
+
+    The file locks are advisory. This means that nothing prevents
+    another process from manipulating a locked file using QFile or
+    file system functions offered by the OS. Serialization is only
+    guaranteed if all processes that access the file use
+    QLockedFile. Also, while holding a lock on a file, a process
+    must not open the same file again (through any API), or locks
+    can be unexpectedly lost.
+
+    The lock provided by an instance of \e QtLockedFile is released
+    whenever the program terminates. This is true even when the
+    program crashes and no destructors are called.
+*/
+
+/*! \enum QtLockedFile::LockMode
+
+    This enum describes the available lock modes.
+
+    \value ReadLock A read lock.
+    \value WriteLock A write lock.
+    \value NoLock Neither a read lock nor a write lock.
+*/
+
+/*!
+    Constructs an unlocked \e QtLockedFile object. This constructor
+    behaves in the same way as \e QFile::QFile().
+
+    \sa QFile::QFile()
+*/
+QtLockedFile::QtLockedFile()
+    : QFile()
+{
+#ifdef Q_OS_WIN
+    wmutex = 0;
+    rmutex = 0;
+#endif
+    m_lock_mode = NoLock;
+}
+
+/*!
+    Constructs an unlocked QtLockedFile object with file \a name. This
+    constructor behaves in the same way as \e QFile::QFile(const
+    QString&).
+
+    \sa QFile::QFile()
+*/
+QtLockedFile::QtLockedFile(const QString &name)
+    : QFile(name)
+{
+#ifdef Q_OS_WIN
+    wmutex = 0;
+    rmutex = 0;
+#endif
+    m_lock_mode = NoLock;
+}
+
+/*!
+  Opens the file in OpenMode \a mode.
+
+  This is identical to QFile::open(), with the one exception that the
+  Truncate mode flag is disallowed. Truncation would conflict with the
+  advisory file locking, since the file would be modified before the
+  write lock is obtained. If truncation is required, use resize(0)
+  after obtaining the write lock.
+
+  Returns true if successful; otherwise false.
+
+  \sa QFile::open(), QFile::resize()
+*/
+bool QtLockedFile::open(OpenMode mode)
+{
+    if (mode & QIODevice::Truncate) {
+        qWarning("QtLockedFile::open(): Truncate mode not allowed.");
+        return false;
+    }
+    return QFile::open(mode);
+}
+
+/*!
+    Returns \e true if this object has a in read or write lock;
+    otherwise returns \e false.
+
+    \sa lockMode()
+*/
+bool QtLockedFile::isLocked() const
+{
+    return m_lock_mode != NoLock;
+}
+
+/*!
+    Returns the type of lock currently held by this object, or \e
+    QtLockedFile::NoLock.
+
+    \sa isLocked()
+*/
+QtLockedFile::LockMode QtLockedFile::lockMode() const
+{
+    return m_lock_mode;
+}
+
+/*!
+    \fn bool QtLockedFile::lock(LockMode mode, bool block = true)
+
+    Obtains a lock of type \a mode. The file must be opened before it
+    can be locked.
+
+    If \a block is true, this function will block until the lock is
+    aquired. If \a block is false, this function returns \e false
+    immediately if the lock cannot be aquired.
+
+    If this object already has a lock of type \a mode, this function
+    returns \e true immediately. If this object has a lock of a
+    different type than \a mode, the lock is first released and then a
+    new lock is obtained.
+
+    This function returns \e true if, after it executes, the file is
+    locked by this object, and \e false otherwise.
+
+    \sa unlock(), isLocked(), lockMode()
+*/
+
+/*!
+    \fn bool QtLockedFile::unlock()
+
+    Releases a lock.
+
+    If the object has no lock, this function returns immediately.
+
+    This function returns \e true if, after it executes, the file is
+    not locked by this object, and \e false otherwise.
+
+    \sa lock(), isLocked(), lockMode()
+*/
+
+/*!
+    \fn QtLockedFile::~QtLockedFile()
+
+    Destroys the \e QtLockedFile object. If any locks were held, they
+    are released.
+*/
diff --git a/AirTV-Qt/qtsingleapplication/src/qtlockedfile.h b/AirTV-Qt/qtsingleapplication/src/qtlockedfile.h
new file mode 100644 (file)
index 0000000..07a42bf
--- /dev/null
@@ -0,0 +1,96 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of a Qt Solutions component.
+**
+** You may use this file under the terms of the BSD license as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+**   * Redistributions of source code must retain the above copyright
+**     notice, this list of conditions and the following disclaimer.
+**   * Redistributions in binary form must reproduce the above copyright
+**     notice, this list of conditions and the following disclaimer in
+**     the documentation and/or other materials provided with the
+**     distribution.
+**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+**     the names of its contributors may be used to endorse or promote
+**     products derived from this software without specific prior written
+**     permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+****************************************************************************/
+
+#ifndef QTLOCKEDFILE_H
+#define QTLOCKEDFILE_H
+
+#include <QtCore/QFile>
+#ifdef Q_OS_WIN
+#include <QtCore/QVector>
+#endif
+
+#if defined(Q_WS_WIN)
+#  if !defined(QT_QTLOCKEDFILE_EXPORT) && !defined(QT_QTLOCKEDFILE_IMPORT)
+#    define QT_QTLOCKEDFILE_EXPORT
+#  elif defined(QT_QTLOCKEDFILE_IMPORT)
+#    if defined(QT_QTLOCKEDFILE_EXPORT)
+#      undef QT_QTLOCKEDFILE_EXPORT
+#    endif
+#    define QT_QTLOCKEDFILE_EXPORT __declspec(dllimport)
+#  elif defined(QT_QTLOCKEDFILE_EXPORT)
+#    undef QT_QTLOCKEDFILE_EXPORT
+#    define QT_QTLOCKEDFILE_EXPORT __declspec(dllexport)
+#  endif
+#else
+#  define QT_QTLOCKEDFILE_EXPORT
+#endif
+
+namespace QtLP_Private {
+
+class QT_QTLOCKEDFILE_EXPORT QtLockedFile : public QFile
+{
+public:
+    enum LockMode { NoLock = 0, ReadLock, WriteLock };
+
+    QtLockedFile();
+    QtLockedFile(const QString &name);
+    ~QtLockedFile();
+
+    bool open(OpenMode mode);
+
+    bool lock(LockMode mode, bool block = true);
+    bool unlock();
+    bool isLocked() const;
+    LockMode lockMode() const;
+
+private:
+#ifdef Q_OS_WIN
+    Qt::HANDLE wmutex;
+    Qt::HANDLE rmutex;
+    QVector<Qt::HANDLE> rmutexes;
+    QString mutexname;
+
+    Qt::HANDLE getMutexHandle(int idx, bool doCreate);
+    bool waitMutex(Qt::HANDLE mutex, bool doBlock);
+
+#endif
+    LockMode m_lock_mode;
+};
+}
+#endif
diff --git a/AirTV-Qt/qtsingleapplication/src/qtlockedfile_unix.cpp b/AirTV-Qt/qtsingleapplication/src/qtlockedfile_unix.cpp
new file mode 100644 (file)
index 0000000..715c7d9
--- /dev/null
@@ -0,0 +1,114 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of a Qt Solutions component.
+**
+** You may use this file under the terms of the BSD license as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+**   * Redistributions of source code must retain the above copyright
+**     notice, this list of conditions and the following disclaimer.
+**   * Redistributions in binary form must reproduce the above copyright
+**     notice, this list of conditions and the following disclaimer in
+**     the documentation and/or other materials provided with the
+**     distribution.
+**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+**     the names of its contributors may be used to endorse or promote
+**     products derived from this software without specific prior written
+**     permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+****************************************************************************/
+
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+#include <fcntl.h>
+
+#include "qtlockedfile.h"
+
+bool QtLockedFile::lock(LockMode mode, bool block)
+{
+    if (!isOpen()) {
+        qWarning("QtLockedFile::lock(): file is not opened");
+        return false;
+    }
+    if (mode == NoLock)
+        return unlock();
+           
+    if (mode == m_lock_mode)
+        return true;
+
+    if (m_lock_mode != NoLock)
+        unlock();
+
+    struct flock fl;
+    fl.l_whence = SEEK_SET;
+    fl.l_start = 0;
+    fl.l_len = 0;
+    fl.l_type = (mode == ReadLock) ? F_RDLCK : F_WRLCK;
+    int cmd = block ? F_SETLKW : F_SETLK;
+    int ret = fcntl(handle(), cmd, &fl);
+    
+    if (ret == -1) {
+        if (errno != EINTR && errno != EAGAIN)
+            qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno));
+        return false;
+    }
+
+    
+    m_lock_mode = mode;
+    return true;
+}
+
+
+bool QtLockedFile::unlock()
+{
+    if (!isOpen()) {
+        qWarning("QtLockedFile::unlock(): file is not opened");
+        return false;
+    }
+
+    if (!isLocked())
+        return true;
+
+    struct flock fl;
+    fl.l_whence = SEEK_SET;
+    fl.l_start = 0;
+    fl.l_len = 0;
+    fl.l_type = F_UNLCK;
+    int ret = fcntl(handle(), F_SETLKW, &fl);
+    
+    if (ret == -1) {
+        qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno));
+        return false;
+    }
+    
+    m_lock_mode = NoLock;
+    return true;
+}
+
+QtLockedFile::~QtLockedFile()
+{
+    if (isOpen())
+        unlock();
+}
+
diff --git a/AirTV-Qt/qtsingleapplication/src/qtlockedfile_win.cpp b/AirTV-Qt/qtsingleapplication/src/qtlockedfile_win.cpp
new file mode 100644 (file)
index 0000000..4cd2003
--- /dev/null
@@ -0,0 +1,206 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of a Qt Solutions component.
+**
+** You may use this file under the terms of the BSD license as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+**   * Redistributions of source code must retain the above copyright
+**     notice, this list of conditions and the following disclaimer.
+**   * Redistributions in binary form must reproduce the above copyright
+**     notice, this list of conditions and the following disclaimer in
+**     the documentation and/or other materials provided with the
+**     distribution.
+**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+**     the names of its contributors may be used to endorse or promote
+**     products derived from this software without specific prior written
+**     permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+****************************************************************************/
+
+#include "qtlockedfile.h"
+#include <qt_windows.h>
+#include <QtCore/QFileInfo>
+
+#define MUTEX_PREFIX "QtLockedFile mutex "
+// Maximum number of concurrent read locks. Must not be greater than MAXIMUM_WAIT_OBJECTS
+#define MAX_READERS MAXIMUM_WAIT_OBJECTS
+
+Qt::HANDLE QtLockedFile::getMutexHandle(int idx, bool doCreate)
+{
+    if (mutexname.isEmpty()) {
+        QFileInfo fi(*this);
+        mutexname = QString::fromLatin1(MUTEX_PREFIX)
+                    + fi.absoluteFilePath().toLower();
+    }
+    QString mname(mutexname);
+    if (idx >= 0)
+        mname += QString::number(idx);
+
+    Qt::HANDLE mutex;
+    if (doCreate) {
+        QT_WA( { mutex = CreateMutexW(NULL, FALSE, (TCHAR*)mname.utf16()); },
+               { mutex = CreateMutexA(NULL, FALSE, mname.toLocal8Bit().constData()); } );
+        if (!mutex) {
+            qErrnoWarning("QtLockedFile::lock(): CreateMutex failed");
+            return 0;
+        }
+    }
+    else {
+        QT_WA( { mutex = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, (TCHAR*)mname.utf16()); },
+               { mutex = OpenMutexA(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, mname.toLocal8Bit().constData()); } );
+        if (!mutex) {
+            if (GetLastError() != ERROR_FILE_NOT_FOUND)
+                qErrnoWarning("QtLockedFile::lock(): OpenMutex failed");
+            return 0;
+        }
+    }
+    return mutex;
+}
+
+bool QtLockedFile::waitMutex(Qt::HANDLE mutex, bool doBlock)
+{
+    Q_ASSERT(mutex);
+    DWORD res = WaitForSingleObject(mutex, doBlock ? INFINITE : 0);
+    switch (res) {
+    case WAIT_OBJECT_0:
+    case WAIT_ABANDONED:
+        return true;
+        break;
+    case WAIT_TIMEOUT:
+        break;
+    default:
+        qErrnoWarning("QtLockedFile::lock(): WaitForSingleObject failed");
+    }
+    return false;
+}
+
+
+
+bool QtLockedFile::lock(LockMode mode, bool block)
+{
+    if (!isOpen()) {
+        qWarning("QtLockedFile::lock(): file is not opened");
+        return false;
+    }
+
+    if (mode == NoLock)
+        return unlock();
+
+    if (mode == m_lock_mode)
+        return true;
+
+    if (m_lock_mode != NoLock)
+        unlock();
+
+    if (!wmutex && !(wmutex = getMutexHandle(-1, true)))
+        return false;
+
+    if (!waitMutex(wmutex, block))
+        return false;
+
+    if (mode == ReadLock) {
+        int idx = 0;
+        for (; idx < MAX_READERS; idx++) {
+            rmutex = getMutexHandle(idx, false);
+            if (!rmutex || waitMutex(rmutex, false))
+                break;
+            CloseHandle(rmutex);
+        }
+        bool ok = true;
+        if (idx >= MAX_READERS) {
+            qWarning("QtLockedFile::lock(): too many readers");
+            rmutex = 0;
+            ok = false;
+        }
+        else if (!rmutex) {
+            rmutex = getMutexHandle(idx, true);
+            if (!rmutex || !waitMutex(rmutex, false))
+                ok = false;
+        }
+        if (!ok && rmutex) {
+            CloseHandle(rmutex);
+            rmutex = 0;
+        }
+        ReleaseMutex(wmutex);
+        if (!ok)
+            return false;
+    }
+    else {
+        Q_ASSERT(rmutexes.isEmpty());
+        for (int i = 0; i < MAX_READERS; i++) {
+            Qt::HANDLE mutex = getMutexHandle(i, false);
+            if (mutex)
+                rmutexes.append(mutex);
+        }
+        if (rmutexes.size()) {
+            DWORD res = WaitForMultipleObjects(rmutexes.size(), rmutexes.constData(),
+                                               TRUE, block ? INFINITE : 0);
+            if (res != WAIT_OBJECT_0 && res != WAIT_ABANDONED) {
+                if (res != WAIT_TIMEOUT)
+                    qErrnoWarning("QtLockedFile::lock(): WaitForMultipleObjects failed");
+                m_lock_mode = WriteLock;  // trick unlock() to clean up - semiyucky
+                unlock();
+                return false;
+            }
+        }
+    }
+
+    m_lock_mode = mode;
+    return true;
+}
+
+bool QtLockedFile::unlock()
+{
+    if (!isOpen()) {
+        qWarning("QtLockedFile::unlock(): file is not opened");
+        return false;
+    }
+
+    if (!isLocked())
+        return true;
+
+    if (m_lock_mode == ReadLock) {
+        ReleaseMutex(rmutex);
+        CloseHandle(rmutex);
+        rmutex = 0;
+    }
+    else {
+        foreach(Qt::HANDLE mutex, rmutexes) {
+            ReleaseMutex(mutex);
+            CloseHandle(mutex);
+        }
+        rmutexes.clear();
+        ReleaseMutex(wmutex);
+    }
+
+    m_lock_mode = QtLockedFile::NoLock;
+    return true;
+}
+
+QtLockedFile::~QtLockedFile()
+{
+    if (isOpen())
+        unlock();
+    if (wmutex)
+        CloseHandle(wmutex);
+}
diff --git a/AirTV-Qt/qtsingleapplication/src/qtsingleapplication.cpp b/AirTV-Qt/qtsingleapplication/src/qtsingleapplication.cpp
new file mode 100644 (file)
index 0000000..5a8f1b0
--- /dev/null
@@ -0,0 +1,344 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of a Qt Solutions component.
+**
+** You may use this file under the terms of the BSD license as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+**   * Redistributions of source code must retain the above copyright
+**     notice, this list of conditions and the following disclaimer.
+**   * Redistributions in binary form must reproduce the above copyright
+**     notice, this list of conditions and the following disclaimer in
+**     the documentation and/or other materials provided with the
+**     distribution.
+**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+**     the names of its contributors may be used to endorse or promote
+**     products derived from this software without specific prior written
+**     permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+****************************************************************************/
+
+
+#include "qtsingleapplication.h"
+#include "qtlocalpeer.h"
+#include <QtGui/QWidget>
+
+
+/*!
+    \class QtSingleApplication qtsingleapplication.h
+    \brief The QtSingleApplication class provides an API to detect and
+    communicate with running instances of an application.
+
+    This class allows you to create applications where only one
+    instance should be running at a time. I.e., if the user tries to
+    launch another instance, the already running instance will be
+    activated instead. Another usecase is a client-server system,
+    where the first started instance will assume the role of server,
+    and the later instances will act as clients of that server.
+
+    By default, the full path of the executable file is used to
+    determine whether two processes are instances of the same
+    application. You can also provide an explicit identifier string
+    that will be compared instead.
+
+    The application should create the QtSingleApplication object early
+    in the startup phase, and call isRunning() to find out if another
+    instance of this application is already running. If isRunning()
+    returns false, it means that no other instance is running, and
+    this instance has assumed the role as the running instance. In
+    this case, the application should continue with the initialization
+    of the application user interface before entering the event loop
+    with exec(), as normal.
+
+    The messageReceived() signal will be emitted when the running
+    application receives messages from another instance of the same
+    application. When a message is received it might be helpful to the
+    user to raise the application so that it becomes visible. To
+    facilitate this, QtSingleApplication provides the
+    setActivationWindow() function and the activateWindow() slot.
+
+    If isRunning() returns true, another instance is already
+    running. It may be alerted to the fact that another instance has
+    started by using the sendMessage() function. Also data such as
+    startup parameters (e.g. the name of the file the user wanted this
+    new instance to open) can be passed to the running instance with
+    this function. Then, the application should terminate (or enter
+    client mode).
+
+    If isRunning() returns true, but sendMessage() fails, that is an
+    indication that the running instance is frozen.
+
+    Here's an example that shows how to convert an existing
+    application to use QtSingleApplication. It is very simple and does
+    not make use of all QtSingleApplication's functionality (see the
+    examples for that).
+
+    \code
+    // Original
+    int main(int argc, char **argv)
+    {
+        QApplication app(argc, argv);
+
+        MyMainWidget mmw;
+        mmw.show();
+        return app.exec();
+    }
+
+    // Single instance
+    int main(int argc, char **argv)
+    {
+        QtSingleApplication app(argc, argv);
+
+        if (app.isRunning())
+            return !app.sendMessage(someDataString);
+
+        MyMainWidget mmw;
+        app.setActivationWindow(&mmw);
+        mmw.show();
+        return app.exec();
+    }
+    \endcode
+
+    Once this QtSingleApplication instance is destroyed (normally when
+    the process exits or crashes), when the user next attempts to run the
+    application this instance will not, of course, be encountered. The
+    next instance to call isRunning() or sendMessage() will assume the
+    role as the new running instance.
+
+    For console (non-GUI) applications, QtSingleCoreApplication may be
+    used instead of this class, to avoid the dependency on the QtGui
+    library.
+
+    \sa QtSingleCoreApplication
+*/
+
+
+void QtSingleApplication::sysInit(const QString &appId)
+{
+    actWin = 0;
+    peer = new QtLocalPeer(this, appId);
+    connect(peer, SIGNAL(messageReceived(const QString&)), SIGNAL(messageReceived(const QString&)));
+}
+
+
+/*!
+    Creates a QtSingleApplication object. The application identifier
+    will be QCoreApplication::applicationFilePath(). \a argc, \a
+    argv, and \a GUIenabled are passed on to the QAppliation constructor.
+
+    If you are creating a console application (i.e. setting \a
+    GUIenabled to false), you may consider using
+    QtSingleCoreApplication instead.
+*/
+
+QtSingleApplication::QtSingleApplication(int &argc, char **argv, bool GUIenabled)
+    : QApplication(argc, argv, GUIenabled)
+{
+    sysInit();
+}
+
+
+/*!
+    Creates a QtSingleApplication object with the application
+    identifier \a appId. \a argc and \a argv are passed on to the
+    QAppliation constructor.
+*/
+
+QtSingleApplication::QtSingleApplication(const QString &appId, int &argc, char **argv)
+    : QApplication(argc, argv)
+{
+    sysInit(appId);
+}
+
+
+/*!
+    Creates a QtSingleApplication object. The application identifier
+    will be QCoreApplication::applicationFilePath(). \a argc, \a
+    argv, and \a type are passed on to the QAppliation constructor.
+*/
+QtSingleApplication::QtSingleApplication(int &argc, char **argv, Type type)
+    : QApplication(argc, argv, type)
+{
+    sysInit();
+}
+
+
+#if defined(Q_WS_X11)
+/*!
+  Special constructor for X11, ref. the documentation of
+  QApplication's corresponding constructor. The application identifier
+  will be QCoreApplication::applicationFilePath(). \a dpy, \a visual,
+  and \a cmap are passed on to the QApplication constructor.
+*/
+QtSingleApplication::QtSingleApplication(Display* dpy, Qt::HANDLE visual, Qt::HANDLE cmap)
+    : QApplication(dpy, visual, cmap)
+{
+    sysInit();
+}
+
+/*!
+  Special constructor for X11, ref. the documentation of
+  QApplication's corresponding constructor. The application identifier
+  will be QCoreApplication::applicationFilePath(). \a dpy, \a argc, \a
+  argv, \a visual, and \a cmap are passed on to the QApplication
+  constructor.
+*/
+QtSingleApplication::QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap)
+    : QApplication(dpy, argc, argv, visual, cmap)
+{
+    sysInit();
+}
+
+/*!
+  Special constructor for X11, ref. the documentation of
+  QApplication's corresponding constructor. The application identifier
+  will be \a appId. \a dpy, \a argc, \a
+  argv, \a visual, and \a cmap are passed on to the QApplication
+  constructor.
+*/
+QtSingleApplication::QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap)
+    : QApplication(dpy, argc, argv, visual, cmap)
+{
+    sysInit(appId);
+}
+#endif
+
+
+/*!
+    Returns true if another instance of this application is running;
+    otherwise false.
+
+    This function does not find instances of this application that are
+    being run by a different user (on Windows: that are running in
+    another session).
+
+    \sa sendMessage()
+*/
+
+bool QtSingleApplication::isRunning()
+{
+    return peer->isClient();
+}
+
+
+/*!
+    Tries to send the text \a message to the currently running
+    instance. The QtSingleApplication object in the running instance
+    will emit the messageReceived() signal when it receives the
+    message.
+
+    This function returns true if the message has been sent to, and
+    processed by, the current instance. If there is no instance
+    currently running, or if the running instance fails to process the
+    message within \a timeout milliseconds, this function return false.
+
+    \sa isRunning(), messageReceived()
+*/
+bool QtSingleApplication::sendMessage(const QString &message, int timeout)
+{
+    return peer->sendMessage(message, timeout);
+}
+
+
+/*!
+    Returns the application identifier. Two processes with the same
+    identifier will be regarded as instances of the same application.
+*/
+QString QtSingleApplication::id() const
+{
+    return peer->applicationId();
+}
+
+
+/*!
+  Sets the activation window of this application to \a aw. The
+  activation window is the widget that will be activated by
+  activateWindow(). This is typically the application's main window.
+
+  If \a activateOnMessage is true (the default), the window will be
+  activated automatically every time a message is received, just prior
+  to the messageReceived() signal being emitted.
+
+  \sa activateWindow(), messageReceived()
+*/
+
+void QtSingleApplication::setActivationWindow(QWidget* aw, bool activateOnMessage)
+{
+    actWin = aw;
+    if (activateOnMessage)
+        connect(peer, SIGNAL(messageReceived(const QString&)), this, SLOT(activateWindow()));
+    else
+        disconnect(peer, SIGNAL(messageReceived(const QString&)), this, SLOT(activateWindow()));
+}
+
+
+/*!
+    Returns the applications activation window if one has been set by
+    calling setActivationWindow(), otherwise returns 0.
+
+    \sa setActivationWindow()
+*/
+QWidget* QtSingleApplication::activationWindow() const
+{
+    return actWin;
+}
+
+
+/*!
+  De-minimizes, raises, and activates this application's activation window.
+  This function does nothing if no activation window has been set.
+
+  This is a convenience function to show the user that this
+  application instance has been activated when he has tried to start
+  another instance.
+
+  This function should typically be called in response to the
+  messageReceived() signal. By default, that will happen
+  automatically, if an activation window has been set.
+
+  \sa setActivationWindow(), messageReceived(), initialize()
+*/
+void QtSingleApplication::activateWindow()
+{
+    if (actWin) {
+        actWin->setWindowState(actWin->windowState() & ~Qt::WindowMinimized);
+        actWin->raise();
+        actWin->activateWindow();
+    }
+}
+
+
+/*!
+    \fn void QtSingleApplication::messageReceived(const QString& message)
+
+    This signal is emitted when the current instance receives a \a
+    message from another instance of this application.
+
+    \sa sendMessage(), setActivationWindow(), activateWindow()
+*/
+
+
+/*!
+    \fn void QtSingleApplication::initialize(bool dummy = true)
+
+    \obsolete
+*/
diff --git a/AirTV-Qt/qtsingleapplication/src/qtsingleapplication.h b/AirTV-Qt/qtsingleapplication/src/qtsingleapplication.h
new file mode 100644 (file)
index 0000000..d1613a4
--- /dev/null
@@ -0,0 +1,102 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of a Qt Solutions component.
+**
+** You may use this file under the terms of the BSD license as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+**   * Redistributions of source code must retain the above copyright
+**     notice, this list of conditions and the following disclaimer.
+**   * Redistributions in binary form must reproduce the above copyright
+**     notice, this list of conditions and the following disclaimer in
+**     the documentation and/or other materials provided with the
+**     distribution.
+**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+**     the names of its contributors may be used to endorse or promote
+**     products derived from this software without specific prior written
+**     permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+****************************************************************************/
+
+#ifndef QTSINGLEAPPLICATION_H
+#define QTSINGLEAPPLICATION_H
+
+#include <QtGui/QApplication>
+
+class QtLocalPeer;
+
+#if defined(Q_WS_WIN)
+#  if !defined(QT_QTSINGLEAPPLICATION_EXPORT) && !defined(QT_QTSINGLEAPPLICATION_IMPORT)
+#    define QT_QTSINGLEAPPLICATION_EXPORT
+#  elif defined(QT_QTSINGLEAPPLICATION_IMPORT)
+#    if defined(QT_QTSINGLEAPPLICATION_EXPORT)
+#      undef QT_QTSINGLEAPPLICATION_EXPORT
+#    endif
+#    define QT_QTSINGLEAPPLICATION_EXPORT __declspec(dllimport)
+#  elif defined(QT_QTSINGLEAPPLICATION_EXPORT)
+#    undef QT_QTSINGLEAPPLICATION_EXPORT
+#    define QT_QTSINGLEAPPLICATION_EXPORT __declspec(dllexport)
+#  endif
+#else
+#  define QT_QTSINGLEAPPLICATION_EXPORT
+#endif
+
+class QT_QTSINGLEAPPLICATION_EXPORT QtSingleApplication : public QApplication
+{
+    Q_OBJECT
+
+public:
+    QtSingleApplication(int &argc, char **argv, bool GUIenabled = true);
+    QtSingleApplication(const QString &id, int &argc, char **argv);
+    QtSingleApplication(int &argc, char **argv, Type type);
+#if defined(Q_WS_X11)
+    QtSingleApplication(Display* dpy, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0);
+    QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE cmap= 0);
+    QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0);
+#endif
+
+    bool isRunning();
+    QString id() const;
+
+    void setActivationWindow(QWidget* aw, bool activateOnMessage = true);
+    QWidget* activationWindow() const;
+
+    // Obsolete:
+    void initialize(bool dummy = true)
+        { isRunning(); Q_UNUSED(dummy) }
+
+public Q_SLOTS:
+    bool sendMessage(const QString &message, int timeout = 5000);
+    void activateWindow();
+
+
+Q_SIGNALS:
+    void messageReceived(const QString &message);
+
+
+private:
+    void sysInit(const QString &appId = QString());
+    QtLocalPeer *peer;
+    QWidget *actWin;
+};
+
+#endif // QTSINGLEAPPLICATION_H
diff --git a/AirTV-Qt/qtsingleapplication/src/qtsingleapplication.pri b/AirTV-Qt/qtsingleapplication/src/qtsingleapplication.pri
new file mode 100644 (file)
index 0000000..5909f04
--- /dev/null
@@ -0,0 +1,16 @@
+include(../common.pri)
+INCLUDEPATH += $$PWD
+DEPENDPATH += $$PWD
+QT *= network
+
+qtsingleapplication-uselib:!qtsingleapplication-buildlib {
+    LIBS += -L$$QTSINGLEAPPLICATION_LIBDIR -l$$QTSINGLEAPPLICATION_LIBNAME
+} else {
+    SOURCES += $$PWD/qtsingleapplication.cpp $$PWD/qtlocalpeer.cpp
+    HEADERS += $$PWD/qtsingleapplication.h $$PWD/qtlocalpeer.h
+}
+
+win32 {
+    contains(TEMPLATE, lib):contains(CONFIG, shared):DEFINES += QT_QTSINGLEAPPLICATION_EXPORT
+    else:qtsingleapplication-uselib:DEFINES += QT_QTSINGLEAPPLICATION_IMPORT
+}
diff --git a/AirTV-Qt/qtsingleapplication/src/qtsinglecoreapplication.cpp b/AirTV-Qt/qtsingleapplication/src/qtsinglecoreapplication.cpp
new file mode 100644 (file)
index 0000000..cf60771
--- /dev/null
@@ -0,0 +1,148 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of a Qt Solutions component.
+**
+** You may use this file under the terms of the BSD license as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+**   * Redistributions of source code must retain the above copyright
+**     notice, this list of conditions and the following disclaimer.
+**   * Redistributions in binary form must reproduce the above copyright
+**     notice, this list of conditions and the following disclaimer in
+**     the documentation and/or other materials provided with the
+**     distribution.
+**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+**     the names of its contributors may be used to endorse or promote
+**     products derived from this software without specific prior written
+**     permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+****************************************************************************/
+
+
+#include "qtsinglecoreapplication.h"
+#include "qtlocalpeer.h"
+
+/*!
+    \class QtSingleCoreApplication qtsinglecoreapplication.h
+    \brief A variant of the QtSingleApplication class for non-GUI applications.
+
+    This class is a variant of QtSingleApplication suited for use in
+    console (non-GUI) applications. It is an extension of
+    QCoreApplication (instead of QApplication). It does not require
+    the QtGui library.
+
+    The API and usage is identical to QtSingleApplication, except that
+    functions relating to the "activation window" are not present, for
+    obvious reasons. Please refer to the QtSingleApplication
+    documentation for explanation of the usage.
+
+    A QtSingleCoreApplication instance can communicate to a
+    QtSingleApplication instance if they share the same application
+    id. Hence, this class can be used to create a light-weight
+    command-line tool that sends commands to a GUI application.
+
+    \sa QtSingleApplication
+*/
+
+/*!
+    Creates a QtSingleCoreApplication object. The application identifier
+    will be QCoreApplication::applicationFilePath(). \a argc and \a
+    argv are passed on to the QCoreAppliation constructor.
+*/
+
+QtSingleCoreApplication::QtSingleCoreApplication(int &argc, char **argv)
+    : QCoreApplication(argc, argv)
+{
+    peer = new QtLocalPeer(this);
+    connect(peer, SIGNAL(messageReceived(const QString&)), SIGNAL(messageReceived(const QString&)));
+}
+
+
+/*!
+    Creates a QtSingleCoreApplication object with the application
+    identifier \a appId. \a argc and \a argv are passed on to the
+    QCoreAppliation constructor.
+*/
+QtSingleCoreApplication::QtSingleCoreApplication(const QString &appId, int &argc, char **argv)
+    : QCoreApplication(argc, argv)
+{
+    peer = new QtLocalPeer(this, appId);
+    connect(peer, SIGNAL(messageReceived(const QString&)), SIGNAL(messageReceived(const QString&)));
+}
+
+
+/*!
+    Returns true if another instance of this application is running;
+    otherwise false.
+
+    This function does not find instances of this application that are
+    being run by a different user (on Windows: that are running in
+    another session).
+
+    \sa sendMessage()
+*/
+
+bool QtSingleCoreApplication::isRunning()
+{
+    return peer->isClient();
+}
+
+
+/*!
+    Tries to send the text \a message to the currently running
+    instance. The QtSingleCoreApplication object in the running instance
+    will emit the messageReceived() signal when it receives the
+    message.
+
+    This function returns true if the message has been sent to, and
+    processed by, the current instance. If there is no instance
+    currently running, or if the running instance fails to process the
+    message within \a timeout milliseconds, this function return false.
+
+    \sa isRunning(), messageReceived()
+*/
+
+bool QtSingleCoreApplication::sendMessage(const QString &message, int timeout)
+{
+    return peer->sendMessage(message, timeout);
+}
+
+
+/*!
+    Returns the application identifier. Two processes with the same
+    identifier will be regarded as instances of the same application.
+*/
+
+QString QtSingleCoreApplication::id() const
+{
+    return peer->applicationId();
+}
+
+
+/*!
+    \fn void QtSingleCoreApplication::messageReceived(const QString& message)
+
+    This signal is emitted when the current instance receives a \a
+    message from another instance of this application.
+
+    \sa sendMessage()
+*/
diff --git a/AirTV-Qt/qtsingleapplication/src/qtsinglecoreapplication.h b/AirTV-Qt/qtsingleapplication/src/qtsinglecoreapplication.h
new file mode 100644 (file)
index 0000000..7cde4b8
--- /dev/null
@@ -0,0 +1,70 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of a Qt Solutions component.
+**
+** You may use this file under the terms of the BSD license as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+**   * Redistributions of source code must retain the above copyright
+**     notice, this list of conditions and the following disclaimer.
+**   * Redistributions in binary form must reproduce the above copyright
+**     notice, this list of conditions and the following disclaimer in
+**     the documentation and/or other materials provided with the
+**     distribution.
+**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+**     the names of its contributors may be used to endorse or promote
+**     products derived from this software without specific prior written
+**     permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+****************************************************************************/
+
+#ifndef QTSINGLECOREAPPLICATION_H
+#define QTSINGLECOREAPPLICATION_H
+
+#include <QtCore/QCoreApplication>
+
+class QtLocalPeer;
+
+class QtSingleCoreApplication : public QCoreApplication
+{
+    Q_OBJECT
+
+public:
+    QtSingleCoreApplication(int &argc, char **argv);
+    QtSingleCoreApplication(const QString &id, int &argc, char **argv);
+
+    bool isRunning();
+    QString id() const;
+
+public Q_SLOTS:
+    bool sendMessage(const QString &message, int timeout = 5000);
+
+
+Q_SIGNALS:
+    void messageReceived(const QString &message);
+
+
+private:
+    QtLocalPeer* peer;
+};
+
+#endif // QTSINGLECOREAPPLICATION_H
diff --git a/AirTV-Qt/qtsingleapplication/src/qtsinglecoreapplication.pri b/AirTV-Qt/qtsingleapplication/src/qtsinglecoreapplication.pri
new file mode 100644 (file)
index 0000000..d2d6cc3
--- /dev/null
@@ -0,0 +1,10 @@
+INCLUDEPATH    += $$PWD
+DEPENDPATH      += $$PWD
+HEADERS                += $$PWD/qtsinglecoreapplication.h $$PWD/qtlocalpeer.h
+SOURCES                += $$PWD/qtsinglecoreapplication.cpp $$PWD/qtlocalpeer.cpp
+
+QT *= network
+
+win32:contains(TEMPLATE, lib):contains(CONFIG, shared) {
+    DEFINES += QT_QTSINGLECOREAPPLICATION_EXPORT=__declspec(dllexport)
+}
diff --git a/AirTV-Qt/raopcallbackhandler.cpp b/AirTV-Qt/raopcallbackhandler.cpp
new file mode 100644 (file)
index 0000000..0852fe8
--- /dev/null
@@ -0,0 +1,45 @@
+#include "raopcallbackhandler.h"
+
+RaopCallbackHandler::RaopCallbackHandler(QObject *parent) :
+    QObject(parent)
+{
+}
+
+void RaopCallbackHandler::audioInit(void *session, int bits, int channels, int samplerate)
+{
+    void **retval = (void**)session;
+
+    AudioOutput *audioOutput = new AudioOutput(0);
+    audioOutput->init(bits, channels, samplerate);
+    audioOutput->start();
+    *retval = audioOutput;
+
+    m_outputList.append(audioOutput);
+}
+
+void RaopCallbackHandler::audioSetVolume(void *session, float volume)
+{
+    AudioOutput *audioOutput = (AudioOutput*)session;
+    audioOutput->setVolume(volume);
+}
+
+void RaopCallbackHandler::audioProcess(void *session, void *buffer, int buflen)
+{
+    AudioOutput *audioOutput = (AudioOutput*)session;
+    audioOutput->output((const char *)buffer, buflen);
+}
+
+void RaopCallbackHandler::audioFlush(void *session)
+{
+    AudioOutput *audioOutput = (AudioOutput*)session;
+    audioOutput->flush();
+}
+
+void RaopCallbackHandler::audioDestroy(void *session)
+{
+    AudioOutput *audioOutput = (AudioOutput*)session;
+    m_outputList.removeAll(audioOutput);
+
+    audioOutput->stop();
+    delete audioOutput;
+}
diff --git a/AirTV-Qt/raopcallbackhandler.h b/AirTV-Qt/raopcallbackhandler.h
new file mode 100644 (file)
index 0000000..3c253ed
--- /dev/null
@@ -0,0 +1,27 @@
+#ifndef RAOPCALLBACKHANDLER_H
+#define RAOPCALLBACKHANDLER_H
+
+#include <QObject>
+
+#include "audiooutput.h"
+
+class RaopCallbackHandler : public QObject
+{
+    Q_OBJECT
+public:
+    explicit RaopCallbackHandler(QObject *parent = 0);
+
+private:
+    QList<AudioOutput*>  m_outputList;
+
+signals:
+
+public slots:
+    void audioInit(void *session, int bits, int channels, int samplerate);
+    void audioSetVolume(void *session, float volume);
+    void audioProcess(void *session, void *buffer, int buflen);
+    void audioFlush(void *session);
+    void audioDestroy(void *session);
+};
+
+#endif // RAOPCALLBACKHANDLER_H
diff --git a/AirTV-Qt/raopservice.cpp b/AirTV-Qt/raopservice.cpp
new file mode 100644 (file)
index 0000000..79472c1
--- /dev/null
@@ -0,0 +1,145 @@
+#include "raopservice.h"
+
+#include <QDebug>
+#include <QFile>
+
+static void
+audio_init(void *cls, void **session, int bits, int channels, int samplerate)
+{
+    QMetaObject::invokeMethod((QObject*)cls, "audioInit", Qt::BlockingQueuedConnection,
+                              Q_ARG(void*, (void*)session),
+                              Q_ARG(int, bits),
+                              Q_ARG(int, channels),
+                              Q_ARG(int, samplerate));
+}
+
+static void
+audio_set_volume(void *cls, void *session, float volume)
+{
+    QMetaObject::invokeMethod((QObject*)cls, "audioSetVolume", Qt::BlockingQueuedConnection,
+                              Q_ARG(void*, session),
+                              Q_ARG(float, volume));
+}
+
+static void
+audio_process(void *cls, void *session, const void *buffer, int buflen)
+{
+    QMetaObject::invokeMethod((QObject*)cls, "audioProcess", Qt::BlockingQueuedConnection,
+                              Q_ARG(void*, session),
+                              Q_ARG(void*, (void*)buffer),
+                              Q_ARG(int, buflen));
+}
+
+static void
+audio_flush(void *cls, void *session)
+{
+    QMetaObject::invokeMethod((QObject*)cls, "audioFlush", Qt::BlockingQueuedConnection,
+                              Q_ARG(void*, session));
+}
+
+static void
+audio_destroy(void *cls, void *session)
+{
+    QMetaObject::invokeMethod((QObject*)cls, "audioDestroy", Qt::BlockingQueuedConnection,
+                              Q_ARG(void*, session));
+}
+
+RaopService::RaopService(QObject *parent) :
+    QObject(parent),
+    m_dnssd(0),
+    m_raop(0)
+{
+    /* This whole hack is required because QAudioOutput
+     * needs to be created in a QThread, threads created
+     * outside Qt are not allowed (they have no eventloop) */
+    m_handler.moveToThread(&m_thread);
+}
+
+RaopService::~RaopService()
+{
+    this->stop();
+
+    dnssd_destroy(m_dnssd);
+    raop_destroy(m_raop);
+}
+
+bool RaopService::init()
+{
+    const char hwaddr[] = { 0x48, 0x5d, 0x60, 0x7c, 0xee, 0x22 };
+    raop_callbacks_t raop_cbs;
+    int error;
+
+    raop_cbs.cls = &m_handler;
+    raop_cbs.audio_init = audio_init;
+    raop_cbs.audio_set_volume = audio_set_volume;
+    raop_cbs.audio_process = audio_process;
+    raop_cbs.audio_flush = audio_flush;
+    raop_cbs.audio_destroy = audio_destroy;
+
+    QFile file("airport.key");
+    if (!file.exists()) {
+        // This is used when running from Qt Creator on Mac
+        file.setFileName("../../../../airport.key");
+    }
+    if (!file.exists()) {
+        // This is used when running from Qt Creator on Windows
+        file.setFileName("../airport.key");
+    }
+    if (!file.exists()) {
+        return false;
+    }
+    file.open(QIODevice::ReadOnly);
+    QByteArray array = file.read(file.size());
+    array.append('\0');
+
+    m_raop = raop_init(&raop_cbs, array.data(), hwaddr, sizeof(hwaddr));
+    if (!m_raop) {
+        return false;
+    }
+
+    m_dnssd = dnssd_init(hwaddr, sizeof(hwaddr), &error);
+    if (!m_dnssd) {
+        raop_destroy(m_raop);
+        m_raop = NULL;
+        return false;
+    }
+
+    return true;
+}
+
+bool RaopService::start(const QString & name, quint16 port)
+{
+    if (!m_raop || !m_dnssd || m_thread.isRunning()) {
+        return false;
+    }
+
+    m_thread.start();
+    if (raop_start(m_raop, &port) < 0) {
+        m_thread.quit();
+        m_thread.wait();
+        return false;
+    }
+    if (dnssd_register_raop(m_dnssd, name.toUtf8(), port) < 0) {
+        raop_stop(m_raop);
+        m_thread.quit();
+        m_thread.wait();
+        return false;
+    }
+
+    return true;
+}
+
+void RaopService::stop()
+{
+    if (m_dnssd) {
+        dnssd_unregister_raop(m_dnssd);
+    }
+    if (m_raop) {
+        raop_stop(m_raop);
+    }
+    if (m_thread.isRunning()) {
+        m_thread.quit();
+        m_thread.wait();
+    }
+}
+
diff --git a/AirTV-Qt/raopservice.h b/AirTV-Qt/raopservice.h
new file mode 100644 (file)
index 0000000..f82fec4
--- /dev/null
@@ -0,0 +1,36 @@
+#ifndef RAOPSERVICE_H
+#define RAOPSERVICE_H
+
+#include <QObject>
+#include <QThread>
+
+#include "raopcallbackhandler.h"
+
+#include "dnssd.h"
+#include "raop.h"
+
+class RaopService : public QObject
+{
+    Q_OBJECT
+public:
+    explicit RaopService(QObject *parent = 0);
+    ~RaopService();
+
+    bool init();
+    bool start(const QString & name=QString("AirTV"), quint16 port=5000);
+    void stop();
+
+private:
+    dnssd_t *            m_dnssd;
+    raop_t *             m_raop;
+
+    QThread              m_thread;
+    RaopCallbackHandler  m_handler;
+
+signals:
+
+public slots:
+
+};
+
+#endif // RAOPSERVICE_H
diff --git a/Makefile b/Makefile
new file mode 100644 (file)
index 0000000..5a02298
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,12 @@
+CFLAGS:=-g -Wall -Iinclude/
+LDFLAGS:=-lm
+LIB_OBJS=src/alac/alac.o src/crypto/aes.o src/crypto/bigint.o src/crypto/hmac.o src/crypto/md5.o src/crypto/rc4.o src/crypto/sha1.o src/sdp.o src/raop_buffer.o src/raop_rtp.o src/http_response.o src/http_request.o src/http_parser.o src/httpd.o src/raop.o src/rsakey.o src/rsapem.o src/dnssd.o src/netutils.o src/utils.o src/base64.o src/logger.o
+
+
+all: shairport
+
+shairport: test/shairport.o $(LIB_OBJS)
+       $(CC) $(CFLAGS) test/shairport.o $(LIB_OBJS) -o $@ $(LDFLAGS)
+
+clean:
+       rm -f shairport test/*.o $(LIB_OBJS)
diff --git a/README b/README
new file mode 100644 (file)
index 0000000..b3d67cf
--- /dev/null
+++ b/README
@@ -0,0 +1 @@
+Some text needs to be added here.
diff --git a/airport.key b/airport.key
new file mode 100644 (file)
index 0000000..ad041c4
--- /dev/null
@@ -0,0 +1,23 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIIEpQIBAAKCAQEA59dE8qLieItsH1WgjrcFRKj6eUWqi+bGLOX1HL3U3GhC/j0Qg90u3sG/1CUt
+wC5vOYvfDmFI6oSFXi5ELabWJmT2dKHzBJKa3k9ok+8t9ucRqMd6DZHJ2YCCLlDRKSKv6kDqnw4U
+wPdpOMXziC/AMj3Z/lUVX1G7WSHCAWKf1zNS1eLvqr+boEjXuBOitnZ/bDzPHrTOZz0Dew0uowxf
+/+sG+NCK3eQJVxqcaJ/vEHKIVd2M+5qL71yJQ+87X6oV3eaYvt3zWZYD6z5vYTcrtij2VZ9Zmni/
+UAaHqn9JdsBWLUEpVviYnhimNVvYFZeCXg/IdTQ+x4IRdiXNv5hEewIDAQABAoIBAQDl8Axy9XfW
+BLmkzkEiqoSwF0PsmVrPzH9KsnwLGH+QZlvjWd8SWYGN7u1507HvhF5N3drJoVU3O14nDY4TFQAa
+LlJ9VM35AApXaLyY1ERrN7u9ALKd2LUwYhM7Km539O4yUFYikE2nIPscEsA5ltpxOgUGCY7b7ez5
+NtD6nL1ZKauw7aNXmVAvmJTcuPxWmoktF3gDJKK2wxZuNGcJE0uFQEG4Z3BrWP7yoNuSK3dii2jm
+lpPHr0O/KnPQtzI3eguhe0TwUem/eYSdyzMyVx/YpwkzwtYL3sR5k0o9rKQLtvLzfAqdBxBurciz
+aaA/L0HIgAmOit1GJA2saMxTVPNhAoGBAPfgv1oeZxgxmotiCcMXFEQEWflzhWYTsXrhUIuz5jFu
+a39GLS99ZEErhLdrwj8rDDViRVJ5skOp9zFvlYAHs0xh92ji1E7V/ysnKBfsMrPkk5KSKPrnjndM
+oPdevWnVkgJ5jxFuNgxkOLMuG9i53B4yMvDTCRiIPMQ++N2iLDaRAoGBAO9v//mU8eVkQaoANf0Z
+oMjW8CN4xwWA2cSEIHkd9AfFkftuv8oyLDCG3ZAf0vrhrrtkrfa7ef+AUb69DNggq4mHQAYBp7L+
+k5DKzJrKuO0r+R0YbY9pZD1+/g9dVt91d6LQNepUE/yY2PP5CNoFmjedpLHMOPFdVgqDzDFxU8hL
+AoGBANDrr7xAJbqBjHVwIzQ4To9pb4BNeqDndk5Qe7fT3+/H1njGaC0/rXE0Qb7q5ySgnsCb3DvA
+cJyRM9SJ7OKlGt0FMSdJD5KG0XPIpAVNwgpXXH5MDJg09KHeh0kXo+QA6viFBi21y340NonnEfdf
+54PX4ZGS/Xac1UK+pLkBB+zRAoGAf0AY3H3qKS2lMEI4bzEFoHeK3G895pDaK3TFBVmD7fV0Zhov
+17fegFPMwOII8MisYm9ZfT2Z0s5Ro3s5rkt+nvLAdfC/PYPKzTLalpGSwomSNYJcB9HNMlmhkGzc
+1JnLYT4iyUyx6pcZBmCd8bD0iwY/FzcgNDaUmbX9+XDvRA0CgYEAkE7pIPlE71qvfJQgoA9em0gI
+LAuE4Pu13aKiJnfft7hIjbK+5kyb3TysZvoyDnb3HOKvInK7vXbKuU4ISgxB2bB3HcYzQMGsz1qJ
+2gG0N5hvJpzwwhbhXqFKA4zaaSrw622wDniAK5MlIE0tIAKKP4yxNGjoD2QYjhBGuhvkWKY=
+-----END RSA PRIVATE KEY-----
diff --git a/include/dnssd.h b/include/dnssd.h
new file mode 100644 (file)
index 0000000..32f3c98
--- /dev/null
@@ -0,0 +1,27 @@
+#ifndef DNSSD_H
+#define DNSSD_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define DNSSD_ERROR_NOERROR       0
+#define DNSSD_ERROR_HWADDRLEN     1
+#define DNSSD_ERROR_OUTOFMEM      2
+#define DNSSD_ERROR_LIBNOTFOUND   3
+#define DNSSD_ERROR_PROCNOTFOUND  4
+
+typedef struct dnssd_s dnssd_t;
+dnssd_t *dnssd_init(const char *hwaddr, int hwaddrlen, int *error);
+
+int dnssd_register_raop(dnssd_t *dnssd, const char *name, unsigned short port);
+int dnssd_register_airplay(dnssd_t *dnssd, const char *name, unsigned short port);
+
+void dnssd_unregister_raop(dnssd_t *dnssd);
+void dnssd_unregister_airplay(dnssd_t *dnssd);
+
+void dnssd_destroy(dnssd_t *dnssd);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/include/raop.h b/include/raop.h
new file mode 100644 (file)
index 0000000..604957a
--- /dev/null
@@ -0,0 +1,30 @@
+#ifndef RAOP_H
+#define RAOP_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct raop_s raop_t;
+
+struct raop_callbacks_s {
+       void* cls;
+       void  (*audio_init)(void *cls, void **session, int bits, int channels, int samplerate);
+       void  (*audio_set_volume)(void *cls, void *session, float volume);
+       void  (*audio_process)(void *cls, void *session, const void *buffer, int buflen);
+       void  (*audio_flush)(void *cls, void *session);
+       void  (*audio_destroy)(void *cls, void *session);
+};
+typedef struct raop_callbacks_s raop_callbacks_t;
+
+raop_t *raop_init(raop_callbacks_t *callbacks, const char *pemkey, const char *hwaddr, int hwaddrlen);
+raop_t *raop_init_from_keyfile(raop_callbacks_t *callbacks, const char *keyfile, const char *hwaddr, int hwaddrlen);
+
+int raop_start(raop_t *raop, unsigned short *port);
+void raop_stop(raop_t *raop);
+
+void raop_destroy(raop_t *raop);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/src/alac/alac.c b/src/alac/alac.c
new file mode 100644 (file)
index 0000000..9d575ae
--- /dev/null
@@ -0,0 +1,1172 @@
+/*
+ * ALAC (Apple Lossless Audio Codec) decoder
+ * Copyright (c) 2005 David Hammerton
+ * All rights reserved.
+ *
+ * This is the actual decoder.
+ *
+ * http://crazney.net/programs/itunes/alac.html
+ * 
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use,
+ * copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ */
+
+#ifdef __BIG_ENDIAN__
+static const int host_bigendian = 1;
+#else
+static const int host_bigendian = 0;
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _WIN32
+       #include "stdint_win.h"
+#else
+       #include <stdint.h>
+#endif
+
+#include "alac.h"
+
+#define _Swap32(v) do { \
+                   v = (((v) & 0x000000FF) << 0x18) | \
+                       (((v) & 0x0000FF00) << 0x08) | \
+                       (((v) & 0x00FF0000) >> 0x08) | \
+                       (((v) & 0xFF000000) >> 0x18); } while(0)
+
+#define _Swap16(v) do { \
+                   v = (((v) & 0x00FF) << 0x08) | \
+                       (((v) & 0xFF00) >> 0x08); } while (0)
+
+struct {signed int x:24;} se_struct_24;
+#define SignExtend24(val) (se_struct_24.x = val)
+
+struct alac_file
+{
+    unsigned char *input_buffer;
+    int input_buffer_bitaccumulator; /* used so we can do arbitary
+                                        bit reads */
+
+    int samplesize;
+    int numchannels;
+    int bytespersample;
+
+
+    /* buffers */
+    int32_t *predicterror_buffer_a;
+    int32_t *predicterror_buffer_b;
+
+    int32_t *outputsamples_buffer_a;
+    int32_t *outputsamples_buffer_b;
+       
+       int32_t *uncompressed_bytes_buffer_a;
+       int32_t *uncompressed_bytes_buffer_b;
+
+
+
+  /* stuff from setinfo */
+  uint32_t setinfo_max_samples_per_frame; /* 0x1000 = 4096 */    /* max samples per frame? */
+  uint8_t setinfo_7a; /* 0x00 */
+  uint8_t setinfo_sample_size; /* 0x10 */
+  uint8_t setinfo_rice_historymult; /* 0x28 */
+  uint8_t setinfo_rice_initialhistory; /* 0x0a */
+  uint8_t setinfo_rice_kmodifier; /* 0x0e */
+  uint8_t setinfo_7f; /* 0x02 */
+  uint16_t setinfo_80; /* 0x00ff */
+  uint32_t setinfo_82; /* 0x000020e7 */ /* max sample size?? */
+  uint32_t setinfo_86; /* 0x00069fe4 */ /* bit rate (avarge)?? */
+  uint32_t setinfo_8a_rate; /* 0x0000ac44 */
+  /* end setinfo stuff */
+
+};
+
+
+static void allocate_buffers(alac_file *alac)
+{
+    alac->predicterror_buffer_a = malloc(alac->setinfo_max_samples_per_frame * 4);
+    alac->predicterror_buffer_b = malloc(alac->setinfo_max_samples_per_frame * 4);
+
+    alac->outputsamples_buffer_a = malloc(alac->setinfo_max_samples_per_frame * 4);
+    alac->outputsamples_buffer_b = malloc(alac->setinfo_max_samples_per_frame * 4);
+       
+       alac->uncompressed_bytes_buffer_a = malloc(alac->setinfo_max_samples_per_frame * 4);
+       alac->uncompressed_bytes_buffer_b = malloc(alac->setinfo_max_samples_per_frame * 4);
+}
+
+void alac_set_info(alac_file *alac, char *inputbuffer)
+{
+  char *ptr = inputbuffer;
+  ptr += 4; /* size */
+  ptr += 4; /* frma */
+  ptr += 4; /* alac */
+  ptr += 4; /* size */
+  ptr += 4; /* alac */
+
+  ptr += 4; /* 0 ? */
+
+  alac->setinfo_max_samples_per_frame = *(uint32_t*)ptr; /* buffer size / 2 ? */
+  if (!host_bigendian)
+      _Swap32(alac->setinfo_max_samples_per_frame);
+  ptr += 4;
+  alac->setinfo_7a = *(uint8_t*)ptr;
+  ptr += 1;
+  alac->setinfo_sample_size = *(uint8_t*)ptr;
+  ptr += 1;
+  alac->setinfo_rice_historymult = *(uint8_t*)ptr;
+  ptr += 1;
+  alac->setinfo_rice_initialhistory = *(uint8_t*)ptr;
+  ptr += 1;
+  alac->setinfo_rice_kmodifier = *(uint8_t*)ptr;
+  ptr += 1;
+  alac->setinfo_7f = *(uint8_t*)ptr;
+  ptr += 1;
+  alac->setinfo_80 = *(uint16_t*)ptr;
+  if (!host_bigendian)
+      _Swap16(alac->setinfo_80);
+  ptr += 2;
+  alac->setinfo_82 = *(uint32_t*)ptr;
+  if (!host_bigendian)
+      _Swap32(alac->setinfo_82);
+  ptr += 4;
+  alac->setinfo_86 = *(uint32_t*)ptr;
+  if (!host_bigendian)
+      _Swap32(alac->setinfo_86);
+  ptr += 4;
+  alac->setinfo_8a_rate = *(uint32_t*)ptr;
+  if (!host_bigendian)
+      _Swap32(alac->setinfo_8a_rate);
+  ptr += 4;
+
+  allocate_buffers(alac);
+
+}
+
+/* stream reading */
+
+/* supports reading 1 to 16 bits, in big endian format */
+static uint32_t readbits_16(alac_file *alac, int bits)
+{
+    uint32_t result;
+    int new_accumulator;
+
+    result = (alac->input_buffer[0] << 16) |
+             (alac->input_buffer[1] << 8) |
+             (alac->input_buffer[2]);
+
+    /* shift left by the number of bits we've already read,
+     * so that the top 'n' bits of the 24 bits we read will
+     * be the return bits */
+    result = result << alac->input_buffer_bitaccumulator;
+
+    result = result & 0x00ffffff;
+
+    /* and then only want the top 'n' bits from that, where
+     * n is 'bits' */
+    result = result >> (24 - bits);
+
+    new_accumulator = (alac->input_buffer_bitaccumulator + bits);
+
+    /* increase the buffer pointer if we've read over n bytes. */
+    alac->input_buffer += (new_accumulator >> 3);
+
+    /* and the remainder goes back into the bit accumulator */
+    alac->input_buffer_bitaccumulator = (new_accumulator & 7);
+
+    return result;
+}
+
+/* supports reading 1 to 32 bits, in big endian format */
+static uint32_t readbits(alac_file *alac, int bits)
+{
+    int32_t result = 0;
+
+    if (bits > 16)
+    {
+        bits -= 16;
+        result = readbits_16(alac, 16) << bits;
+    }
+
+    result |= readbits_16(alac, bits);
+
+    return result;
+}
+
+/* reads a single bit */
+static int readbit(alac_file *alac)
+{
+    int result;
+    int new_accumulator;
+
+    result = alac->input_buffer[0];
+
+    result = result << alac->input_buffer_bitaccumulator;
+
+    result = result >> 7 & 1;
+
+    new_accumulator = (alac->input_buffer_bitaccumulator + 1);
+
+    alac->input_buffer += (new_accumulator / 8);
+
+    alac->input_buffer_bitaccumulator = (new_accumulator % 8);
+
+    return result;
+}
+
+static void unreadbits(alac_file *alac, int bits)
+{
+    int new_accumulator = (alac->input_buffer_bitaccumulator - bits);
+
+    alac->input_buffer += (new_accumulator >> 3);
+
+    alac->input_buffer_bitaccumulator = (new_accumulator & 7);
+    if (alac->input_buffer_bitaccumulator < 0)
+        alac->input_buffer_bitaccumulator *= -1;
+}
+
+/* various implementations of count_leading_zero:
+ * the first one is the original one, the simplest and most
+ * obvious for what it's doing. never use this.
+ * then there are the asm ones. fill in as necessary
+ * and finally an unrolled and optimised c version
+ * to fall back to
+ */
+#if 0
+/* hideously inefficient. could use a bitmask search,
+ * alternatively bsr on x86,
+ */
+static int count_leading_zeros(int32_t input)
+{
+    int i = 0;
+    while (!(0x80000000 & input) && i < 32)
+    {
+        i++;
+        input = input << 1;
+    }
+    return i;
+}
+#elif defined(__GNUC__) && (defined(_X86) || defined(__i386) || defined(i386))
+/* for some reason the unrolled version (below) is
+ * actually faster than this. yay intel!
+ */
+static int count_leading_zeros(int input)
+{
+    int output = 0;
+    if (!input) return 32;
+    __asm("bsr %1, %0\n"
+        : "=r" (output)
+        : "r" (input));
+    return (0x1f - output);
+}
+#elif defined(__GNUC__)
+static int count_leading_zeros(int input)
+{
+    return __builtin_clz(input);
+}
+#elif defined(_MSC_VER) && defined(_M_IX86)
+static int count_leading_zeros(int input)
+{
+    int output = 0;
+    if (!input) return 32;
+    __asm
+    {
+        mov eax, input;
+        mov edx, 0x1f;
+        bsr ecx, eax;
+        sub edx, ecx;
+        mov output, edx;
+    }
+    return output;
+}
+#else
+#warning using generic count leading zeroes. You may wish to write one for your CPU / compiler
+static int count_leading_zeros(int input)
+{
+    int output = 0;
+    int curbyte = 0;
+
+    curbyte = input >> 24;
+    if (curbyte) goto found;
+    output += 8;
+
+    curbyte = input >> 16;
+    if (curbyte & 0xff) goto found;
+    output += 8;
+
+    curbyte = input >> 8;
+    if (curbyte & 0xff) goto found;
+    output += 8;
+
+    curbyte = input;
+    if (curbyte & 0xff) goto found;
+    output += 8;
+
+    return output;
+
+found:
+    if (!(curbyte & 0xf0))
+    {
+        output += 4;
+    }
+    else
+        curbyte >>= 4;
+
+    if (curbyte & 0x8)
+        return output;
+    if (curbyte & 0x4)
+        return output + 1;
+    if (curbyte & 0x2)
+        return output + 2;
+    if (curbyte & 0x1)
+        return output + 3;
+
+    /* shouldn't get here: */
+    return output + 4;
+}
+#endif
+
+#define RICE_THRESHOLD 8 // maximum number of bits for a rice prefix.
+
+int32_t entropy_decode_value(alac_file* alac,
+                                                        int readSampleSize,
+                                                        int k,
+                                                        int rice_kmodifier_mask)
+{
+       int32_t x = 0; // decoded value
+       
+       // read x, number of 1s before 0 represent the rice value.
+       while (x <= RICE_THRESHOLD && readbit(alac))
+       {
+               x++;
+       }
+       
+       if (x > RICE_THRESHOLD)
+       {
+               // read the number from the bit stream (raw value)
+               int32_t value;
+               
+               value = readbits(alac, readSampleSize);
+               
+               // mask value
+               value &= (((uint32_t)0xffffffff) >> (32 - readSampleSize));
+               
+               x = value;
+       }
+       else
+       {
+               if (k != 1)
+               {
+                       int extraBits = readbits(alac, k);
+                       
+                       // x = x * (2^k - 1)
+                       x *= (((1 << k) - 1) & rice_kmodifier_mask);
+                       
+                       if (extraBits > 1)
+                               x += extraBits - 1;
+                       else
+                               unreadbits(alac, 1);
+               }
+       }
+       
+       return x;
+}
+
+void entropy_rice_decode(alac_file* alac,
+                                                int32_t* outputBuffer,
+                                                int outputSize,
+                                                int readSampleSize,
+                                                int rice_initialhistory,
+                                                int rice_kmodifier,
+                                                int rice_historymult,
+                                                int rice_kmodifier_mask)
+{
+       int                             outputCount;
+       int                             history = rice_initialhistory;
+       int                             signModifier = 0;
+       
+       for (outputCount = 0; outputCount < outputSize; outputCount++)
+       {
+               int32_t         decodedValue;
+               int32_t         finalValue;
+               int32_t         k;
+               
+               k = 31 - rice_kmodifier - count_leading_zeros((history >> 9) + 3);
+               
+               if (k < 0) k += rice_kmodifier;
+               else k = rice_kmodifier;
+               
+               // note: don't use rice_kmodifier_mask here (set mask to 0xFFFFFFFF)
+               decodedValue = entropy_decode_value(alac, readSampleSize, k, 0xFFFFFFFF);
+               
+               decodedValue += signModifier;
+               finalValue = (decodedValue + 1) / 2; // inc by 1 and shift out sign bit
+               if (decodedValue & 1) // the sign is stored in the low bit
+                       finalValue *= -1;
+               
+               outputBuffer[outputCount] = finalValue;
+               
+               signModifier = 0;
+               
+               // update history
+               history += (decodedValue * rice_historymult)
+                               - ((history * rice_historymult) >> 9);
+               
+               if (decodedValue > 0xFFFF)
+                       history = 0xFFFF;
+               
+               // special case, for compressed blocks of 0
+               if ((history < 128) && (outputCount + 1 < outputSize))
+               {
+                       int32_t         blockSize;
+                       
+                       signModifier = 1;
+                       
+                       k = count_leading_zeros(history) + ((history + 16) / 64) - 24;
+                       
+                       // note: blockSize is always 16bit
+                       blockSize = entropy_decode_value(alac, 16, k, rice_kmodifier_mask);
+                       
+                       // got blockSize 0s
+                       if (blockSize > 0)
+                       {
+                               memset(&outputBuffer[outputCount + 1], 0, blockSize * sizeof(*outputBuffer));
+                               outputCount += blockSize;
+                       }
+                       
+                       if (blockSize > 0xFFFF)
+                               signModifier = 0;
+                       
+                       history = 0;
+               }
+       }
+}
+
+#define SIGN_EXTENDED32(val, bits) ((val << (32 - bits)) >> (32 - bits))
+
+#define SIGN_ONLY(v) \
+                     ((v < 0) ? (-1) : \
+                                ((v > 0) ? (1) : \
+                                           (0)))
+
+static void predictor_decompress_fir_adapt(int32_t *error_buffer,
+                                           int32_t *buffer_out,
+                                           int output_size,
+                                           int readsamplesize,
+                                           int16_t *predictor_coef_table,
+                                           int predictor_coef_num,
+                                           int predictor_quantitization)
+{
+    int i;
+
+    /* first sample always copies */
+    *buffer_out = *error_buffer;
+
+    if (!predictor_coef_num)
+    {
+        if (output_size <= 1) return;
+        memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
+        return;
+    }
+
+    if (predictor_coef_num == 0x1f) /* 11111 - max value of predictor_coef_num */
+    { /* second-best case scenario for fir decompression,
+       * error describes a small difference from the previous sample only
+       */
+        if (output_size <= 1) return;
+        for (i = 0; i < output_size - 1; i++)
+        {
+            int32_t prev_value;
+            int32_t error_value;
+
+            prev_value = buffer_out[i];
+            error_value = error_buffer[i+1];
+            buffer_out[i+1] = SIGN_EXTENDED32((prev_value + error_value), readsamplesize);
+        }
+        return;
+    }
+
+    /* read warm-up samples */
+    if (predictor_coef_num > 0)
+    {
+        int i;
+        for (i = 0; i < predictor_coef_num; i++)
+        {
+            int32_t val;
+
+            val = buffer_out[i] + error_buffer[i+1];
+
+            val = SIGN_EXTENDED32(val, readsamplesize);
+
+            buffer_out[i+1] = val;
+        }
+    }
+
+#if 0
+    /* 4 and 8 are very common cases (the only ones i've seen). these
+     * should be unrolled and optimised
+     */
+    if (predictor_coef_num == 4)
+    {
+        /* FIXME: optimised general case */
+        return;
+    }
+
+    if (predictor_coef_table == 8)
+    {
+        /* FIXME: optimised general case */
+        return;
+    }
+#endif
+
+
+    /* general case */
+    if (predictor_coef_num > 0)
+    {
+        for (i = predictor_coef_num + 1;
+             i < output_size;
+             i++)
+        {
+            int j;
+            int sum = 0;
+            int outval;
+            int error_val = error_buffer[i];
+
+            for (j = 0; j < predictor_coef_num; j++)
+            {
+                sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
+                       predictor_coef_table[j];
+            }
+
+            outval = (1 << (predictor_quantitization-1)) + sum;
+            outval = outval >> predictor_quantitization;
+            outval = outval + buffer_out[0] + error_val;
+            outval = SIGN_EXTENDED32(outval, readsamplesize);
+
+            buffer_out[predictor_coef_num+1] = outval;
+
+            if (error_val > 0)
+            {
+                int predictor_num = predictor_coef_num - 1;
+
+                while (predictor_num >= 0 && error_val > 0)
+                {
+                    int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
+                    int sign = SIGN_ONLY(val);
+
+                    predictor_coef_table[predictor_num] -= sign;
+
+                    val *= sign; /* absolute value */
+
+                    error_val -= ((val >> predictor_quantitization) *
+                                  (predictor_coef_num - predictor_num));
+
+                    predictor_num--;
+                }
+            }
+            else if (error_val < 0)
+            {
+                int predictor_num = predictor_coef_num - 1;
+
+                while (predictor_num >= 0 && error_val < 0)
+                {
+                    int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
+                    int sign = - SIGN_ONLY(val);
+
+                    predictor_coef_table[predictor_num] -= sign;
+
+                    val *= sign; /* neg value */
+
+                    error_val -= ((val >> predictor_quantitization) *
+                                  (predictor_coef_num - predictor_num));
+
+                    predictor_num--;
+                }
+            }
+
+            buffer_out++;
+        }
+    }
+}
+
+void deinterlace_16(int32_t *buffer_a, int32_t *buffer_b,
+                    int16_t *buffer_out,
+                    int numchannels, int numsamples,
+                    uint8_t interlacing_shift,
+                    uint8_t interlacing_leftweight)
+{
+    int i;
+    if (numsamples <= 0) return;
+
+    /* weighted interlacing */
+    if (interlacing_leftweight)
+    {
+        for (i = 0; i < numsamples; i++)
+        {
+            int32_t difference, midright;
+            int16_t left;
+            int16_t right;
+
+            midright = buffer_a[i];
+            difference = buffer_b[i];
+
+
+            right = midright - ((difference * interlacing_leftweight) >> interlacing_shift);
+            left = right + difference;
+
+            /* output is always little endian */
+            if (host_bigendian)
+            {
+                _Swap16(left);
+                _Swap16(right);
+            }
+
+            buffer_out[i*numchannels] = left;
+            buffer_out[i*numchannels + 1] = right;
+        }
+
+        return;
+    }
+
+    /* otherwise basic interlacing took place */
+    for (i = 0; i < numsamples; i++)
+    {
+        int16_t left, right;
+
+        left = buffer_a[i];
+        right = buffer_b[i];
+
+        /* output is always little endian */
+        if (host_bigendian)
+        {
+            _Swap16(left);
+            _Swap16(right);
+        }
+
+        buffer_out[i*numchannels] = left;
+        buffer_out[i*numchannels + 1] = right;
+    }
+}
+
+void deinterlace_24(int32_t *buffer_a, int32_t *buffer_b,
+                                       int uncompressed_bytes,
+                                       int32_t *uncompressed_bytes_buffer_a, int32_t *uncompressed_bytes_buffer_b,
+                    void *buffer_out,
+                    int numchannels, int numsamples,
+                    uint8_t interlacing_shift,
+                    uint8_t interlacing_leftweight)
+{
+       int i;
+    if (numsamples <= 0) return;
+       
+    /* weighted interlacing */
+    if (interlacing_leftweight)
+    {
+        for (i = 0; i < numsamples; i++)
+        {
+            int32_t difference, midright;
+            int32_t left;
+            int32_t right;
+                       
+            midright = buffer_a[i];
+            difference = buffer_b[i];
+                       
+            right = midright - ((difference * interlacing_leftweight) >> interlacing_shift);
+            left = right + difference;
+                       
+                       if (uncompressed_bytes)
+                       {
+                               uint32_t mask = ~(0xFFFFFFFF << (uncompressed_bytes * 8));
+                               left <<= (uncompressed_bytes * 8);
+                               right <<= (uncompressed_bytes * 8);
+                               
+                               left |= uncompressed_bytes_buffer_a[i] & mask;
+                               right |= uncompressed_bytes_buffer_b[i] & mask;
+                       }
+                       
+                       ((uint8_t*)buffer_out)[i * numchannels * 3] = (left) & 0xFF;
+                       ((uint8_t*)buffer_out)[i * numchannels * 3 + 1] = (left >> 8) & 0xFF;
+                       ((uint8_t*)buffer_out)[i * numchannels * 3 + 2] = (left >> 16) & 0xFF;
+                       
+                       ((uint8_t*)buffer_out)[i * numchannels * 3 + 3] = (right) & 0xFF;
+                       ((uint8_t*)buffer_out)[i * numchannels * 3 + 4] = (right >> 8) & 0xFF;
+                       ((uint8_t*)buffer_out)[i * numchannels * 3 + 5] = (right >> 16) & 0xFF;
+        }
+               
+        return;
+    }
+       
+    /* otherwise basic interlacing took place */
+    for (i = 0; i < numsamples; i++)
+    {
+        int32_t left, right;
+               
+        left = buffer_a[i];
+        right = buffer_b[i];
+               
+               if (uncompressed_bytes)
+               {
+                       uint32_t mask = ~(0xFFFFFFFF << (uncompressed_bytes * 8));
+                       left <<= (uncompressed_bytes * 8);
+                       right <<= (uncompressed_bytes * 8);
+                       
+                       left |= uncompressed_bytes_buffer_a[i] & mask;
+                       right |= uncompressed_bytes_buffer_b[i] & mask;
+               }
+               
+               ((uint8_t*)buffer_out)[i * numchannels * 3] = (left) & 0xFF;
+               ((uint8_t*)buffer_out)[i * numchannels * 3 + 1] = (left >> 8) & 0xFF;
+               ((uint8_t*)buffer_out)[i * numchannels * 3 + 2] = (left >> 16) & 0xFF;
+               
+               ((uint8_t*)buffer_out)[i * numchannels * 3 + 3] = (right) & 0xFF;
+               ((uint8_t*)buffer_out)[i * numchannels * 3 + 4] = (right >> 8) & 0xFF;
+               ((uint8_t*)buffer_out)[i * numchannels * 3 + 5] = (right >> 16) & 0xFF;
+               
+    }
+       
+}
+
+void decode_frame(alac_file *alac,
+                  unsigned char *inbuffer,
+                  void *outbuffer, int *outputsize)
+{
+    int channels;
+    int32_t outputsamples = alac->setinfo_max_samples_per_frame;
+
+    /* setup the stream */
+    alac->input_buffer = inbuffer;
+    alac->input_buffer_bitaccumulator = 0;
+
+    channels = readbits(alac, 3);
+
+    *outputsize = outputsamples * alac->bytespersample;
+
+    switch(channels)
+    {
+    case 0: /* 1 channel */
+    {
+        int hassize;
+        int isnotcompressed;
+        int readsamplesize;
+
+        int uncompressed_bytes;
+        int ricemodifier;
+
+        /* 2^result = something to do with output waiting.
+         * perhaps matters if we read > 1 frame in a pass?
+         */
+        readbits(alac, 4);
+
+        readbits(alac, 12); /* unknown, skip 12 bits */
+
+        hassize = readbits(alac, 1); /* the output sample size is stored soon */
+
+        uncompressed_bytes = readbits(alac, 2); /* number of bytes in the (compressed) stream that are not compressed */
+
+        isnotcompressed = readbits(alac, 1); /* whether the frame is compressed */
+
+        if (hassize)
+        {
+            /* now read the number of samples,
+             * as a 32bit integer */
+            outputsamples = readbits(alac, 32);
+            *outputsize = outputsamples * alac->bytespersample;
+        }
+
+        readsamplesize = alac->setinfo_sample_size - (uncompressed_bytes * 8);
+
+        if (!isnotcompressed)
+        { /* so it is compressed */
+            int16_t predictor_coef_table[32];
+            int predictor_coef_num;
+            int prediction_type;
+            int prediction_quantitization;
+            int i;
+
+            /* skip 16 bits, not sure what they are. seem to be used in
+             * two channel case */
+            readbits(alac, 8);
+            readbits(alac, 8);
+
+            prediction_type = readbits(alac, 4);
+            prediction_quantitization = readbits(alac, 4);
+
+            ricemodifier = readbits(alac, 3);
+            predictor_coef_num = readbits(alac, 5);
+
+            /* read the predictor table */
+            for (i = 0; i < predictor_coef_num; i++)
+            {
+                predictor_coef_table[i] = (int16_t)readbits(alac, 16);
+            }
+
+            if (uncompressed_bytes)
+            {
+                               int i;
+                               for (i = 0; i < outputsamples; i++)
+                               {
+                                       alac->uncompressed_bytes_buffer_a[i] = readbits(alac, uncompressed_bytes * 8);
+                               }
+            }
+
+            entropy_rice_decode(alac,
+                                                               alac->predicterror_buffer_a,
+                                                               outputsamples,
+                                                               readsamplesize,
+                                                               alac->setinfo_rice_initialhistory,
+                                                               alac->setinfo_rice_kmodifier,
+                                                               ricemodifier * alac->setinfo_rice_historymult / 4,
+                                                               (1 << alac->setinfo_rice_kmodifier) - 1);
+
+            if (prediction_type == 0)
+            { /* adaptive fir */
+                predictor_decompress_fir_adapt(alac->predicterror_buffer_a,
+                                               alac->outputsamples_buffer_a,
+                                               outputsamples,
+                                               readsamplesize,
+                                               predictor_coef_table,
+                                               predictor_coef_num,
+                                               prediction_quantitization);
+            }
+            else
+            {
+                fprintf(stderr, "FIXME: unhandled predicition type: %i\n", prediction_type);
+                /* i think the only other prediction type (or perhaps this is just a
+                 * boolean?) runs adaptive fir twice.. like:
+                 * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
+                 * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
+                 * little strange..
+                 */
+            }
+
+        }
+        else
+        { /* not compressed, easy case */
+            if (alac->setinfo_sample_size <= 16)
+            {
+                int i;
+                for (i = 0; i < outputsamples; i++)
+                {
+                    int32_t audiobits = readbits(alac, alac->setinfo_sample_size);
+
+                    audiobits = SIGN_EXTENDED32(audiobits, alac->setinfo_sample_size);
+
+                    alac->outputsamples_buffer_a[i] = audiobits;
+                }
+            }
+            else
+            {
+                int i;
+                for (i = 0; i < outputsamples; i++)
+                {
+                    int32_t audiobits;
+
+                    audiobits = readbits(alac, 16);
+                    /* special case of sign extension..
+                     * as we'll be ORing the low 16bits into this */
+                    audiobits = audiobits << (alac->setinfo_sample_size - 16);
+                    audiobits |= readbits(alac, alac->setinfo_sample_size - 16);
+                                       audiobits = SignExtend24(audiobits);
+
+                    alac->outputsamples_buffer_a[i] = audiobits;
+                }
+            }
+            uncompressed_bytes = 0; // always 0 for uncompressed
+        }
+
+        switch(alac->setinfo_sample_size)
+        {
+        case 16:
+        {
+            int i;
+            for (i = 0; i < outputsamples; i++)
+            {
+                int16_t sample = alac->outputsamples_buffer_a[i];
+                if (host_bigendian)
+                    _Swap16(sample);
+                ((int16_t*)outbuffer)[i * alac->numchannels] = sample;
+            }
+            break;
+        }
+               case 24:
+               {
+                       int i;
+                       for (i = 0; i < outputsamples; i++)
+                       {
+                               int32_t sample = alac->outputsamples_buffer_a[i];
+                               
+                               if (uncompressed_bytes)
+                               {
+                                       uint32_t mask;
+                                       sample = sample << (uncompressed_bytes * 8);
+                                       mask = ~(0xFFFFFFFF << (uncompressed_bytes * 8));
+                                       sample |= alac->uncompressed_bytes_buffer_a[i] & mask;
+                               }
+                               
+                               ((uint8_t*)outbuffer)[i * alac->numchannels * 3] = (sample) & 0xFF;
+                               ((uint8_t*)outbuffer)[i * alac->numchannels * 3 + 1] = (sample >> 8) & 0xFF;
+                               ((uint8_t*)outbuffer)[i * alac->numchannels * 3 + 2] = (sample >> 16) & 0xFF;
+                       }
+                       break;
+               }
+        case 20:
+        case 32:
+            fprintf(stderr, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
+            break;
+        default:
+            break;
+        }
+        break;
+    }
+    case 1: /* 2 channels */
+    {
+        int hassize;
+        int isnotcompressed;
+        int readsamplesize;
+
+        int uncompressed_bytes;
+
+        uint8_t interlacing_shift;
+        uint8_t interlacing_leftweight;
+
+        /* 2^result = something to do with output waiting.
+         * perhaps matters if we read > 1 frame in a pass?
+         */
+        readbits(alac, 4);
+
+        readbits(alac, 12); /* unknown, skip 12 bits */
+
+        hassize = readbits(alac, 1); /* the output sample size is stored soon */
+
+        uncompressed_bytes = readbits(alac, 2); /* the number of bytes in the (compressed) stream that are not compressed */
+
+        isnotcompressed = readbits(alac, 1); /* whether the frame is compressed */
+
+        if (hassize)
+        {
+            /* now read the number of samples,
+             * as a 32bit integer */
+            outputsamples = readbits(alac, 32);
+            *outputsize = outputsamples * alac->bytespersample;
+        }
+
+        readsamplesize = alac->setinfo_sample_size - (uncompressed_bytes * 8) + 1;
+
+        if (!isnotcompressed)
+        { /* compressed */
+            int16_t predictor_coef_table_a[32];
+            int predictor_coef_num_a;
+            int prediction_type_a;
+            int prediction_quantitization_a;
+            int ricemodifier_a;
+
+            int16_t predictor_coef_table_b[32];
+            int predictor_coef_num_b;
+            int prediction_type_b;
+            int prediction_quantitization_b;
+            int ricemodifier_b;
+
+            int i;
+
+            interlacing_shift = readbits(alac, 8);
+            interlacing_leftweight = readbits(alac, 8);
+
+            /******** channel 1 ***********/
+            prediction_type_a = readbits(alac, 4);
+            prediction_quantitization_a = readbits(alac, 4);
+
+            ricemodifier_a = readbits(alac, 3);
+            predictor_coef_num_a = readbits(alac, 5);
+
+            /* read the predictor table */
+            for (i = 0; i < predictor_coef_num_a; i++)
+            {
+                predictor_coef_table_a[i] = (int16_t)readbits(alac, 16);
+            }
+
+            /******** channel 2 *********/
+            prediction_type_b = readbits(alac, 4);
+            prediction_quantitization_b = readbits(alac, 4);
+
+            ricemodifier_b = readbits(alac, 3);
+            predictor_coef_num_b = readbits(alac, 5);
+
+            /* read the predictor table */
+            for (i = 0; i < predictor_coef_num_b; i++)
+            {
+                predictor_coef_table_b[i] = (int16_t)readbits(alac, 16);
+            }
+
+            /*********************/
+            if (uncompressed_bytes)
+            { /* see mono case */
+                               int i;
+                               for (i = 0; i < outputsamples; i++)
+                               {
+                                       alac->uncompressed_bytes_buffer_a[i] = readbits(alac, uncompressed_bytes * 8);
+                                       alac->uncompressed_bytes_buffer_b[i] = readbits(alac, uncompressed_bytes * 8);
+                               }
+            }
+
+            /* channel 1 */
+            entropy_rice_decode(alac,
+                                                               alac->predicterror_buffer_a,
+                                                               outputsamples,
+                                                               readsamplesize,
+                                                               alac->setinfo_rice_initialhistory,
+                                                               alac->setinfo_rice_kmodifier,
+                                                               ricemodifier_a * alac->setinfo_rice_historymult / 4,
+                                                               (1 << alac->setinfo_rice_kmodifier) - 1);
+
+            if (prediction_type_a == 0)
+            { /* adaptive fir */
+                predictor_decompress_fir_adapt(alac->predicterror_buffer_a,
+                                               alac->outputsamples_buffer_a,
+                                               outputsamples,
+                                               readsamplesize,
+                                               predictor_coef_table_a,
+                                               predictor_coef_num_a,
+                                               prediction_quantitization_a);
+            }
+            else
+            { /* see mono case */
+                fprintf(stderr, "FIXME: unhandled predicition type: %i\n", prediction_type_a);
+            }
+
+            /* channel 2 */
+            entropy_rice_decode(alac,
+                                                               alac->predicterror_buffer_b,
+                                                               outputsamples,
+                                                               readsamplesize,
+                                                               alac->setinfo_rice_initialhistory,
+                                                               alac->setinfo_rice_kmodifier,
+                                                               ricemodifier_b * alac->setinfo_rice_historymult / 4,
+                                                               (1 << alac->setinfo_rice_kmodifier) - 1);
+
+            if (prediction_type_b == 0)
+            { /* adaptive fir */
+                predictor_decompress_fir_adapt(alac->predicterror_buffer_b,
+                                               alac->outputsamples_buffer_b,
+                                               outputsamples,
+                                               readsamplesize,
+                                               predictor_coef_table_b,
+                                               predictor_coef_num_b,
+                                               prediction_quantitization_b);
+            }
+            else
+            {
+                fprintf(stderr, "FIXME: unhandled predicition type: %i\n", prediction_type_b);
+            }
+        }
+        else
+        { /* not compressed, easy case */
+            if (alac->setinfo_sample_size <= 16)
+            {
+                int i;
+                for (i = 0; i < outputsamples; i++)
+                {
+                    int32_t audiobits_a, audiobits_b;
+
+                    audiobits_a = readbits(alac, alac->setinfo_sample_size);
+                    audiobits_b = readbits(alac, alac->setinfo_sample_size);
+
+                    audiobits_a = SIGN_EXTENDED32(audiobits_a, alac->setinfo_sample_size);
+                    audiobits_b = SIGN_EXTENDED32(audiobits_b, alac->setinfo_sample_size);
+
+                    alac->outputsamples_buffer_a[i] = audiobits_a;
+                    alac->outputsamples_buffer_b[i] = audiobits_b;
+                }
+            }
+            else
+            {
+                int i;
+                for (i = 0; i < outputsamples; i++)
+                {
+                    int32_t audiobits_a, audiobits_b;
+
+                    audiobits_a = readbits(alac, 16);
+                    audiobits_a = audiobits_a << (alac->setinfo_sample_size - 16);
+                    audiobits_a |= readbits(alac, alac->setinfo_sample_size - 16);
+                                       audiobits_a = SignExtend24(audiobits_a);
+
+                    audiobits_b = readbits(alac, 16);
+                    audiobits_b = audiobits_b << (alac->setinfo_sample_size - 16);
+                    audiobits_b |= readbits(alac, alac->setinfo_sample_size - 16);
+                                       audiobits_b = SignExtend24(audiobits_b);
+                                       
+                    alac->outputsamples_buffer_a[i] = audiobits_a;
+                    alac->outputsamples_buffer_b[i] = audiobits_b;
+                }
+            }
+            uncompressed_bytes = 0; // always 0 for uncompressed
+            interlacing_shift = 0;
+            interlacing_leftweight = 0;
+        }
+
+        switch(alac->setinfo_sample_size)
+        {
+        case 16:
+        {
+            deinterlace_16(alac->outputsamples_buffer_a,
+                           alac->outputsamples_buffer_b,
+                           (int16_t*)outbuffer,
+                           alac->numchannels,
+                           outputsamples,
+                           interlacing_shift,
+                           interlacing_leftweight);
+            break;
+        }
+               case 24:
+               {
+                       deinterlace_24(alac->outputsamples_buffer_a,
+                           alac->outputsamples_buffer_b,
+                                                  uncompressed_bytes,
+                                                  alac->uncompressed_bytes_buffer_a,
+                                                  alac->uncompressed_bytes_buffer_b,
+                           (int16_t*)outbuffer,
+                           alac->numchannels,
+                           outputsamples,
+                           interlacing_shift,
+                           interlacing_leftweight);                    
+                       break;
+               }
+        case 20:
+        case 32:
+            fprintf(stderr, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
+            break;
+        default:
+            break;
+        }
+
+        break;
+    }
+    }
+}
+
+alac_file *create_alac(int samplesize, int numchannels)
+{
+    alac_file *newfile = malloc(sizeof(alac_file));
+
+    newfile->samplesize = samplesize;
+    newfile->numchannels = numchannels;
+    newfile->bytespersample = (samplesize / 8) * numchannels;
+
+    return newfile;
+}
+
diff --git a/src/alac/alac.h b/src/alac/alac.h
new file mode 100644 (file)
index 0000000..23dbc52
--- /dev/null
@@ -0,0 +1,13 @@
+#ifndef __ALAC__DECOMP_H
+#define __ALAC__DECOMP_H
+
+typedef struct alac_file alac_file;
+
+alac_file *create_alac(int samplesize, int numchannels);
+void decode_frame(alac_file *alac,
+                  unsigned char *inbuffer,
+                  void *outbuffer, int *outputsize);
+void alac_set_info(alac_file *alac, char *inputbuffer);
+
+#endif /* __ALAC__DECOMP_H */
+
diff --git a/src/alac/stdint_win.h b/src/alac/stdint_win.h
new file mode 100644 (file)
index 0000000..a580eb7
--- /dev/null
@@ -0,0 +1,14 @@
+\r
+#ifndef ALAC_STDINT_WIN_H__\r
+#define ALAC_STDINT_WIN_H__\r
+\r
+typedef signed char         int8_t;\r
+typedef signed short        int16_t;\r
+typedef signed int          int32_t;\r
+typedef signed __int64      int64_t;\r
+typedef unsigned char       uint8_t;\r
+typedef unsigned short      uint16_t;\r
+typedef unsigned int        uint32_t;\r
+typedef unsigned __int64    uint64_t;\r
+\r
+#endif // ALAC_STDINT_WIN_H__
\ No newline at end of file
diff --git a/src/base64.c b/src/base64.c
new file mode 100644 (file)
index 0000000..786e445
--- /dev/null
@@ -0,0 +1,268 @@
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+
+#include "base64.h"
+
+#define DEFAULT_CHARLIST "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
+
+#define BASE64_PADDING 0x40
+#define BASE64_INVALID 0x80
+
+struct base64_s {
+       char charlist[65];
+       char charmap[256];
+       int charmap_inited;
+
+       int use_padding;
+       int skip_spaces;
+};
+
+static base64_t default_base64 =
+       { .charlist = DEFAULT_CHARLIST,
+         .use_padding = 1 };
+
+static void
+initialize_charmap(base64_t *base64)
+{
+       int i;
+
+       memset(base64->charmap, BASE64_INVALID, sizeof(base64->charmap));
+       for (i=0; i<64; i++) {
+               base64->charmap[(int)base64->charlist[i]] = i;
+       }
+       base64->charmap['='] = BASE64_PADDING;
+       base64->charmap_inited = 1;
+}
+
+base64_t *
+base64_init(const char *charlist, int use_padding, int skip_spaces)
+{
+       base64_t *base64;
+       int i;
+
+       if (!charlist) {
+               charlist = DEFAULT_CHARLIST;    
+       }
+       if (strlen(charlist) != 64) {
+               return NULL;
+       }
+       for (i=0; i<64; i++) {
+               switch (charlist[i]) {
+               case '\r':
+               case '\n':
+               case '=':
+                       return NULL;
+               }
+       }
+
+       base64 = calloc(1, sizeof(base64_t));
+       if (!base64) {
+               return NULL;
+       }
+       strncpy(base64->charlist, charlist, sizeof(base64->charlist)-1);
+       base64->use_padding = use_padding;
+       base64->skip_spaces = skip_spaces;
+
+       return base64;
+}
+
+void
+base64_destroy(base64_t *base64)
+{
+       free(base64);
+}
+
+int
+base64_encoded_length(base64_t *base64, int srclen)
+{
+       if (!base64) {
+               base64 = &default_base64;
+       }
+
+       if (base64->use_padding) {
+               return ((srclen+2)/3*4)+1;
+       } else {
+               int strlen = 0;
+               switch (srclen % 3) {
+               case 2:
+                       strlen += 1;
+               case 1:
+                       strlen += 2; 
+               default:
+                       strlen += srclen/3*4;
+                       break;
+               }
+               return strlen+1;
+       }
+}
+
+int
+base64_encode(base64_t *base64, char *dst, const unsigned char *src, int srclen)
+{
+       int src_idx, dst_idx;
+       int residue;
+
+       if (!base64) {
+               base64 = &default_base64;
+       }
+
+       residue = 0;
+       for (src_idx=dst_idx=0; src_idx<srclen; src_idx++) {
+               residue |= src[src_idx];
+
+               switch (src_idx%3) {
+               case 0:
+                       dst[dst_idx++] = base64->charlist[(residue>>2)%64];
+                       residue &= 0x03;
+                       break;
+               case 1:
+                       dst[dst_idx++] = base64->charlist[residue>>4];
+                       residue &= 0x0f;
+                       break;
+               case 2:
+                       dst[dst_idx++] = base64->charlist[residue>>6];
+                       dst[dst_idx++] = base64->charlist[residue&0x3f];
+                       residue = 0;
+                       break;
+               }
+               residue <<= 8;
+       }
+
+       /* Add padding */
+       if (src_idx%3 == 1) {
+               dst[dst_idx++] = base64->charlist[residue>>4];
+               if (base64->use_padding) {
+                       dst[dst_idx++] = '=';
+                       dst[dst_idx++] = '=';
+               }
+       } else if (src_idx%3 == 2) {
+               dst[dst_idx++] = base64->charlist[residue>>6];
+               if (base64->use_padding) {
+                       dst[dst_idx++] = '=';
+               }
+       }
+       dst[dst_idx] = '\0';
+       return dst_idx;
+}
+
+int
+base64_decode(base64_t *base64, unsigned char **dst, const char *src, int srclen)
+{
+       char *inbuf;
+       int inbuflen;
+       unsigned char *outbuf;
+       int outbuflen;
+       char *srcptr;
+       int index;
+
+       if (!base64) {
+               base64 = &default_base64;
+       }
+       if (!base64->charmap_inited) {
+               initialize_charmap(base64);
+       }
+
+       inbuf = malloc(srclen+4);
+       if (!inbuf) {
+               return -1;
+       }
+       memcpy(inbuf, src, srclen);
+       inbuf[srclen] = '\0';
+
+       /* Remove all whitespaces from inbuf */
+       if (base64->skip_spaces) {
+               int i, inbuflen = strlen(inbuf);
+               for (i=0; i<inbuflen; i++) {
+                       if (inbuf[i] == '\0') {
+                               break;
+                       } else if (isspace(inbuf[i])) {
+                               memmove(inbuf+i, inbuf+i+1, inbuflen-i);
+                               inbuflen -= 1;
+                               i -= 1;
+                       }
+               }
+       }
+
+       /* Add padding to inbuf if required */
+       inbuflen = strlen(inbuf);
+       if (!base64->use_padding) {
+               if (inbuflen%4 == 1) {
+                       free(inbuf);
+                       return -2;
+               }
+               if (inbuflen%4 == 2) {
+                       inbuf[inbuflen] = '=';
+                       inbuf[inbuflen+1] = '=';
+                       inbuf[inbuflen+2] = '\0';
+                       inbuflen += 2;
+               } else if (inbuflen%4 == 3) {
+                       inbuf[inbuflen] = '=';
+                       inbuf[inbuflen+1] = '\0';
+                       inbuflen += 1;
+               }
+       }
+
+       /* Make sure data is divisible by 4 */
+       if (inbuflen%4 != 0) {
+               free(inbuf);
+               return -3;
+       }
+
+       /* Calculate the output length without padding */
+       outbuflen = inbuflen/4*3;
+       if (inbuflen >= 4 && inbuf[inbuflen-1] == '=') {
+               outbuflen -= 1;
+               if (inbuf[inbuflen-2] == '=') {
+                       outbuflen -= 1;
+               }
+       }
+
+       /* Allocate buffer for outputting data */
+       outbuf = malloc(outbuflen);
+       if (!outbuf) {
+               free(inbuf);
+               return -4;
+       }
+
+       index = 0;
+       srcptr = inbuf;
+       while (*srcptr) {
+               unsigned char a = base64->charmap[(unsigned char)*(srcptr++)];
+               unsigned char b = base64->charmap[(unsigned char)*(srcptr++)];
+               unsigned char c = base64->charmap[(unsigned char)*(srcptr++)];
+               unsigned char d = base64->charmap[(unsigned char)*(srcptr++)];
+
+               if (a == BASE64_INVALID || b == BASE64_INVALID ||
+                   c == BASE64_INVALID || d == BASE64_INVALID) {
+                       return -5;
+               }
+               if (a == BASE64_PADDING || b == BASE64_PADDING) {
+                       return -6;
+               }
+
+               /* Update the first byte */
+               outbuf[index++] = (a << 2) | ((b & 0x30) >> 4);
+
+               /* Update the second byte */
+               if (c == BASE64_PADDING) {
+                       break;
+               }
+               outbuf[index++] = ((b & 0x0f) << 4) | ((c & 0x3c) >> 2);
+
+               /* Update the third byte */
+               if (d == BASE64_PADDING) {
+                       break;
+               }
+               outbuf[index++] = ((c & 0x03) << 6) | d;
+       }
+       if (index != outbuflen) {
+               free(inbuf);
+               free(outbuf);
+               return -7;
+       }
+
+       free(inbuf);
+       *dst = outbuf;
+       return outbuflen;
+}
diff --git a/src/base64.h b/src/base64.h
new file mode 100644 (file)
index 0000000..e362108
--- /dev/null
@@ -0,0 +1,15 @@
+#ifndef BASE64_H
+#define BASE64_H
+
+typedef struct base64_s base64_t;
+
+base64_t *base64_init(const char *charlist, int use_padding, int skip_spaces);
+
+int base64_encoded_length(base64_t *base64, int srclen);
+
+int base64_encode(base64_t *base64, char *dst, const unsigned char *src, int srclen);
+int base64_decode(base64_t *base64, unsigned char **dst, const char *src, int srclen);
+
+void base64_destroy(base64_t *base64);
+
+#endif
diff --git a/src/compat.h b/src/compat.h
new file mode 100644 (file)
index 0000000..4a48e0f
--- /dev/null
@@ -0,0 +1,24 @@
+#ifndef COMPAT_H
+#define COMPAT_H
+
+#if defined(WIN32)
+#include <windows.h>
+#include <ws2tcpip.h>
+#else
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/ioctl.h>
+#include <sys/time.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <unistd.h>
+#include <errno.h>
+#include <netdb.h>
+#include <pthread.h>
+#endif
+
+#include "memalign.h"
+#include "sockets.h"
+#include "threads.h"
+
+#endif
diff --git a/src/crypto/aes.c b/src/crypto/aes.c
new file mode 100644 (file)
index 0000000..9b07e27
--- /dev/null
@@ -0,0 +1,457 @@
+/*
+ * Copyright (c) 2007, Cameron Rich
+ * 
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice, 
+ *   this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice, 
+ *   this list of conditions and the following disclaimer in the documentation 
+ *   and/or other materials provided with the distribution.
+ * * Neither the name of the axTLS project nor the names of its contributors 
+ *   may be used to endorse or promote products derived from this software 
+ *   without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * AES implementation - this is a small code version. There are much faster
+ * versions around but they are much larger in size (i.e. they use large 
+ * submix tables).
+ */
+
+#include <string.h>
+#include "os_port.h"
+#include "crypto.h"
+
+/* all commented out in skeleton mode */
+#ifndef CONFIG_SSL_SKELETON_MODE
+
+#define rot1(x) (((x) << 24) | ((x) >> 8))
+#define rot2(x) (((x) << 16) | ((x) >> 16))
+#define rot3(x) (((x) <<  8) | ((x) >> 24))
+
+/* 
+ * This cute trick does 4 'mul by two' at once.  Stolen from
+ * Dr B. R. Gladman <brg@gladman.uk.net> but I'm sure the u-(u>>7) is
+ * a standard graphics trick
+ * The key to this is that we need to xor with 0x1b if the top bit is set.
+ * a 1xxx xxxx   0xxx 0xxx First we mask the 7bit,
+ * b 1000 0000   0000 0000 then we shift right by 7 putting the 7bit in 0bit,
+ * c 0000 0001   0000 0000 we then subtract (c) from (b)
+ * d 0111 1111   0000 0000 and now we and with our mask
+ * e 0001 1011   0000 0000
+ */
+#define mt  0x80808080
+#define ml  0x7f7f7f7f
+#define mh  0xfefefefe
+#define mm  0x1b1b1b1b
+#define mul2(x,t)      ((t)=((x)&mt), \
+                       ((((x)+(x))&mh)^(((t)-((t)>>7))&mm)))
+
+#define inv_mix_col(x,f2,f4,f8,f9) (\
+                       (f2)=mul2(x,f2), \
+                       (f4)=mul2(f2,f4), \
+                       (f8)=mul2(f4,f8), \
+                       (f9)=(x)^(f8), \
+                       (f8)=((f2)^(f4)^(f8)), \
+                       (f2)^=(f9), \
+                       (f4)^=(f9), \
+                       (f8)^=rot3(f2), \
+                       (f8)^=rot2(f4), \
+                       (f8)^rot1(f9))
+
+/*
+ * AES S-box
+ */
+static const uint8_t aes_sbox[256] =
+{
+       0x63,0x7C,0x77,0x7B,0xF2,0x6B,0x6F,0xC5,
+       0x30,0x01,0x67,0x2B,0xFE,0xD7,0xAB,0x76,
+       0xCA,0x82,0xC9,0x7D,0xFA,0x59,0x47,0xF0,
+       0xAD,0xD4,0xA2,0xAF,0x9C,0xA4,0x72,0xC0,
+       0xB7,0xFD,0x93,0x26,0x36,0x3F,0xF7,0xCC,
+       0x34,0xA5,0xE5,0xF1,0x71,0xD8,0x31,0x15,
+       0x04,0xC7,0x23,0xC3,0x18,0x96,0x05,0x9A,
+       0x07,0x12,0x80,0xE2,0xEB,0x27,0xB2,0x75,
+       0x09,0x83,0x2C,0x1A,0x1B,0x6E,0x5A,0xA0,
+       0x52,0x3B,0xD6,0xB3,0x29,0xE3,0x2F,0x84,
+       0x53,0xD1,0x00,0xED,0x20,0xFC,0xB1,0x5B,
+       0x6A,0xCB,0xBE,0x39,0x4A,0x4C,0x58,0xCF,
+       0xD0,0xEF,0xAA,0xFB,0x43,0x4D,0x33,0x85,
+       0x45,0xF9,0x02,0x7F,0x50,0x3C,0x9F,0xA8,
+       0x51,0xA3,0x40,0x8F,0x92,0x9D,0x38,0xF5,
+       0xBC,0xB6,0xDA,0x21,0x10,0xFF,0xF3,0xD2,
+       0xCD,0x0C,0x13,0xEC,0x5F,0x97,0x44,0x17,
+       0xC4,0xA7,0x7E,0x3D,0x64,0x5D,0x19,0x73,
+       0x60,0x81,0x4F,0xDC,0x22,0x2A,0x90,0x88,
+       0x46,0xEE,0xB8,0x14,0xDE,0x5E,0x0B,0xDB,
+       0xE0,0x32,0x3A,0x0A,0x49,0x06,0x24,0x5C,
+       0xC2,0xD3,0xAC,0x62,0x91,0x95,0xE4,0x79,
+       0xE7,0xC8,0x37,0x6D,0x8D,0xD5,0x4E,0xA9,
+       0x6C,0x56,0xF4,0xEA,0x65,0x7A,0xAE,0x08,
+       0xBA,0x78,0x25,0x2E,0x1C,0xA6,0xB4,0xC6,
+       0xE8,0xDD,0x74,0x1F,0x4B,0xBD,0x8B,0x8A,
+       0x70,0x3E,0xB5,0x66,0x48,0x03,0xF6,0x0E,
+       0x61,0x35,0x57,0xB9,0x86,0xC1,0x1D,0x9E,
+       0xE1,0xF8,0x98,0x11,0x69,0xD9,0x8E,0x94,
+       0x9B,0x1E,0x87,0xE9,0xCE,0x55,0x28,0xDF,
+       0x8C,0xA1,0x89,0x0D,0xBF,0xE6,0x42,0x68,
+       0x41,0x99,0x2D,0x0F,0xB0,0x54,0xBB,0x16,
+};
+
+/*
+ * AES is-box
+ */
+static const uint8_t aes_isbox[256] = 
+{
+    0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38,
+    0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb,
+    0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87,
+    0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb,
+    0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d,
+    0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e,
+    0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2,
+    0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25,
+    0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16,
+    0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92,
+    0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda,
+    0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84,
+    0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a,
+    0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06,
+    0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02,
+    0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b,
+    0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea,
+    0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73,
+    0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85,
+    0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e,
+    0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89,
+    0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b,
+    0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20,
+    0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4,
+    0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31,
+    0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f,
+    0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d,
+    0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef,
+    0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0,
+    0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61,
+    0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26,
+    0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d
+};
+
+static const unsigned char Rcon[30]=
+{
+       0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,
+       0x1b,0x36,0x6c,0xd8,0xab,0x4d,0x9a,0x2f,
+       0x5e,0xbc,0x63,0xc6,0x97,0x35,0x6a,0xd4,
+       0xb3,0x7d,0xfa,0xef,0xc5,0x91,
+};
+
+/* ----- static functions ----- */
+static void AES_encrypt(const AES_CTX *ctx, uint32_t *data);
+static void AES_decrypt(const AES_CTX *ctx, uint32_t *data);
+
+/* Perform doubling in Galois Field GF(2^8) using the irreducible polynomial
+   x^8+x^4+x^3+x+1 */
+static unsigned char AES_xtime(uint32_t x)
+{
+       return (x&0x80) ? (x<<1)^0x1b : x<<1;
+}
+
+/**
+ * Set up AES with the key/iv and cipher size.
+ */
+void AES_set_key(AES_CTX *ctx, const uint8_t *key, 
+        const uint8_t *iv, AES_MODE mode)
+{
+    int i, ii;
+    uint32_t *W, tmp, tmp2;
+    const unsigned char *ip;
+    int words;
+
+    switch (mode)
+    {
+        case AES_MODE_128:
+            i = 10;
+            words = 4;
+            break;
+
+        case AES_MODE_256:
+            i = 14;
+            words = 8;
+            break;
+
+        default:        /* fail silently */
+            return;
+    }
+
+    ctx->rounds = i;
+    ctx->key_size = words;
+    W = ctx->ks;
+    for (i = 0; i < words; i+=2)
+    {
+        W[i+0]=        ((uint32_t)key[ 0]<<24)|
+            ((uint32_t)key[ 1]<<16)|
+            ((uint32_t)key[ 2]<< 8)|
+            ((uint32_t)key[ 3]    );
+        W[i+1]=        ((uint32_t)key[ 4]<<24)|
+            ((uint32_t)key[ 5]<<16)|
+            ((uint32_t)key[ 6]<< 8)|
+            ((uint32_t)key[ 7]    );
+        key += 8;
+    }
+
+    ip = Rcon;
+    ii = 4 * (ctx->rounds+1);
+    for (i = words; i<ii; i++)
+    {
+        tmp = W[i-1];
+
+        if ((i % words) == 0)
+        {
+            tmp2 =(uint32_t)aes_sbox[(tmp    )&0xff]<< 8;
+            tmp2|=(uint32_t)aes_sbox[(tmp>> 8)&0xff]<<16;
+            tmp2|=(uint32_t)aes_sbox[(tmp>>16)&0xff]<<24;
+            tmp2|=(uint32_t)aes_sbox[(tmp>>24)     ];
+            tmp=tmp2^(((unsigned int)*ip)<<24);
+            ip++;
+        }
+
+        if ((words == 8) && ((i % words) == 4))
+        {
+            tmp2 =(uint32_t)aes_sbox[(tmp    )&0xff]    ;
+            tmp2|=(uint32_t)aes_sbox[(tmp>> 8)&0xff]<< 8;
+            tmp2|=(uint32_t)aes_sbox[(tmp>>16)&0xff]<<16;
+            tmp2|=(uint32_t)aes_sbox[(tmp>>24)     ]<<24;
+            tmp=tmp2;
+        }
+
+        W[i]=W[i-words]^tmp;
+    }
+
+    /* copy the iv across */
+    memcpy(ctx->iv, iv, 16);
+}
+
+/**
+ * Change a key for decryption.
+ */
+void AES_convert_key(AES_CTX *ctx)
+{
+    int i;
+    uint32_t *k,w,t1,t2,t3,t4;
+
+    k = ctx->ks;
+    k += 4;
+
+    for (i= ctx->rounds*4; i > 4; i--)
+    {
+        w= *k;
+        w = inv_mix_col(w,t1,t2,t3,t4);
+        *k++ =w;
+    }
+}
+
+/**
+ * Encrypt a byte sequence (with a block size 16) using the AES cipher.
+ */
+void AES_cbc_encrypt(AES_CTX *ctx, const uint8_t *msg, uint8_t *out, int length)
+{
+    int i;
+    uint32_t tin[4], tout[4], iv[4];
+
+    memcpy(iv, ctx->iv, AES_IV_SIZE);
+    for (i = 0; i < 4; i++)
+        tout[i] = ntohl(iv[i]);
+
+    for (length -= AES_BLOCKSIZE; length >= 0; length -= AES_BLOCKSIZE)
+    {
+        uint32_t msg_32[4];
+        uint32_t out_32[4];
+        memcpy(msg_32, msg, AES_BLOCKSIZE);
+        msg += AES_BLOCKSIZE;
+
+        for (i = 0; i < 4; i++)
+            tin[i] = ntohl(msg_32[i])^tout[i];
+
+        AES_encrypt(ctx, tin);
+
+        for (i = 0; i < 4; i++)
+        {
+            tout[i] = tin[i]; 
+            out_32[i] = htonl(tout[i]);
+        }
+
+        memcpy(out, out_32, AES_BLOCKSIZE);
+        out += AES_BLOCKSIZE;
+    }
+
+    for (i = 0; i < 4; i++)
+        iv[i] = htonl(tout[i]);
+    memcpy(ctx->iv, iv, AES_IV_SIZE);
+}
+
+/**
+ * Decrypt a byte sequence (with a block size 16) using the AES cipher.
+ */
+void AES_cbc_decrypt(AES_CTX *ctx, const uint8_t *msg, uint8_t *out, int length)
+{
+    int i;
+    uint32_t tin[4], xor[4], tout[4], data[4], iv[4];
+
+    memcpy(iv, ctx->iv, AES_IV_SIZE);
+    for (i = 0; i < 4; i++)
+        xor[i] = ntohl(iv[i]);
+
+    for (length -= 16; length >= 0; length -= 16)
+    {
+        uint32_t msg_32[4];
+        uint32_t out_32[4];
+        memcpy(msg_32, msg, AES_BLOCKSIZE);
+        msg += AES_BLOCKSIZE;
+
+        for (i = 0; i < 4; i++)
+        {
+            tin[i] = ntohl(msg_32[i]);
+            data[i] = tin[i];
+        }
+
+        AES_decrypt(ctx, data);
+
+        for (i = 0; i < 4; i++)
+        {
+            tout[i] = data[i]^xor[i];
+            xor[i] = tin[i];
+            out_32[i] = htonl(tout[i]);
+        }
+
+        memcpy(out, out_32, AES_BLOCKSIZE);
+        out += AES_BLOCKSIZE;
+    }
+
+    for (i = 0; i < 4; i++)
+        iv[i] = htonl(xor[i]);
+    memcpy(ctx->iv, iv, AES_IV_SIZE);
+}
+
+/**
+ * Encrypt a single block (16 bytes) of data
+ */
+static void AES_encrypt(const AES_CTX *ctx, uint32_t *data)
+{
+    /* To make this code smaller, generate the sbox entries on the fly.
+     * This will have a really heavy effect upon performance.
+     */
+    uint32_t tmp[4];
+    uint32_t tmp1, old_a0, a0, a1, a2, a3, row;
+    int curr_rnd;
+    int rounds = ctx->rounds; 
+    const uint32_t *k = ctx->ks;
+
+    /* Pre-round key addition */
+    for (row = 0; row < 4; row++)
+        data[row] ^= *(k++);
+
+    /* Encrypt one block. */
+    for (curr_rnd = 0; curr_rnd < rounds; curr_rnd++)
+    {
+        /* Perform ByteSub and ShiftRow operations together */
+        for (row = 0; row < 4; row++)
+        {
+            a0 = (uint32_t)aes_sbox[(data[row%4]>>24)&0xFF];
+            a1 = (uint32_t)aes_sbox[(data[(row+1)%4]>>16)&0xFF];
+            a2 = (uint32_t)aes_sbox[(data[(row+2)%4]>>8)&0xFF]; 
+            a3 = (uint32_t)aes_sbox[(data[(row+3)%4])&0xFF];
+
+            /* Perform MixColumn iff not last round */
+            if (curr_rnd < (rounds - 1))
+            {
+                tmp1 = a0 ^ a1 ^ a2 ^ a3;
+                old_a0 = a0;
+                a0 ^= tmp1 ^ AES_xtime(a0 ^ a1);
+                a1 ^= tmp1 ^ AES_xtime(a1 ^ a2);
+                a2 ^= tmp1 ^ AES_xtime(a2 ^ a3);
+                a3 ^= tmp1 ^ AES_xtime(a3 ^ old_a0);
+            }
+
+            tmp[row] = ((a0 << 24) | (a1 << 16) | (a2 << 8) | a3);
+        }
+
+        /* KeyAddition - note that it is vital that this loop is separate from
+           the MixColumn operation, which must be atomic...*/ 
+        for (row = 0; row < 4; row++)
+            data[row] = tmp[row] ^ *(k++);
+    }
+}
+
+/**
+ * Decrypt a single block (16 bytes) of data
+ */
+static void AES_decrypt(const AES_CTX *ctx, uint32_t *data)
+{ 
+    uint32_t tmp[4];
+    uint32_t xt0,xt1,xt2,xt3,xt4,xt5,xt6;
+    uint32_t a0, a1, a2, a3, row;
+    int curr_rnd;
+    int rounds = ctx->rounds;
+    const uint32_t *k = ctx->ks + ((rounds+1)*4);
+
+    /* pre-round key addition */
+    for (row=4; row > 0;row--)
+        data[row-1] ^= *(--k);
+
+    /* Decrypt one block */
+    for (curr_rnd = 0; curr_rnd < rounds; curr_rnd++)
+    {
+        /* Perform ByteSub and ShiftRow operations together */
+        for (row = 4; row > 0; row--)
+        {
+            a0 = aes_isbox[(data[(row+3)%4]>>24)&0xFF];
+            a1 = aes_isbox[(data[(row+2)%4]>>16)&0xFF];
+            a2 = aes_isbox[(data[(row+1)%4]>>8)&0xFF];
+            a3 = aes_isbox[(data[row%4])&0xFF];
+
+            /* Perform MixColumn iff not last round */
+            if (curr_rnd<(rounds-1))
+            {
+                /* The MDS cofefficients (0x09, 0x0B, 0x0D, 0x0E)
+                   are quite large compared to encryption; this 
+                   operation slows decryption down noticeably. */
+                xt0 = AES_xtime(a0^a1);
+                xt1 = AES_xtime(a1^a2);
+                xt2 = AES_xtime(a2^a3);
+                xt3 = AES_xtime(a3^a0);
+                xt4 = AES_xtime(xt0^xt1);
+                xt5 = AES_xtime(xt1^xt2);
+                xt6 = AES_xtime(xt4^xt5);
+
+                xt0 ^= a1^a2^a3^xt4^xt6;
+                xt1 ^= a0^a2^a3^xt5^xt6;
+                xt2 ^= a0^a1^a3^xt4^xt6;
+                xt3 ^= a0^a1^a2^xt5^xt6;
+                tmp[row-1] = ((xt0<<24)|(xt1<<16)|(xt2<<8)|xt3);
+            }
+            else
+                tmp[row-1] = ((a0<<24)|(a1<<16)|(a2<<8)|a3);
+        }
+
+        for (row = 4; row > 0; row--)
+            data[row-1] = tmp[row-1] ^ *(--k);
+    }
+}
+
+#endif
diff --git a/src/crypto/bigint.c b/src/crypto/bigint.c
new file mode 100644 (file)
index 0000000..e9ca04c
--- /dev/null
@@ -0,0 +1,1512 @@
+/*
+ * Copyright (c) 2007, Cameron Rich
+ * 
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice, 
+ *   this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice, 
+ *   this list of conditions and the following disclaimer in the documentation 
+ *   and/or other materials provided with the distribution.
+ * * Neither the name of the axTLS project nor the names of its contributors 
+ *   may be used to endorse or promote products derived from this software 
+ *   without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * @defgroup bigint_api Big Integer API
+ * @brief The bigint implementation as used by the axTLS project.
+ *
+ * The bigint library is for RSA encryption/decryption as well as signing.
+ * This code tries to minimise use of malloc/free by maintaining a small 
+ * cache. A bigint context may maintain state by being made "permanent". 
+ * It be be later released with a bi_depermanent() and bi_free() call.
+ *
+ * It supports the following reduction techniques:
+ * - Classical
+ * - Barrett
+ * - Montgomery
+ *
+ * It also implements the following:
+ * - Karatsuba multiplication
+ * - Squaring
+ * - Sliding window exponentiation
+ * - Chinese Remainder Theorem (implemented in rsa.c).
+ *
+ * All the algorithms used are pretty standard, and designed for different
+ * data bus sizes. Negative numbers are not dealt with at all, so a subtraction
+ * may need to be tested for negativity.
+ *
+ * This library steals some ideas from Jef Poskanzer
+ * <http://cs.marlboro.edu/term/cs-fall02/algorithms/crypto/RSA/bigint>
+ * and GMP <http://www.swox.com/gmp>. It gets most of its implementation
+ * detail from "The Handbook of Applied Cryptography"
+ * <http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf>
+ * @{
+ */
+
+#include <stdlib.h>
+#include <limits.h>
+#include <string.h>
+#include <stdio.h>
+#include <time.h>
+#include "os_port.h"
+#include "bigint.h"
+
+#define V1      v->comps[v->size-1]                 /**< v1 for division */
+#define V2      v->comps[v->size-2]                 /**< v2 for division */
+#define U(j)    tmp_u->comps[tmp_u->size-j-1]       /**< uj for division */
+#define Q(j)    quotient->comps[quotient->size-j-1] /**< qj for division */
+
+static bigint *bi_int_multiply(BI_CTX *ctx, bigint *bi, comp i);
+static bigint *bi_int_divide(BI_CTX *ctx, bigint *biR, comp denom);
+static bigint *alloc(BI_CTX *ctx, int size);
+static bigint *trim(bigint *bi);
+static void more_comps(bigint *bi, int n);
+#if defined(CONFIG_BIGINT_KARATSUBA) || defined(CONFIG_BIGINT_BARRETT) || \
+    defined(CONFIG_BIGINT_MONTGOMERY)
+static bigint *comp_right_shift(bigint *biR, int num_shifts);
+static bigint *comp_left_shift(bigint *biR, int num_shifts);
+#endif
+
+#ifdef CONFIG_BIGINT_CHECK_ON
+static void check(const bigint *bi);
+#else
+#define check(A)                /**< disappears in normal production mode */
+#endif
+
+
+/**
+ * @brief Start a new bigint context.
+ * @return A bigint context.
+ */
+BI_CTX *bi_initialize(void)
+{
+    /* calloc() sets everything to zero */
+    BI_CTX *ctx = (BI_CTX *)calloc(1, sizeof(BI_CTX));
+   
+    /* the radix */
+    ctx->bi_radix = alloc(ctx, 2); 
+    ctx->bi_radix->comps[0] = 0;
+    ctx->bi_radix->comps[1] = 1;
+    bi_permanent(ctx->bi_radix);
+    return ctx;
+}
+
+/**
+ * @brief Close the bigint context and free any resources.
+ *
+ * Free up any used memory - a check is done if all objects were not 
+ * properly freed.
+ * @param ctx [in]   The bigint session context.
+ */
+void bi_terminate(BI_CTX *ctx)
+{
+    bi_depermanent(ctx->bi_radix); 
+    bi_free(ctx, ctx->bi_radix);
+
+    if (ctx->active_count != 0)
+    {
+#ifdef CONFIG_SSL_FULL_MODE
+        printf("bi_terminate: there were %d un-freed bigints\n",
+                       ctx->active_count);
+#endif
+        abort();
+    }
+
+    bi_clear_cache(ctx);
+    free(ctx);
+}
+
+/**
+ *@brief Clear the memory cache.
+ */
+void bi_clear_cache(BI_CTX *ctx)
+{
+    bigint *p, *pn;
+
+    if (ctx->free_list == NULL)
+        return;
+    
+    for (p = ctx->free_list; p != NULL; p = pn)
+    {
+        pn = p->next;
+        free(p->comps);
+        free(p);
+    }
+
+    ctx->free_count = 0;
+    ctx->free_list = NULL;
+}
+
+/**
+ * @brief Increment the number of references to this object. 
+ * It does not do a full copy.
+ * @param bi [in]   The bigint to copy.
+ * @return A reference to the same bigint.
+ */
+bigint *bi_copy(bigint *bi)
+{
+    check(bi);
+    if (bi->refs != PERMANENT)
+        bi->refs++;
+    return bi;
+}
+
+/**
+ * @brief Simply make a bigint object "unfreeable" if bi_free() is called on it.
+ *
+ * For this object to be freed, bi_depermanent() must be called.
+ * @param bi [in]   The bigint to be made permanent.
+ */
+void bi_permanent(bigint *bi)
+{
+    check(bi);
+    if (bi->refs != 1)
+    {
+#ifdef CONFIG_SSL_FULL_MODE
+        printf("bi_permanent: refs was not 1\n");
+#endif
+        abort();
+    }
+
+    bi->refs = PERMANENT;
+}
+
+/**
+ * @brief Take a permanent object and make it eligible for freedom.
+ * @param bi [in]   The bigint to be made back to temporary.
+ */
+void bi_depermanent(bigint *bi)
+{
+    check(bi);
+    if (bi->refs != PERMANENT)
+    {
+#ifdef CONFIG_SSL_FULL_MODE
+        printf("bi_depermanent: bigint was not permanent\n");
+#endif
+        abort();
+    }
+
+    bi->refs = 1;
+}
+
+/**
+ * @brief Free a bigint object so it can be used again. 
+ *
+ * The memory itself it not actually freed, just tagged as being available 
+ * @param ctx [in]   The bigint session context.
+ * @param bi [in]    The bigint to be freed.
+ */
+void bi_free(BI_CTX *ctx, bigint *bi)
+{
+    check(bi);
+    if (bi->refs == PERMANENT)
+    {
+        return;
+    }
+
+    if (--bi->refs > 0)
+    {
+        return;
+    }
+
+    bi->next = ctx->free_list;
+    ctx->free_list = bi;
+    ctx->free_count++;
+
+    if (--ctx->active_count < 0)
+    {
+#ifdef CONFIG_SSL_FULL_MODE
+        printf("bi_free: active_count went negative "
+                "- double-freed bigint?\n");
+#endif
+        abort();
+    }
+}
+
+/**
+ * @brief Convert an (unsigned) integer into a bigint.
+ * @param ctx [in]   The bigint session context.
+ * @param i [in]     The (unsigned) integer to be converted.
+ * 
+ */
+bigint *int_to_bi(BI_CTX *ctx, comp i)
+{
+    bigint *biR = alloc(ctx, 1);
+    biR->comps[0] = i;
+    return biR;
+}
+
+/**
+ * @brief Do a full copy of the bigint object.
+ * @param ctx [in]   The bigint session context.
+ * @param bi  [in]   The bigint object to be copied.
+ */
+bigint *bi_clone(BI_CTX *ctx, const bigint *bi)
+{
+    bigint *biR = alloc(ctx, bi->size);
+    check(bi);
+    memcpy(biR->comps, bi->comps, bi->size*COMP_BYTE_SIZE);
+    return biR;
+}
+
+/**
+ * @brief Perform an addition operation between two bigints.
+ * @param ctx [in]  The bigint session context.
+ * @param bia [in]  A bigint.
+ * @param bib [in]  Another bigint.
+ * @return The result of the addition.
+ */
+bigint *bi_add(BI_CTX *ctx, bigint *bia, bigint *bib)
+{
+    int n;
+    comp carry = 0;
+    comp *pa, *pb;
+
+    check(bia);
+    check(bib);
+
+    n = max(bia->size, bib->size);
+    more_comps(bia, n+1);
+    more_comps(bib, n);
+    pa = bia->comps;
+    pb = bib->comps;
+
+    do
+    {
+        comp  sl, rl, cy1;
+        sl = *pa + *pb++;
+        rl = sl + carry;
+        cy1 = sl < *pa;
+        carry = cy1 | (rl < sl);
+        *pa++ = rl;
+    } while (--n != 0);
+
+    *pa = carry;                  /* do overflow */
+    bi_free(ctx, bib);
+    return trim(bia);
+}
+
+/**
+ * @brief Perform a subtraction operation between two bigints.
+ * @param ctx [in]  The bigint session context.
+ * @param bia [in]  A bigint.
+ * @param bib [in]  Another bigint.
+ * @param is_negative [out] If defined, indicates that the result was negative.
+ * is_negative may be null.
+ * @return The result of the subtraction. The result is always positive.
+ */
+bigint *bi_subtract(BI_CTX *ctx, 
+        bigint *bia, bigint *bib, int *is_negative)
+{
+    int n = bia->size;
+    comp *pa, *pb, carry = 0;
+
+    check(bia);
+    check(bib);
+
+    more_comps(bib, n);
+    pa = bia->comps;
+    pb = bib->comps;
+
+    do 
+    {
+        comp sl, rl, cy1;
+        sl = *pa - *pb++;
+        rl = sl - carry;
+        cy1 = sl > *pa;
+        carry = cy1 | (rl > sl);
+        *pa++ = rl;
+    } while (--n != 0);
+
+    if (is_negative)    /* indicate a negative result */
+    {
+        *is_negative = carry;
+    }
+
+    bi_free(ctx, trim(bib));    /* put bib back to the way it was */
+    return trim(bia);
+}
+
+/**
+ * Perform a multiply between a bigint an an (unsigned) integer
+ */
+static bigint *bi_int_multiply(BI_CTX *ctx, bigint *bia, comp b)
+{
+    int j = 0, n = bia->size;
+    bigint *biR = alloc(ctx, n + 1);
+    comp carry = 0;
+    comp *r = biR->comps;
+    comp *a = bia->comps;
+
+    check(bia);
+
+    /* clear things to start with */
+    memset(r, 0, ((n+1)*COMP_BYTE_SIZE));
+
+    do
+    {
+        long_comp tmp = *r + (long_comp)a[j]*b + carry;
+        *r++ = (comp)tmp;              /* downsize */
+        carry = (comp)(tmp >> COMP_BIT_SIZE);
+    } while (++j < n);
+
+    *r = carry;
+    bi_free(ctx, bia);
+    return trim(biR);
+}
+
+/**
+ * @brief Does both division and modulo calculations. 
+ *
+ * Used extensively when doing classical reduction.
+ * @param ctx [in]  The bigint session context.
+ * @param u [in]    A bigint which is the numerator.
+ * @param v [in]    Either the denominator or the modulus depending on the mode.
+ * @param is_mod [n] Determines if this is a normal division (0) or a reduction
+ * (1).
+ * @return  The result of the division/reduction.
+ */
+bigint *bi_divide(BI_CTX *ctx, bigint *u, bigint *v, int is_mod)
+{
+    int n = v->size, m = u->size-n;
+    int j = 0, orig_u_size = u->size;
+    uint8_t mod_offset = ctx->mod_offset;
+    comp d;
+    bigint *quotient, *tmp_u;
+    comp q_dash;
+
+    check(u);
+    check(v);
+
+    /* if doing reduction and we are < mod, then return mod */
+    if (is_mod && bi_compare(v, u) > 0)
+    {
+        bi_free(ctx, v);
+        return u;
+    }
+
+    quotient = alloc(ctx, m+1);
+    tmp_u = alloc(ctx, n+1);
+    v = trim(v);        /* make sure we have no leading 0's */
+    d = (comp)((long_comp)COMP_RADIX/(V1+1));
+
+    /* clear things to start with */
+    memset(quotient->comps, 0, ((quotient->size)*COMP_BYTE_SIZE));
+
+    /* normalise */
+    if (d > 1)
+    {
+        u = bi_int_multiply(ctx, u, d);
+
+        if (is_mod)
+        {
+            v = ctx->bi_normalised_mod[mod_offset];
+        }
+        else
+        {
+            v = bi_int_multiply(ctx, v, d);
+        }
+    }
+
+    if (orig_u_size == u->size)  /* new digit position u0 */
+    {
+        more_comps(u, orig_u_size + 1);
+    }
+
+    do
+    {
+        /* get a temporary short version of u */
+        memcpy(tmp_u->comps, &u->comps[u->size-n-1-j], (n+1)*COMP_BYTE_SIZE);
+
+        /* calculate q' */
+        if (U(0) == V1)
+        {
+            q_dash = COMP_RADIX-1;
+        }
+        else
+        {
+            q_dash = (comp)(((long_comp)U(0)*COMP_RADIX + U(1))/V1);
+
+            if (v->size > 1 && V2)
+            {
+                /* we are implementing the following:
+                if (V2*q_dash > (((U(0)*COMP_RADIX + U(1) - 
+                        q_dash*V1)*COMP_RADIX) + U(2))) ... */
+                comp inner = (comp)((long_comp)COMP_RADIX*U(0) + U(1) - 
+                                            (long_comp)q_dash*V1);
+                if ((long_comp)V2*q_dash > (long_comp)inner*COMP_RADIX + U(2))
+                {
+                    q_dash--;
+                }
+            }
+        }
+
+        /* multiply and subtract */
+        if (q_dash)
+        {
+            int is_negative;
+            tmp_u = bi_subtract(ctx, tmp_u, 
+                    bi_int_multiply(ctx, bi_copy(v), q_dash), &is_negative);
+            more_comps(tmp_u, n+1);
+
+            Q(j) = q_dash; 
+
+            /* add back */
+            if (is_negative)
+            {
+                Q(j)--;
+                tmp_u = bi_add(ctx, tmp_u, bi_copy(v));
+
+                /* lop off the carry */
+                tmp_u->size--;
+                v->size--;
+            }
+        }
+        else
+        {
+            Q(j) = 0; 
+        }
+
+        /* copy back to u */
+        memcpy(&u->comps[u->size-n-1-j], tmp_u->comps, (n+1)*COMP_BYTE_SIZE);
+    } while (++j <= m);
+
+    bi_free(ctx, tmp_u);
+    bi_free(ctx, v);
+
+    if (is_mod)     /* get the remainder */
+    {
+        bi_free(ctx, quotient);
+        return bi_int_divide(ctx, trim(u), d);
+    }
+    else            /* get the quotient */
+    {
+        bi_free(ctx, u);
+        return trim(quotient);
+    }
+}
+
+/*
+ * Perform an integer divide on a bigint.
+ */
+static bigint *bi_int_divide(BI_CTX *ctx, bigint *biR, comp denom)
+{
+    int i = biR->size - 1;
+    long_comp r = 0;
+
+    check(biR);
+
+    do
+    {
+        r = (r<<COMP_BIT_SIZE) + biR->comps[i];
+        biR->comps[i] = (comp)(r / denom);
+        r %= denom;
+    } while (--i >= 0);
+
+    return trim(biR);
+}
+
+#ifdef CONFIG_BIGINT_MONTGOMERY
+/**
+ * There is a need for the value of integer N' such that B^-1(B-1)-N^-1N'=1, 
+ * where B^-1(B-1) mod N=1. Actually, only the least significant part of 
+ * N' is needed, hence the definition N0'=N' mod b. We reproduce below the 
+ * simple algorithm from an article by Dusse and Kaliski to efficiently 
+ * find N0' from N0 and b */
+static comp modular_inverse(bigint *bim)
+{
+    int i;
+    comp t = 1;
+    comp two_2_i_minus_1 = 2;   /* 2^(i-1) */
+    long_comp two_2_i = 4;      /* 2^i */
+    comp N = bim->comps[0];
+
+    for (i = 2; i <= COMP_BIT_SIZE; i++)
+    {
+        if ((long_comp)N*t%two_2_i >= two_2_i_minus_1)
+        {
+            t += two_2_i_minus_1;
+        }
+
+        two_2_i_minus_1 <<= 1;
+        two_2_i <<= 1;
+    }
+
+    return (comp)(COMP_RADIX-t);
+}
+#endif
+
+#if defined(CONFIG_BIGINT_KARATSUBA) || defined(CONFIG_BIGINT_BARRETT) || \
+    defined(CONFIG_BIGINT_MONTGOMERY)
+/**
+ * Take each component and shift down (in terms of components) 
+ */
+static bigint *comp_right_shift(bigint *biR, int num_shifts)
+{
+    int i = biR->size-num_shifts;
+    comp *x = biR->comps;
+    comp *y = &biR->comps[num_shifts];
+
+    check(biR);
+
+    if (i <= 0)     /* have we completely right shifted? */
+    {
+        biR->comps[0] = 0;  /* return 0 */
+        biR->size = 1;
+        return biR;
+    }
+
+    do
+    {
+        *x++ = *y++;
+    } while (--i > 0);
+
+    biR->size -= num_shifts;
+    return biR;
+}
+
+/**
+ * Take each component and shift it up (in terms of components) 
+ */
+static bigint *comp_left_shift(bigint *biR, int num_shifts)
+{
+    int i = biR->size-1;
+    comp *x, *y;
+
+    check(biR);
+
+    if (num_shifts <= 0)
+    {
+        return biR;
+    }
+
+    more_comps(biR, biR->size + num_shifts);
+
+    x = &biR->comps[i+num_shifts];
+    y = &biR->comps[i];
+
+    do
+    {
+        *x-- = *y--;
+    } while (i--);
+
+    memset(biR->comps, 0, num_shifts*COMP_BYTE_SIZE); /* zero LS comps */
+    return biR;
+}
+#endif
+
+/**
+ * @brief Allow a binary sequence to be imported as a bigint.
+ * @param ctx [in]  The bigint session context.
+ * @param data [in] The data to be converted.
+ * @param size [in] The number of bytes of data.
+ * @return A bigint representing this data.
+ */
+bigint *bi_import(BI_CTX *ctx, const uint8_t *data, int size)
+{
+    bigint *biR = alloc(ctx, (size+COMP_BYTE_SIZE-1)/COMP_BYTE_SIZE);
+    int i, j = 0, offset = 0;
+
+    memset(biR->comps, 0, biR->size*COMP_BYTE_SIZE);
+
+    for (i = size-1; i >= 0; i--)
+    {
+        biR->comps[offset] += data[i] << (j*8);
+
+        if (++j == COMP_BYTE_SIZE)
+        {
+            j = 0;
+            offset ++;
+        }
+    }
+
+    return trim(biR);
+}
+
+#ifdef CONFIG_SSL_FULL_MODE
+/**
+ * @brief The testharness uses this code to import text hex-streams and 
+ * convert them into bigints.
+ * @param ctx [in]  The bigint session context.
+ * @param data [in] A string consisting of hex characters. The characters must
+ * be in upper case.
+ * @return A bigint representing this data.
+ */
+bigint *bi_str_import(BI_CTX *ctx, const char *data)
+{
+    int size = strlen(data);
+    bigint *biR = alloc(ctx, (size+COMP_NUM_NIBBLES-1)/COMP_NUM_NIBBLES);
+    int i, j = 0, offset = 0;
+    memset(biR->comps, 0, biR->size*COMP_BYTE_SIZE);
+
+    for (i = size-1; i >= 0; i--)
+    {
+        int num = (data[i] <= '9') ? (data[i] - '0') : (data[i] - 'A' + 10);
+        biR->comps[offset] += num << (j*4);
+
+        if (++j == COMP_NUM_NIBBLES)
+        {
+            j = 0;
+            offset ++;
+        }
+    }
+
+    return biR;
+}
+
+void bi_print(const char *label, bigint *x)
+{
+    int i, j;
+
+    if (x == NULL)
+    {
+        printf("%s: (null)\n", label);
+        return;
+    }
+
+    printf("%s: (size %d)\n", label, x->size);
+    for (i = x->size-1; i >= 0; i--)
+    {
+        for (j = COMP_NUM_NIBBLES-1; j >= 0; j--)
+        {
+            comp mask = 0x0f << (j*4);
+            comp num = (x->comps[i] & mask) >> (j*4);
+            putc((num <= 9) ? (num + '0') : (num + 'A' - 10), stdout);
+        }
+    }  
+
+    printf("\n");
+}
+#endif
+
+/**
+ * @brief Take a bigint and convert it into a byte sequence. 
+ *
+ * This is useful after a decrypt operation.
+ * @param ctx [in]  The bigint session context.
+ * @param x [in]  The bigint to be converted.
+ * @param data [out] The converted data as a byte stream.
+ * @param size [in] The maximum size of the byte stream. Unused bytes will be
+ * zeroed.
+ */
+void bi_export(BI_CTX *ctx, bigint *x, uint8_t *data, int size)
+{
+    int i, j, k = size-1;
+
+    check(x);
+    memset(data, 0, size);  /* ensure all leading 0's are cleared */
+
+    for (i = 0; i < x->size; i++)
+    {
+        for (j = 0; j < COMP_BYTE_SIZE; j++)
+        {
+            comp mask = 0xff << (j*8);
+            int num = (x->comps[i] & mask) >> (j*8);
+            data[k--] = num;
+
+            if (k < 0)
+            {
+                goto buf_done;
+            }
+        }
+    }
+buf_done:
+
+    bi_free(ctx, x);
+}
+
+/**
+ * @brief Pre-calculate some of the expensive steps in reduction. 
+ *
+ * This function should only be called once (normally when a session starts).
+ * When the session is over, bi_free_mod() should be called. bi_mod_power()
+ * relies on this function being called.
+ * @param ctx [in]  The bigint session context.
+ * @param bim [in]  The bigint modulus that will be used.
+ * @param mod_offset [in] There are three moduluii that can be stored - the
+ * standard modulus, and its two primes p and q. This offset refers to which
+ * modulus we are referring to.
+ * @see bi_free_mod(), bi_mod_power().
+ */
+void bi_set_mod(BI_CTX *ctx, bigint *bim, int mod_offset)
+{
+    int k = bim->size;
+    comp d = (comp)((long_comp)COMP_RADIX/(bim->comps[k-1]+1));
+#ifdef CONFIG_BIGINT_MONTGOMERY
+    bigint *R, *R2;
+#endif
+
+    ctx->bi_mod[mod_offset] = bim;
+    bi_permanent(ctx->bi_mod[mod_offset]);
+    ctx->bi_normalised_mod[mod_offset] = bi_int_multiply(ctx, bim, d);
+    bi_permanent(ctx->bi_normalised_mod[mod_offset]);
+
+#if defined(CONFIG_BIGINT_MONTGOMERY)
+    /* set montgomery variables */
+    R = comp_left_shift(bi_clone(ctx, ctx->bi_radix), k-1);     /* R */
+    R2 = comp_left_shift(bi_clone(ctx, ctx->bi_radix), k*2-1);  /* R^2 */
+    ctx->bi_RR_mod_m[mod_offset] = bi_mod(ctx, R2);             /* R^2 mod m */
+    ctx->bi_R_mod_m[mod_offset] = bi_mod(ctx, R);               /* R mod m */
+
+    bi_permanent(ctx->bi_RR_mod_m[mod_offset]);
+    bi_permanent(ctx->bi_R_mod_m[mod_offset]);
+
+    ctx->N0_dash[mod_offset] = modular_inverse(ctx->bi_mod[mod_offset]);
+
+#elif defined (CONFIG_BIGINT_BARRETT)
+    ctx->bi_mu[mod_offset] = 
+        bi_divide(ctx, comp_left_shift(
+            bi_clone(ctx, ctx->bi_radix), k*2-1), ctx->bi_mod[mod_offset], 0);
+    bi_permanent(ctx->bi_mu[mod_offset]);
+#endif
+}
+
+/**
+ * @brief Used when cleaning various bigints at the end of a session.
+ * @param ctx [in]  The bigint session context.
+ * @param mod_offset [in] The offset to use.
+ * @see bi_set_mod().
+ */
+void bi_free_mod(BI_CTX *ctx, int mod_offset)
+{
+    bi_depermanent(ctx->bi_mod[mod_offset]);
+    bi_free(ctx, ctx->bi_mod[mod_offset]);
+#if defined (CONFIG_BIGINT_MONTGOMERY)
+    bi_depermanent(ctx->bi_RR_mod_m[mod_offset]);
+    bi_depermanent(ctx->bi_R_mod_m[mod_offset]);
+    bi_free(ctx, ctx->bi_RR_mod_m[mod_offset]);
+    bi_free(ctx, ctx->bi_R_mod_m[mod_offset]);
+#elif defined(CONFIG_BIGINT_BARRETT)
+    bi_depermanent(ctx->bi_mu[mod_offset]); 
+    bi_free(ctx, ctx->bi_mu[mod_offset]);
+#endif
+    bi_depermanent(ctx->bi_normalised_mod[mod_offset]); 
+    bi_free(ctx, ctx->bi_normalised_mod[mod_offset]);
+}
+
+/** 
+ * Perform a standard multiplication between two bigints.
+ *
+ * Barrett reduction has no need for some parts of the product, so ignore bits
+ * of the multiply. This routine gives Barrett its big performance
+ * improvements over Classical/Montgomery reduction methods. 
+ */
+static bigint *regular_multiply(BI_CTX *ctx, bigint *bia, bigint *bib, 
+        int inner_partial, int outer_partial)
+{
+    int i = 0, j;
+    int n = bia->size;
+    int t = bib->size;
+    bigint *biR = alloc(ctx, n + t);
+    comp *sr = biR->comps;
+    comp *sa = bia->comps;
+    comp *sb = bib->comps;
+
+    check(bia);
+    check(bib);
+
+    /* clear things to start with */
+    memset(biR->comps, 0, ((n+t)*COMP_BYTE_SIZE));
+
+    do 
+    {
+        long_comp tmp;
+        comp carry = 0;
+        int r_index = i;
+        j = 0;
+
+        if (outer_partial && outer_partial-i > 0 && outer_partial < n)
+        {
+            r_index = outer_partial-1;
+            j = outer_partial-i-1;
+        }
+
+        do
+        {
+            if (inner_partial && r_index >= inner_partial) 
+            {
+                break;
+            }
+
+            tmp = sr[r_index] + ((long_comp)sa[j])*sb[i] + carry;
+            sr[r_index++] = (comp)tmp;              /* downsize */
+            carry = tmp >> COMP_BIT_SIZE;
+        } while (++j < n);
+
+        sr[r_index] = carry;
+    } while (++i < t);
+
+    bi_free(ctx, bia);
+    bi_free(ctx, bib);
+    return trim(biR);
+}
+
+#ifdef CONFIG_BIGINT_KARATSUBA
+/*
+ * Karatsuba improves on regular multiplication due to only 3 multiplications 
+ * being done instead of 4. The additional additions/subtractions are O(N) 
+ * rather than O(N^2) and so for big numbers it saves on a few operations 
+ */
+static bigint *karatsuba(BI_CTX *ctx, bigint *bia, bigint *bib, int is_square)
+{
+    bigint *x0, *x1;
+    bigint *p0, *p1, *p2;
+    int m;
+
+    if (is_square)
+    {
+        m = (bia->size + 1)/2;
+    }
+    else
+    {
+        m = (max(bia->size, bib->size) + 1)/2;
+    }
+
+    x0 = bi_clone(ctx, bia);
+    x0->size = m;
+    x1 = bi_clone(ctx, bia);
+    comp_right_shift(x1, m);
+    bi_free(ctx, bia);
+
+    /* work out the 3 partial products */
+    if (is_square)
+    {
+        p0 = bi_square(ctx, bi_copy(x0));
+        p2 = bi_square(ctx, bi_copy(x1));
+        p1 = bi_square(ctx, bi_add(ctx, x0, x1));
+    }
+    else /* normal multiply */
+    {
+        bigint *y0, *y1;
+        y0 = bi_clone(ctx, bib);
+        y0->size = m;
+        y1 = bi_clone(ctx, bib);
+        comp_right_shift(y1, m);
+        bi_free(ctx, bib);
+
+        p0 = bi_multiply(ctx, bi_copy(x0), bi_copy(y0));
+        p2 = bi_multiply(ctx, bi_copy(x1), bi_copy(y1));
+        p1 = bi_multiply(ctx, bi_add(ctx, x0, x1), bi_add(ctx, y0, y1));
+    }
+
+    p1 = bi_subtract(ctx, 
+            bi_subtract(ctx, p1, bi_copy(p2), NULL), bi_copy(p0), NULL);
+
+    comp_left_shift(p1, m);
+    comp_left_shift(p2, 2*m);
+    return bi_add(ctx, p1, bi_add(ctx, p0, p2));
+}
+#endif
+
+/**
+ * @brief Perform a multiplication operation between two bigints.
+ * @param ctx [in]  The bigint session context.
+ * @param bia [in]  A bigint.
+ * @param bib [in]  Another bigint.
+ * @return The result of the multiplication.
+ */
+bigint *bi_multiply(BI_CTX *ctx, bigint *bia, bigint *bib)
+{
+    check(bia);
+    check(bib);
+
+#ifdef CONFIG_BIGINT_KARATSUBA
+    if (min(bia->size, bib->size) < MUL_KARATSUBA_THRESH)
+    {
+        return regular_multiply(ctx, bia, bib, 0, 0);
+    }
+
+    return karatsuba(ctx, bia, bib, 0);
+#else
+    return regular_multiply(ctx, bia, bib, 0, 0);
+#endif
+}
+
+#ifdef CONFIG_BIGINT_SQUARE
+/*
+ * Perform the actual square operion. It takes into account overflow.
+ */
+static bigint *regular_square(BI_CTX *ctx, bigint *bi)
+{
+    int t = bi->size;
+    int i = 0, j;
+    bigint *biR = alloc(ctx, t*2+1);
+    comp *w = biR->comps;
+    comp *x = bi->comps;
+    long_comp carry;
+    memset(w, 0, biR->size*COMP_BYTE_SIZE);
+
+    do
+    {
+        long_comp tmp = w[2*i] + (long_comp)x[i]*x[i];
+        w[2*i] = (comp)tmp;
+        carry = tmp >> COMP_BIT_SIZE;
+
+        for (j = i+1; j < t; j++)
+        {
+            uint8_t c = 0;
+            long_comp xx = (long_comp)x[i]*x[j];
+            if ((COMP_MAX-xx) < xx)
+                c = 1;
+
+            tmp = (xx<<1);
+
+            if ((COMP_MAX-tmp) < w[i+j])
+                c = 1;
+
+            tmp += w[i+j];
+
+            if ((COMP_MAX-tmp) < carry)
+                c = 1;
+
+            tmp += carry;
+            w[i+j] = (comp)tmp;
+            carry = tmp >> COMP_BIT_SIZE;
+
+            if (c)
+                carry += COMP_RADIX;
+        }
+
+        tmp = w[i+t] + carry;
+        w[i+t] = (comp)tmp;
+        w[i+t+1] = tmp >> COMP_BIT_SIZE;
+    } while (++i < t);
+
+    bi_free(ctx, bi);
+    return trim(biR);
+}
+
+/**
+ * @brief Perform a square operation on a bigint.
+ * @param ctx [in]  The bigint session context.
+ * @param bia [in]  A bigint.
+ * @return The result of the multiplication.
+ */
+bigint *bi_square(BI_CTX *ctx, bigint *bia)
+{
+    check(bia);
+
+#ifdef CONFIG_BIGINT_KARATSUBA
+    if (bia->size < SQU_KARATSUBA_THRESH) 
+    {
+        return regular_square(ctx, bia);
+    }
+
+    return karatsuba(ctx, bia, NULL, 1);
+#else
+    return regular_square(ctx, bia);
+#endif
+}
+#endif
+
+/**
+ * @brief Compare two bigints.
+ * @param bia [in]  A bigint.
+ * @param bib [in]  Another bigint.
+ * @return -1 if smaller, 1 if larger and 0 if equal.
+ */
+int bi_compare(bigint *bia, bigint *bib)
+{
+    int r, i;
+
+    check(bia);
+    check(bib);
+
+    if (bia->size > bib->size)
+        r = 1;
+    else if (bia->size < bib->size)
+        r = -1;
+    else
+    {
+        comp *a = bia->comps; 
+        comp *b = bib->comps; 
+
+        /* Same number of components.  Compare starting from the high end
+         * and working down. */
+        r = 0;
+        i = bia->size - 1;
+
+        do 
+        {
+            if (a[i] > b[i])
+            { 
+                r = 1;
+                break; 
+            }
+            else if (a[i] < b[i])
+            { 
+                r = -1;
+                break; 
+            }
+        } while (--i >= 0);
+    }
+
+    return r;
+}
+
+/*
+ * Allocate and zero more components.  Does not consume bi. 
+ */
+static void more_comps(bigint *bi, int n)
+{
+    if (n > bi->max_comps)
+    {
+        bi->max_comps = max(bi->max_comps * 2, n);
+        bi->comps = (comp*)realloc(bi->comps, bi->max_comps * COMP_BYTE_SIZE);
+    }
+
+    if (n > bi->size)
+    {
+        memset(&bi->comps[bi->size], 0, (n-bi->size)*COMP_BYTE_SIZE);
+    }
+
+    bi->size = n;
+}
+
+/*
+ * Make a new empty bigint. It may just use an old one if one is available.
+ * Otherwise get one off the heap.
+ */
+static bigint *alloc(BI_CTX *ctx, int size)
+{
+    bigint *biR;
+
+    /* Can we recycle an old bigint? */
+    if (ctx->free_list != NULL)
+    {
+        biR = ctx->free_list;
+        ctx->free_list = biR->next;
+        ctx->free_count--;
+
+        if (biR->refs != 0)
+        {
+#ifdef CONFIG_SSL_FULL_MODE
+            printf("alloc: refs was not 0\n");
+#endif
+            abort();    /* create a stack trace from a core dump */
+        }
+
+        more_comps(biR, size);
+    }
+    else
+    {
+        /* No free bigints available - create a new one. */
+        biR = (bigint *)malloc(sizeof(bigint));
+        biR->comps = (comp*)malloc(size * COMP_BYTE_SIZE);
+        biR->max_comps = size;  /* give some space to spare */
+    }
+
+    biR->size = size;
+    biR->refs = 1;
+    biR->next = NULL;
+    ctx->active_count++;
+    return biR;
+}
+
+/*
+ * Work out the highest '1' bit in an exponent. Used when doing sliding-window
+ * exponentiation.
+ */
+static int find_max_exp_index(bigint *biexp)
+{
+    int i = COMP_BIT_SIZE-1;
+    comp shift = COMP_RADIX/2;
+    comp test = biexp->comps[biexp->size-1];    /* assume no leading zeroes */
+
+    check(biexp);
+
+    do
+    {
+        if (test & shift)
+        {
+            return i+(biexp->size-1)*COMP_BIT_SIZE;
+        }
+
+        shift >>= 1;
+    } while (i-- != 0);
+
+    return -1;      /* error - must have been a leading 0 */
+}
+
+/*
+ * Is a particular bit is an exponent 1 or 0? Used when doing sliding-window
+ * exponentiation.
+ */
+static int exp_bit_is_one(bigint *biexp, int offset)
+{
+    comp test = biexp->comps[offset / COMP_BIT_SIZE];
+    int num_shifts = offset % COMP_BIT_SIZE;
+    comp shift = 1;
+    int i;
+
+    check(biexp);
+
+    for (i = 0; i < num_shifts; i++)
+    {
+        shift <<= 1;
+    }
+
+    return (test & shift) != 0;
+}
+
+#ifdef CONFIG_BIGINT_CHECK_ON
+/*
+ * Perform a sanity check on bi.
+ */
+static void check(const bigint *bi)
+{
+    if (bi->refs <= 0)
+    {
+        printf("check: zero or negative refs in bigint\n");
+        abort();
+    }
+
+    if (bi->next != NULL)
+    {
+        printf("check: attempt to use a bigint from "
+                "the free list\n");
+        abort();
+    }
+}
+#endif
+
+/*
+ * Delete any leading 0's (and allow for 0).
+ */
+static bigint *trim(bigint *bi)
+{
+    check(bi);
+
+    while (bi->comps[bi->size-1] == 0 && bi->size > 1)
+    {
+        bi->size--;
+    }
+
+    return bi;
+}
+
+#if defined(CONFIG_BIGINT_MONTGOMERY)
+/**
+ * @brief Perform a single montgomery reduction.
+ * @param ctx [in]  The bigint session context.
+ * @param bixy [in]  A bigint.
+ * @return The result of the montgomery reduction.
+ */
+bigint *bi_mont(BI_CTX *ctx, bigint *bixy)
+{
+    int i = 0, n;
+    uint8_t mod_offset = ctx->mod_offset;
+    bigint *bim = ctx->bi_mod[mod_offset];
+    comp mod_inv = ctx->N0_dash[mod_offset];
+
+    check(bixy);
+
+    if (ctx->use_classical)     /* just use classical instead */
+    {
+        return bi_mod(ctx, bixy);
+    }
+
+    n = bim->size;
+
+    do
+    {
+        bixy = bi_add(ctx, bixy, comp_left_shift(
+                    bi_int_multiply(ctx, bim, bixy->comps[i]*mod_inv), i));
+    } while (++i < n);
+
+    comp_right_shift(bixy, n);
+
+    if (bi_compare(bixy, bim) >= 0)
+    {
+        bixy = bi_subtract(ctx, bixy, bim, NULL);
+    }
+
+    return bixy;
+}
+
+#elif defined(CONFIG_BIGINT_BARRETT)
+/*
+ * Stomp on the most significant components to give the illusion of a "mod base
+ * radix" operation 
+ */
+static bigint *comp_mod(bigint *bi, int mod)
+{
+    check(bi);
+
+    if (bi->size > mod)
+    {
+        bi->size = mod;
+    }
+
+    return bi;
+}
+
+/**
+ * @brief Perform a single Barrett reduction.
+ * @param ctx [in]  The bigint session context.
+ * @param bi [in]  A bigint.
+ * @return The result of the Barrett reduction.
+ */
+bigint *bi_barrett(BI_CTX *ctx, bigint *bi)
+{
+    bigint *q1, *q2, *q3, *r1, *r2, *r;
+    uint8_t mod_offset = ctx->mod_offset;
+    bigint *bim = ctx->bi_mod[mod_offset];
+    int k = bim->size;
+
+    check(bi);
+    check(bim);
+
+    /* use Classical method instead  - Barrett cannot help here */
+    if (bi->size > k*2)
+    {
+        return bi_mod(ctx, bi);
+    }
+
+    q1 = comp_right_shift(bi_clone(ctx, bi), k-1);
+
+    /* do outer partial multiply */
+    q2 = regular_multiply(ctx, q1, ctx->bi_mu[mod_offset], 0, k-1); 
+    q3 = comp_right_shift(q2, k+1);
+    r1 = comp_mod(bi, k+1);
+
+    /* do inner partial multiply */
+    r2 = comp_mod(regular_multiply(ctx, q3, bim, k+1, 0), k+1);
+    r = bi_subtract(ctx, r1, r2, NULL);
+
+    /* if (r >= m) r = r - m; */
+    if (bi_compare(r, bim) >= 0)
+    {
+        r = bi_subtract(ctx, r, bim, NULL);
+    }
+
+    return r;
+}
+#endif /* CONFIG_BIGINT_BARRETT */
+
+#ifdef CONFIG_BIGINT_SLIDING_WINDOW
+/*
+ * Work out g1, g3, g5, g7... etc for the sliding-window algorithm 
+ */
+static void precompute_slide_window(BI_CTX *ctx, int window, bigint *g1)
+{
+    int k = 1, i;
+    bigint *g2;
+
+    for (i = 0; i < window-1; i++)   /* compute 2^(window-1) */
+    {
+        k <<= 1;
+    }
+
+    ctx->g = (bigint **)malloc(k*sizeof(bigint *));
+    ctx->g[0] = bi_clone(ctx, g1);
+    bi_permanent(ctx->g[0]);
+    g2 = bi_residue(ctx, bi_square(ctx, ctx->g[0]));   /* g^2 */
+
+    for (i = 1; i < k; i++)
+    {
+        ctx->g[i] = bi_residue(ctx, bi_multiply(ctx, ctx->g[i-1], bi_copy(g2)));
+        bi_permanent(ctx->g[i]);
+    }
+
+    bi_free(ctx, g2);
+    ctx->window = k;
+}
+#endif
+
+/**
+ * @brief Perform a modular exponentiation.
+ *
+ * This function requires bi_set_mod() to have been called previously. This is 
+ * one of the optimisations used for performance.
+ * @param ctx [in]  The bigint session context.
+ * @param bi  [in]  The bigint on which to perform the mod power operation.
+ * @param biexp [in] The bigint exponent.
+ * @return The result of the mod exponentiation operation
+ * @see bi_set_mod().
+ */
+bigint *bi_mod_power(BI_CTX *ctx, bigint *bi, bigint *biexp)
+{
+    int i = find_max_exp_index(biexp), j, window_size = 1;
+    bigint *biR = int_to_bi(ctx, 1);
+
+#if defined(CONFIG_BIGINT_MONTGOMERY)
+    uint8_t mod_offset = ctx->mod_offset;
+    if (!ctx->use_classical)
+    {
+        /* preconvert */
+        bi = bi_mont(ctx, 
+                bi_multiply(ctx, bi, ctx->bi_RR_mod_m[mod_offset]));    /* x' */
+        bi_free(ctx, biR);
+        biR = ctx->bi_R_mod_m[mod_offset];                              /* A */
+    }
+#endif
+
+    check(bi);
+    check(biexp);
+
+#ifdef CONFIG_BIGINT_SLIDING_WINDOW
+    for (j = i; j > 32; j /= 5) /* work out an optimum size */
+        window_size++;
+
+    /* work out the slide constants */
+    precompute_slide_window(ctx, window_size, bi);
+#else   /* just one constant */
+    ctx->g = (bigint **)malloc(sizeof(bigint *));
+    ctx->g[0] = bi_clone(ctx, bi);
+    ctx->window = 1;
+    bi_permanent(ctx->g[0]);
+#endif
+
+    /* if sliding-window is off, then only one bit will be done at a time and
+     * will reduce to standard left-to-right exponentiation */
+    do
+    {
+        if (exp_bit_is_one(biexp, i))
+        {
+            int l = i-window_size+1;
+            int part_exp = 0;
+
+            if (l < 0)  /* LSB of exponent will always be 1 */
+                l = 0;
+            else
+            {
+                while (exp_bit_is_one(biexp, l) == 0)
+                    l++;    /* go back up */
+            }
+
+            /* build up the section of the exponent */
+            for (j = i; j >= l; j--)
+            {
+                biR = bi_residue(ctx, bi_square(ctx, biR));
+                if (exp_bit_is_one(biexp, j))
+                    part_exp++;
+
+                if (j != l)
+                    part_exp <<= 1;
+            }
+
+            part_exp = (part_exp-1)/2;  /* adjust for array */
+            biR = bi_residue(ctx, bi_multiply(ctx, biR, ctx->g[part_exp]));
+            i = l-1;
+        }
+        else    /* square it */
+        {
+            biR = bi_residue(ctx, bi_square(ctx, biR));
+            i--;
+        }
+    } while (i >= 0);
+     
+    /* cleanup */
+    for (i = 0; i < ctx->window; i++)
+    {
+        bi_depermanent(ctx->g[i]);
+        bi_free(ctx, ctx->g[i]);
+    }
+
+    free(ctx->g);
+    bi_free(ctx, bi);
+    bi_free(ctx, biexp);
+#if defined CONFIG_BIGINT_MONTGOMERY
+    return ctx->use_classical ? biR : bi_mont(ctx, biR); /* convert back */
+#else /* CONFIG_BIGINT_CLASSICAL or CONFIG_BIGINT_BARRETT */
+    return biR;
+#endif
+}
+
+#ifdef CONFIG_SSL_CERT_VERIFICATION
+/**
+ * @brief Perform a modular exponentiation using a temporary modulus.
+ *
+ * We need this function to check the signatures of certificates. The modulus
+ * of this function is temporary as it's just used for authentication.
+ * @param ctx [in]  The bigint session context.
+ * @param bi  [in]  The bigint to perform the exp/mod.
+ * @param bim [in]  The temporary modulus.
+ * @param biexp [in] The bigint exponent.
+ * @return The result of the mod exponentiation operation
+ * @see bi_set_mod().
+ */
+bigint *bi_mod_power2(BI_CTX *ctx, bigint *bi, bigint *bim, bigint *biexp)
+{
+    bigint *biR, *tmp_biR;
+
+    /* Set up a temporary bigint context and transfer what we need between
+     * them. We need to do this since we want to keep the original modulus
+     * which is already in this context. This operation is only called when
+     * doing peer verification, and so is not expensive :-) */
+    BI_CTX *tmp_ctx = bi_initialize();
+    bi_set_mod(tmp_ctx, bi_clone(tmp_ctx, bim), BIGINT_M_OFFSET);
+    tmp_biR = bi_mod_power(tmp_ctx, 
+                bi_clone(tmp_ctx, bi), 
+                bi_clone(tmp_ctx, biexp));
+    biR = bi_clone(ctx, tmp_biR);
+    bi_free(tmp_ctx, tmp_biR);
+    bi_free_mod(tmp_ctx, BIGINT_M_OFFSET);
+    bi_terminate(tmp_ctx);
+
+    bi_free(ctx, bi);
+    bi_free(ctx, bim);
+    bi_free(ctx, biexp);
+    return biR;
+}
+#endif
+
+#ifdef CONFIG_BIGINT_CRT
+/**
+ * @brief Use the Chinese Remainder Theorem to quickly perform RSA decrypts.
+ *
+ * @param ctx [in]  The bigint session context.
+ * @param bi  [in]  The bigint to perform the exp/mod.
+ * @param dP [in] CRT's dP bigint
+ * @param dQ [in] CRT's dQ bigint
+ * @param p [in] CRT's p bigint
+ * @param q [in] CRT's q bigint
+ * @param qInv [in] CRT's qInv bigint
+ * @return The result of the CRT operation
+ */
+bigint *bi_crt(BI_CTX *ctx, bigint *bi,
+        bigint *dP, bigint *dQ,
+        bigint *p, bigint *q, bigint *qInv)
+{
+    bigint *m1, *m2, *h;
+
+    /* Montgomery has a condition the 0 < x, y < m and these products violate
+     * that condition. So disable Montgomery when using CRT */
+#if defined(CONFIG_BIGINT_MONTGOMERY)
+    ctx->use_classical = 1;
+#endif
+    ctx->mod_offset = BIGINT_P_OFFSET;
+    m1 = bi_mod_power(ctx, bi_copy(bi), dP);
+
+    ctx->mod_offset = BIGINT_Q_OFFSET;
+    m2 = bi_mod_power(ctx, bi, dQ);
+
+    h = bi_subtract(ctx, bi_add(ctx, m1, p), bi_copy(m2), NULL);
+    h = bi_multiply(ctx, h, qInv);
+    ctx->mod_offset = BIGINT_P_OFFSET;
+    h = bi_residue(ctx, h);
+#if defined(CONFIG_BIGINT_MONTGOMERY)
+    ctx->use_classical = 0;         /* reset for any further operation */
+#endif
+    return bi_add(ctx, m2, bi_multiply(ctx, q, h));
+}
+#endif
+/** @} */
diff --git a/src/crypto/bigint.h b/src/crypto/bigint.h
new file mode 100644 (file)
index 0000000..2966a3e
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2007, Cameron Rich
+ * 
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice, 
+ *   this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice, 
+ *   this list of conditions and the following disclaimer in the documentation 
+ *   and/or other materials provided with the distribution.
+ * * Neither the name of the axTLS project nor the names of its contributors 
+ *   may be used to endorse or promote products derived from this software 
+ *   without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef BIGINT_HEADER
+#define BIGINT_HEADER
+
+#include "crypto.h"
+
+BI_CTX *bi_initialize(void);
+void bi_terminate(BI_CTX *ctx);
+void bi_permanent(bigint *bi);
+void bi_depermanent(bigint *bi);
+void bi_clear_cache(BI_CTX *ctx);
+void bi_free(BI_CTX *ctx, bigint *bi);
+bigint *bi_copy(bigint *bi);
+bigint *bi_clone(BI_CTX *ctx, const bigint *bi);
+void bi_export(BI_CTX *ctx, bigint *bi, uint8_t *data, int size);
+bigint *bi_import(BI_CTX *ctx, const uint8_t *data, int len);
+bigint *int_to_bi(BI_CTX *ctx, comp i);
+
+/* the functions that actually do something interesting */
+bigint *bi_add(BI_CTX *ctx, bigint *bia, bigint *bib);
+bigint *bi_subtract(BI_CTX *ctx, bigint *bia, 
+        bigint *bib, int *is_negative);
+bigint *bi_divide(BI_CTX *ctx, bigint *bia, bigint *bim, int is_mod);
+bigint *bi_multiply(BI_CTX *ctx, bigint *bia, bigint *bib);
+bigint *bi_mod_power(BI_CTX *ctx, bigint *bi, bigint *biexp);
+bigint *bi_mod_power2(BI_CTX *ctx, bigint *bi, bigint *bim, bigint *biexp);
+int bi_compare(bigint *bia, bigint *bib);
+void bi_set_mod(BI_CTX *ctx, bigint *bim, int mod_offset);
+void bi_free_mod(BI_CTX *ctx, int mod_offset);
+
+#ifdef CONFIG_SSL_FULL_MODE
+void bi_print(const char *label, bigint *bi);
+bigint *bi_str_import(BI_CTX *ctx, const char *data);
+#endif
+
+/**
+ * @def bi_mod
+ * Find the residue of B. bi_set_mod() must be called before hand.
+ */
+#define bi_mod(A, B)      bi_divide(A, B, ctx->bi_mod[ctx->mod_offset], 1)
+
+/**
+ * bi_residue() is technically the same as bi_mod(), but it uses the
+ * appropriate reduction technique (which is bi_mod() when doing classical
+ * reduction).
+ */
+#if defined(CONFIG_BIGINT_MONTGOMERY)
+#define bi_residue(A, B)         bi_mont(A, B)
+bigint *bi_mont(BI_CTX *ctx, bigint *bixy);
+#elif defined(CONFIG_BIGINT_BARRETT)
+#define bi_residue(A, B)         bi_barrett(A, B)
+bigint *bi_barrett(BI_CTX *ctx, bigint *bi);
+#else /* if defined(CONFIG_BIGINT_CLASSICAL) */
+#define bi_residue(A, B)         bi_mod(A, B)
+#endif
+
+#ifdef CONFIG_BIGINT_SQUARE
+bigint *bi_square(BI_CTX *ctx, bigint *bi);
+#else
+#define bi_square(A, B)     bi_multiply(A, bi_copy(B), B)
+#endif
+
+#ifdef CONFIG_BIGINT_CRT
+bigint *bi_crt(BI_CTX *ctx, bigint *bi,
+        bigint *dP, bigint *dQ,
+        bigint *p, bigint *q,
+        bigint *qInv);
+#endif
+
+#endif
diff --git a/src/crypto/bigint_impl.h b/src/crypto/bigint_impl.h
new file mode 100644 (file)
index 0000000..820620d
--- /dev/null
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2007, Cameron Rich
+ * 
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice, 
+ *   this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice, 
+ *   this list of conditions and the following disclaimer in the documentation 
+ *   and/or other materials provided with the distribution.
+ * * Neither the name of the axTLS project nor the names of its contributors 
+ *   may be used to endorse or promote products derived from this software 
+ *   without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef BIGINT_IMPL_HEADER
+#define BIGINT_IMPL_HEADER
+
+/* Maintain a number of precomputed variables when doing reduction */
+#define BIGINT_M_OFFSET     0    /**< Normal modulo offset. */
+#ifdef CONFIG_BIGINT_CRT
+#define BIGINT_P_OFFSET     1    /**< p modulo offset. */
+#define BIGINT_Q_OFFSET     2    /**< q module offset. */
+#define BIGINT_NUM_MODS     3    /**< The number of modulus constants used. */
+#else
+#define BIGINT_NUM_MODS     1    
+#endif
+
+/* Architecture specific functions for big ints */
+#if defined(CONFIG_INTEGER_8BIT)
+#define COMP_RADIX          256U       /**< Max component + 1 */
+#define COMP_MAX            0xFFFFU/**< (Max dbl comp -1) */
+#define COMP_BIT_SIZE       8   /**< Number of bits in a component. */
+#define COMP_BYTE_SIZE      1   /**< Number of bytes in a component. */
+#define COMP_NUM_NIBBLES    2   /**< Used For diagnostics only. */
+typedef uint8_t comp;          /**< A single precision component. */
+typedef uint16_t long_comp;     /**< A double precision component. */
+typedef int16_t slong_comp;     /**< A signed double precision component. */
+#elif defined(CONFIG_INTEGER_16BIT)
+#define COMP_RADIX          65536U       /**< Max component + 1 */
+#define COMP_MAX            0xFFFFFFFFU/**< (Max dbl comp -1) */
+#define COMP_BIT_SIZE       16  /**< Number of bits in a component. */
+#define COMP_BYTE_SIZE      2   /**< Number of bytes in a component. */
+#define COMP_NUM_NIBBLES    4   /**< Used For diagnostics only. */
+typedef uint16_t comp;         /**< A single precision component. */
+typedef uint32_t long_comp;     /**< A double precision component. */
+typedef int32_t slong_comp;     /**< A signed double precision component. */
+#else /* regular 32 bit */
+#if defined(WIN32) && !defined(__GNUC__)
+#define COMP_RADIX          4294967296i64         
+#define COMP_MAX            0xFFFFFFFFFFFFFFFFui64
+#else
+#define COMP_RADIX          4294967296ULL         /**< Max component + 1 */
+#define COMP_MAX            0xFFFFFFFFFFFFFFFFULL/**< (Max dbl comp -1) */
+#endif
+#define COMP_BIT_SIZE       32  /**< Number of bits in a component. */
+#define COMP_BYTE_SIZE      4   /**< Number of bytes in a component. */
+#define COMP_NUM_NIBBLES    8   /**< Used For diagnostics only. */
+typedef uint32_t comp;         /**< A single precision component. */
+typedef uint64_t long_comp;     /**< A double precision component. */
+typedef int64_t slong_comp;     /**< A signed double precision component. */
+#endif
+
+/**
+ * @struct  _bigint
+ * @brief A big integer basic object
+ */
+struct _bigint
+{
+    struct _bigint* next;       /**< The next bigint in the cache. */
+    short size;                 /**< The number of components in this bigint. */
+    short max_comps;            /**< The heapsize allocated for this bigint */
+    int refs;                   /**< An internal reference count. */
+    comp* comps;                /**< A ptr to the actual component data */
+};
+
+typedef struct _bigint bigint;  /**< An alias for _bigint */
+
+/**
+ * Maintains the state of the cache, and a number of variables used in 
+ * reduction.
+ */
+typedef struct /**< A big integer "session" context. */
+{
+    bigint *active_list;                    /**< Bigints currently used. */
+    bigint *free_list;                      /**< Bigints not used. */
+    bigint *bi_radix;                       /**< The radix used. */
+    bigint *bi_mod[BIGINT_NUM_MODS];        /**< modulus */
+
+#if defined(CONFIG_BIGINT_MONTGOMERY)
+    bigint *bi_RR_mod_m[BIGINT_NUM_MODS];   /**< R^2 mod m */
+    bigint *bi_R_mod_m[BIGINT_NUM_MODS];    /**< R mod m */
+    comp N0_dash[BIGINT_NUM_MODS];
+#elif defined(CONFIG_BIGINT_BARRETT)
+    bigint *bi_mu[BIGINT_NUM_MODS];         /**< Storage for mu */
+#endif
+    bigint *bi_normalised_mod[BIGINT_NUM_MODS]; /**< Normalised mod storage. */
+    bigint **g;                 /**< Used by sliding-window. */
+    int window;                 /**< The size of the sliding window */
+    int active_count;           /**< Number of active bigints. */
+    int free_count;             /**< Number of free bigints. */
+
+#ifdef CONFIG_BIGINT_MONTGOMERY
+    uint8_t use_classical;      /**< Use classical reduction. */
+#endif
+    uint8_t mod_offset;         /**< The mod offset we are using */
+} BI_CTX;
+
+#ifndef WIN32
+#define max(a,b) ((a)>(b)?(a):(b))  /**< Find the maximum of 2 numbers. */
+#define min(a,b) ((a)<(b)?(a):(b))  /**< Find the minimum of 2 numbers. */
+#endif
+
+#define PERMANENT           0x7FFF55AA  /**< A magic number for permanents. */
+
+#endif
diff --git a/src/crypto/config.h b/src/crypto/config.h
new file mode 100644 (file)
index 0000000..8da9dc2
--- /dev/null
@@ -0,0 +1,6 @@
+
+#define CONFIG_BIGINT_BARRETT 1
+#define CONFIG_BIGINT_CRT 1
+#define CONFIG_BIGINT_SQUARE 1
+#define CONFIG_BIGINT_32BIT 1
+
diff --git a/src/crypto/crypto.h b/src/crypto/crypto.h
new file mode 100644 (file)
index 0000000..a1c6ada
--- /dev/null
@@ -0,0 +1,146 @@
+/*
+ * Copyright (c) 2007, Cameron Rich
+ * 
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice, 
+ *   this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice, 
+ *   this list of conditions and the following disclaimer in the documentation 
+ *   and/or other materials provided with the distribution.
+ * * Neither the name of the axTLS project nor the names of its contributors 
+ *   may be used to endorse or promote products derived from this software 
+ *   without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * @file crypto.h
+ */
+
+#ifndef HEADER_CRYPTO_H
+#define HEADER_CRYPTO_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "config.h"
+#include "bigint_impl.h"
+#include "bigint.h"
+
+#ifndef STDCALL
+#define STDCALL
+#endif
+#ifndef EXP_FUNC
+#define EXP_FUNC
+#endif
+
+/**************************************************************************
+ * AES declarations 
+ **************************************************************************/
+
+#define AES_MAXROUNDS                  14
+#define AES_BLOCKSIZE           16
+#define AES_IV_SIZE             16
+
+typedef struct aes_key_st 
+{
+    uint16_t rounds;
+    uint16_t key_size;
+    uint32_t ks[(AES_MAXROUNDS+1)*8];
+    uint8_t iv[AES_IV_SIZE];
+} AES_CTX;
+
+typedef enum
+{
+    AES_MODE_128,
+    AES_MODE_256
+} AES_MODE;
+
+void AES_set_key(AES_CTX *ctx, const uint8_t *key, 
+        const uint8_t *iv, AES_MODE mode);
+void AES_cbc_encrypt(AES_CTX *ctx, const uint8_t *msg, 
+        uint8_t *out, int length);
+void AES_cbc_decrypt(AES_CTX *ks, const uint8_t *in, uint8_t *out, int length);
+void AES_convert_key(AES_CTX *ctx);
+
+/**************************************************************************
+ * RC4 declarations 
+ **************************************************************************/
+
+typedef struct 
+{
+    uint8_t x, y, m[256];
+} RC4_CTX;
+
+void RC4_setup(RC4_CTX *s, const uint8_t *key, int length);
+void RC4_crypt(RC4_CTX *s, const uint8_t *msg, uint8_t *data, int length);
+
+/**************************************************************************
+ * SHA1 declarations 
+ **************************************************************************/
+
+#define SHA1_SIZE   20
+
+/*
+ *  This structure will hold context information for the SHA-1
+ *  hashing operation
+ */
+typedef struct 
+{
+    uint32_t Intermediate_Hash[SHA1_SIZE/4]; /* Message Digest */
+    uint32_t Length_Low;            /* Message length in bits */
+    uint32_t Length_High;           /* Message length in bits */
+    uint16_t Message_Block_Index;   /* Index into message block array   */
+    uint8_t Message_Block[64];      /* 512-bit message blocks */
+} SHA1_CTX;
+
+void SHA1_Init(SHA1_CTX *);
+void SHA1_Update(SHA1_CTX *, const uint8_t * msg, int len);
+void SHA1_Final(uint8_t *digest, SHA1_CTX *);
+
+/**************************************************************************
+ * MD5 declarations 
+ **************************************************************************/
+
+#define MD5_SIZE    16
+
+typedef struct 
+{
+  uint32_t state[4];        /* state (ABCD) */
+  uint32_t count[2];        /* number of bits, modulo 2^64 (lsb first) */
+  uint8_t buffer[64];       /* input buffer */
+} MD5_CTX;
+
+EXP_FUNC void STDCALL MD5_Init(MD5_CTX *);
+EXP_FUNC void STDCALL MD5_Update(MD5_CTX *, const uint8_t *msg, int len);
+EXP_FUNC void STDCALL MD5_Final(uint8_t *digest, MD5_CTX *);
+
+/**************************************************************************
+ * HMAC declarations 
+ **************************************************************************/
+void hmac_md5(const uint8_t *msg, int length, const uint8_t *key, 
+        int key_len, uint8_t *digest);
+void hmac_sha1(const uint8_t *msg, int length, const uint8_t *key, 
+        int key_len, uint8_t *digest);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif 
diff --git a/src/crypto/hmac.c b/src/crypto/hmac.c
new file mode 100644 (file)
index 0000000..24a04d7
--- /dev/null
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2007, Cameron Rich
+ * 
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice, 
+ *   this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice, 
+ *   this list of conditions and the following disclaimer in the documentation 
+ *   and/or other materials provided with the distribution.
+ * * Neither the name of the axTLS project nor the names of its contributors 
+ *   may be used to endorse or promote products derived from this software 
+ *   without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * HMAC implementation - This code was originally taken from RFC2104
+ * See http://www.ietf.org/rfc/rfc2104.txt and
+ * http://www.faqs.org/rfcs/rfc2202.html
+ */
+
+#include <string.h>
+#include "os_port.h"
+#include "crypto.h"
+
+/**
+ * Perform HMAC-MD5
+ * NOTE: does not handle keys larger than the block size.
+ */
+void hmac_md5(const uint8_t *msg, int length, const uint8_t *key, 
+        int key_len, uint8_t *digest)
+{
+    MD5_CTX context;
+    uint8_t k_ipad[64];
+    uint8_t k_opad[64];
+    int i;
+
+    memset(k_ipad, 0, sizeof k_ipad);
+    memset(k_opad, 0, sizeof k_opad);
+    memcpy(k_ipad, key, key_len);
+    memcpy(k_opad, key, key_len);
+
+    for (i = 0; i < 64; i++) 
+    {
+        k_ipad[i] ^= 0x36;
+        k_opad[i] ^= 0x5c;
+    }
+
+    MD5_Init(&context);
+    MD5_Update(&context, k_ipad, 64);
+    MD5_Update(&context, msg, length);
+    MD5_Final(digest, &context);
+    MD5_Init(&context);
+    MD5_Update(&context, k_opad, 64);
+    MD5_Update(&context, digest, MD5_SIZE);
+    MD5_Final(digest, &context);
+}
+
+/**
+ * Perform HMAC-SHA1
+ * NOTE: does not handle keys larger than the block size.
+ */
+void hmac_sha1(const uint8_t *msg, int length, const uint8_t *key, 
+        int key_len, uint8_t *digest)
+{
+    SHA1_CTX context;
+    uint8_t k_ipad[64];
+    uint8_t k_opad[64];
+    int i;
+
+    memset(k_ipad, 0, sizeof k_ipad);
+    memset(k_opad, 0, sizeof k_opad);
+    memcpy(k_ipad, key, key_len);
+    memcpy(k_opad, key, key_len);
+
+    for (i = 0; i < 64; i++) 
+    {
+        k_ipad[i] ^= 0x36;
+        k_opad[i] ^= 0x5c;
+    }
+
+    SHA1_Init(&context);
+    SHA1_Update(&context, k_ipad, 64);
+    SHA1_Update(&context, msg, length);
+    SHA1_Final(digest, &context);
+    SHA1_Init(&context);
+    SHA1_Update(&context, k_opad, 64);
+    SHA1_Update(&context, digest, SHA1_SIZE);
+    SHA1_Final(digest, &context);
+}
diff --git a/src/crypto/md5.c b/src/crypto/md5.c
new file mode 100644 (file)
index 0000000..7f50713
--- /dev/null
@@ -0,0 +1,294 @@
+/*
+ * Copyright (c) 2007, Cameron Rich
+ * 
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice, 
+ *   this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice, 
+ *   this list of conditions and the following disclaimer in the documentation 
+ *   and/or other materials provided with the distribution.
+ * * Neither the name of the axTLS project nor the names of its contributors 
+ *   may be used to endorse or promote products derived from this software 
+ *   without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * This file implements the MD5 algorithm as defined in RFC1321
+ */
+
+#include <string.h>
+#include "os_port.h"
+#include "crypto.h"
+
+/* Constants for MD5Transform routine.
+ */
+#define S11 7
+#define S12 12
+#define S13 17
+#define S14 22
+#define S21 5
+#define S22 9
+#define S23 14
+#define S24 20
+#define S31 4
+#define S32 11
+#define S33 16
+#define S34 23
+#define S41 6
+#define S42 10
+#define S43 15
+#define S44 21
+
+/* ----- static functions ----- */
+static void MD5Transform(uint32_t state[4], const uint8_t block[64]);
+static void Encode(uint8_t *output, uint32_t *input, uint32_t len);
+static void Decode(uint32_t *output, const uint8_t *input, uint32_t len);
+
+static const uint8_t PADDING[64] = 
+{
+    0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+/* F, G, H and I are basic MD5 functions.
+ */
+#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
+#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
+#define H(x, y, z) ((x) ^ (y) ^ (z))
+#define I(x, y, z) ((y) ^ ((x) | (~z)))
+
+/* ROTATE_LEFT rotates x left n bits.  */
+#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
+
+/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
+   Rotation is separate from addition to prevent recomputation.  */
+#define FF(a, b, c, d, x, s, ac) { \
+    (a) += F ((b), (c), (d)) + (x) + (uint32_t)(ac); \
+    (a) = ROTATE_LEFT ((a), (s)); \
+    (a) += (b); \
+  }
+#define GG(a, b, c, d, x, s, ac) { \
+    (a) += G ((b), (c), (d)) + (x) + (uint32_t)(ac); \
+    (a) = ROTATE_LEFT ((a), (s)); \
+    (a) += (b); \
+  }
+#define HH(a, b, c, d, x, s, ac) { \
+    (a) += H ((b), (c), (d)) + (x) + (uint32_t)(ac); \
+    (a) = ROTATE_LEFT ((a), (s)); \
+    (a) += (b); \
+  }
+#define II(a, b, c, d, x, s, ac) { \
+    (a) += I ((b), (c), (d)) + (x) + (uint32_t)(ac); \
+    (a) = ROTATE_LEFT ((a), (s)); \
+    (a) += (b); \
+  }
+
+/**
+ * MD5 initialization - begins an MD5 operation, writing a new ctx.
+ */
+EXP_FUNC void STDCALL MD5_Init(MD5_CTX *ctx)
+{
+    ctx->count[0] = ctx->count[1] = 0;
+
+    /* Load magic initialization constants.
+     */
+    ctx->state[0] = 0x67452301;
+    ctx->state[1] = 0xefcdab89;
+    ctx->state[2] = 0x98badcfe;
+    ctx->state[3] = 0x10325476;
+}
+
+/**
+ * Accepts an array of octets as the next portion of the message.
+ */
+EXP_FUNC void STDCALL MD5_Update(MD5_CTX *ctx, const uint8_t * msg, int len)
+{
+    uint32_t x;
+    int i, partLen;
+
+    /* Compute number of bytes mod 64 */
+    x = (uint32_t)((ctx->count[0] >> 3) & 0x3F);
+
+    /* Update number of bits */
+    if ((ctx->count[0] += ((uint32_t)len << 3)) < ((uint32_t)len << 3))
+        ctx->count[1]++;
+    ctx->count[1] += ((uint32_t)len >> 29);
+
+    partLen = 64 - x;
+
+    /* Transform as many times as possible.  */
+    if (len >= partLen) 
+    {
+        memcpy(&ctx->buffer[x], msg, partLen);
+        MD5Transform(ctx->state, ctx->buffer);
+
+        for (i = partLen; i + 63 < len; i += 64)
+            MD5Transform(ctx->state, &msg[i]);
+
+        x = 0;
+    }
+    else
+        i = 0;
+
+    /* Buffer remaining input */
+    memcpy(&ctx->buffer[x], &msg[i], len-i);
+}
+
+/**
+ * Return the 128-bit message digest into the user's array
+ */
+EXP_FUNC void STDCALL MD5_Final(uint8_t *digest, MD5_CTX *ctx)
+{
+    uint8_t bits[8];
+    uint32_t x, padLen;
+
+    /* Save number of bits */
+    Encode(bits, ctx->count, 8);
+
+    /* Pad out to 56 mod 64.
+     */
+    x = (uint32_t)((ctx->count[0] >> 3) & 0x3f);
+    padLen = (x < 56) ? (56 - x) : (120 - x);
+    MD5_Update(ctx, PADDING, padLen);
+
+    /* Append length (before padding) */
+    MD5_Update(ctx, bits, 8);
+
+    /* Store state in digest */
+    Encode(digest, ctx->state, MD5_SIZE);
+}
+
+/**
+ * MD5 basic transformation. Transforms state based on block.
+ */
+static void MD5Transform(uint32_t state[4], const uint8_t block[64])
+{
+    uint32_t a = state[0], b = state[1], c = state[2], 
+             d = state[3], x[MD5_SIZE];
+
+    Decode(x, block, 64);
+
+    /* Round 1 */
+    FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
+    FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
+    FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
+    FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
+    FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
+    FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
+    FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
+    FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
+    FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
+    FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
+    FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
+    FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
+    FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
+    FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
+    FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
+    FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
+
+    /* Round 2 */
+    GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
+    GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
+    GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
+    GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
+    GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
+    GG (d, a, b, c, x[10], S22,  0x2441453); /* 22 */
+    GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
+    GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
+    GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
+    GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
+    GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
+    GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
+    GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
+    GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
+    GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
+    GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
+
+    /* Round 3 */
+    HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
+    HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
+    HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
+    HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
+    HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
+    HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
+    HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
+    HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
+    HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
+    HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
+    HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
+    HH (b, c, d, a, x[ 6], S34,  0x4881d05); /* 44 */
+    HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
+    HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
+    HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
+    HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
+
+    /* Round 4 */
+    II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
+    II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
+    II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
+    II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
+    II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
+    II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
+    II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
+    II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
+    II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
+    II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
+    II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
+    II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
+    II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
+    II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
+    II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
+    II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
+
+    state[0] += a;
+    state[1] += b;
+    state[2] += c;
+    state[3] += d;
+}
+
+/**
+ * Encodes input (uint32_t) into output (uint8_t). Assumes len is
+ *   a multiple of 4.
+ */
+static void Encode(uint8_t *output, uint32_t *input, uint32_t len)
+{
+    uint32_t i, j;
+
+    for (i = 0, j = 0; j < len; i++, j += 4) 
+    {
+        output[j] = (uint8_t)(input[i] & 0xff);
+        output[j+1] = (uint8_t)((input[i] >> 8) & 0xff);
+        output[j+2] = (uint8_t)((input[i] >> 16) & 0xff);
+        output[j+3] = (uint8_t)((input[i] >> 24) & 0xff);
+    }
+}
+
+/**
+ *  Decodes input (uint8_t) into output (uint32_t). Assumes len is
+ *   a multiple of 4.
+ */
+static void Decode(uint32_t *output, const uint8_t *input, uint32_t len)
+{
+    uint32_t i, j;
+
+    for (i = 0, j = 0; j < len; i++, j += 4)
+        output[i] = ((uint32_t)input[j]) | (((uint32_t)input[j+1]) << 8) |
+            (((uint32_t)input[j+2]) << 16) | (((uint32_t)input[j+3]) << 24);
+}
diff --git a/src/crypto/os_port.h b/src/crypto/os_port.h
new file mode 100644 (file)
index 0000000..80c09e8
--- /dev/null
@@ -0,0 +1,160 @@
+/*
+ * Copyright (c) 2007, Cameron Rich
+ * 
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice, 
+ *   this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice, 
+ *   this list of conditions and the following disclaimer in the documentation 
+ *   and/or other materials provided with the distribution.
+ * * Neither the name of the axTLS project nor the names of its contributors 
+ *   may be used to endorse or promote products derived from this software 
+ *   without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * @file os_port.h
+ *
+ * Some stuff to minimise the differences between windows and linux/unix
+ */
+
+#ifndef HEADER_OS_PORT_H
+#define HEADER_OS_PORT_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdio.h>
+
+#if defined(WIN32)
+#define STDCALL                 __stdcall
+#define EXP_FUNC                __declspec(dllexport)
+#else
+#define STDCALL
+#define EXP_FUNC
+#endif
+
+#if defined(_WIN32_WCE)
+#undef WIN32
+#define WIN32
+#endif
+
+#ifdef WIN32
+
+/* Windows CE stuff */
+#if defined(_WIN32_WCE)
+#include <basetsd.h>
+#define abort()                 exit(1)
+#else
+#include <io.h>
+#include <process.h>
+#include <sys/timeb.h>
+#include <fcntl.h>
+#endif      /* _WIN32_WCE */
+
+#include <winsock.h>
+#include <direct.h>
+#undef getpid
+#undef open
+#undef close
+#undef sleep
+#undef gettimeofday
+#undef dup2
+#undef unlink
+
+#define SOCKET_READ(A,B,C)      recv(A,B,C,0)
+#define SOCKET_WRITE(A,B,C)     send(A,B,C,0)
+#define SOCKET_CLOSE(A)         closesocket(A)
+#define srandom(A)              srand(A)
+#define random()                rand()
+#define getpid()                _getpid()
+#define snprintf                _snprintf
+#define open(A,B)               _open(A,B)
+#define dup2(A,B)               _dup2(A,B)
+#define unlink(A)               _unlink(A)
+#define close(A)                _close(A)
+#define read(A,B,C)             _read(A,B,C)
+#define write(A,B,C)            _write(A,B,C)
+#define sleep(A)                Sleep(A*1000)
+#define usleep(A)               Sleep(A/1000)
+#define strdup(A)               _strdup(A)
+#define chroot(A)               _chdir(A)
+#define chdir(A)                _chdir(A)
+#define alloca(A)               _alloca(A)
+#ifndef lseek
+#define lseek(A,B,C)            _lseek(A,B,C)
+#endif
+
+/* This fix gets around a problem where a win32 application on a cygwin xterm
+   doesn't display regular output (until a certain buffer limit) - but it works
+   fine under a normal DOS window. This is a hack to get around the issue - 
+   see http://www.khngai.com/emacs/tty.php  */
+#define TTY_FLUSH()             if (!_isatty(_fileno(stdout))) fflush(stdout);
+
+/*
+typedef UINT8 uint8_t;
+typedef INT8 int8_t;
+typedef UINT16 uint16_t;
+typedef INT16 int16_t;
+typedef UINT32 uint32_t;
+typedef INT32 int32_t;
+typedef UINT64 uint64_t;
+typedef INT64 int64_t;
+typedef int socklen_t;
+*/
+
+#else   /* Not Win32 */
+
+#ifdef __sun__
+#include <inttypes.h>
+#else
+#include <stdint.h>
+#endif /* Not Solaris */
+
+#include <unistd.h>
+#include <pwd.h>
+#include <netdb.h>
+#include <dirent.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/socket.h>
+#include <sys/wait.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+#define SOCKET_READ(A,B,C)      read(A,B,C)
+#define SOCKET_WRITE(A,B,C)     write(A,B,C)
+#define SOCKET_CLOSE(A)         if (A >= 0) close(A)
+#define TTY_FLUSH()
+
+#endif  /* Not Win32 */
+
+/* some functions to mutate the way these work */
+#define ax_malloc(A)    malloc(A)
+#define ax_realloc(A)   realloc(A)
+#define ax_calloc(A)    calloc(A)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif 
diff --git a/src/crypto/rc4.c b/src/crypto/rc4.c
new file mode 100644 (file)
index 0000000..12a1211
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2007, Cameron Rich
+ * 
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice, 
+ *   this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice, 
+ *   this list of conditions and the following disclaimer in the documentation 
+ *   and/or other materials provided with the distribution.
+ * * Neither the name of the axTLS project nor the names of its contributors 
+ *   may be used to endorse or promote products derived from this software 
+ *   without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * An implementation of the RC4/ARC4 algorithm.
+ * Originally written by Christophe Devine.
+ */
+
+#include <string.h>
+#include "os_port.h"
+#include "crypto.h"
+
+/**
+ * Get ready for an encrypt/decrypt operation
+ */
+void RC4_setup(RC4_CTX *ctx, const uint8_t *key, int length)
+{
+    int i, j = 0, k = 0, a;
+    uint8_t *m;
+
+    ctx->x = 0;
+    ctx->y = 0;
+    m = ctx->m;
+
+    for (i = 0; i < 256; i++)
+        m[i] = i;
+
+    for (i = 0; i < 256; i++)
+    {
+        a = m[i];
+        j = (uint8_t)(j + a + key[k]);
+        m[i] = m[j]; 
+        m[j] = a;
+
+        if (++k >= length) 
+            k = 0;
+    }
+}
+
+/**
+ * Perform the encrypt/decrypt operation (can use it for either since
+ * this is a stream cipher).
+ * NOTE: *msg and *out must be the same pointer (performance tweak)
+ */
+void RC4_crypt(RC4_CTX *ctx, const uint8_t *msg, uint8_t *out, int length)
+{ 
+    int i;
+    uint8_t *m, x, y, a, b;
+
+    x = ctx->x;
+    y = ctx->y;
+    m = ctx->m;
+
+    for (i = 0; i < length; i++)
+    {
+        a = m[++x];
+        y += a;
+        m[x] = b = m[y];
+        m[y] = a;
+        out[i] ^= m[(uint8_t)(a + b)];
+    }
+
+    ctx->x = x;
+    ctx->y = y;
+}
diff --git a/src/crypto/sha1.c b/src/crypto/sha1.c
new file mode 100644 (file)
index 0000000..1082733
--- /dev/null
@@ -0,0 +1,249 @@
+/*
+ * Copyright (c) 2007, Cameron Rich
+ * 
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice, 
+ *   this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice, 
+ *   this list of conditions and the following disclaimer in the documentation 
+ *   and/or other materials provided with the distribution.
+ * * Neither the name of the axTLS project nor the names of its contributors 
+ *   may be used to endorse or promote products derived from this software 
+ *   without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * SHA1 implementation - as defined in FIPS PUB 180-1 published April 17, 1995.
+ * This code was originally taken from RFC3174
+ */
+
+#include <string.h>
+#include "os_port.h"
+#include "crypto.h"
+
+/*
+ *  Define the SHA1 circular left shift macro
+ */
+#define SHA1CircularShift(bits,word) \
+                (((word) << (bits)) | ((word) >> (32-(bits))))
+
+/* ----- static functions ----- */
+static void SHA1PadMessage(SHA1_CTX *ctx);
+static void SHA1ProcessMessageBlock(SHA1_CTX *ctx);
+
+/**
+ * Initialize the SHA1 context 
+ */
+void SHA1_Init(SHA1_CTX *ctx)
+{
+    ctx->Length_Low             = 0;
+    ctx->Length_High            = 0;
+    ctx->Message_Block_Index    = 0;
+    ctx->Intermediate_Hash[0]   = 0x67452301;
+    ctx->Intermediate_Hash[1]   = 0xEFCDAB89;
+    ctx->Intermediate_Hash[2]   = 0x98BADCFE;
+    ctx->Intermediate_Hash[3]   = 0x10325476;
+    ctx->Intermediate_Hash[4]   = 0xC3D2E1F0;
+}
+
+/**
+ * Accepts an array of octets as the next portion of the message.
+ */
+void SHA1_Update(SHA1_CTX *ctx, const uint8_t *msg, int len)
+{
+    while (len--)
+    {
+        ctx->Message_Block[ctx->Message_Block_Index++] = (*msg & 0xFF);
+        ctx->Length_Low += 8;
+
+        if (ctx->Length_Low == 0)
+            ctx->Length_High++;
+
+        if (ctx->Message_Block_Index == 64)
+            SHA1ProcessMessageBlock(ctx);
+
+        msg++;
+    }
+}
+
+/**
+ * Return the 160-bit message digest into the user's array
+ */
+void SHA1_Final(uint8_t *digest, SHA1_CTX *ctx)
+{
+    int i;
+
+    SHA1PadMessage(ctx);
+    memset(ctx->Message_Block, 0, 64);
+    ctx->Length_Low = 0;    /* and clear length */
+    ctx->Length_High = 0;
+
+    for  (i = 0; i < SHA1_SIZE; i++)
+    {
+        digest[i] = ctx->Intermediate_Hash[i>>2] >> 8 * ( 3 - ( i & 0x03 ) );
+    }
+}
+
+/**
+ * Process the next 512 bits of the message stored in the array.
+ */
+static void SHA1ProcessMessageBlock(SHA1_CTX *ctx)
+{
+    const uint32_t K[] =    {       /* Constants defined in SHA-1   */
+                            0x5A827999,
+                            0x6ED9EBA1,
+                            0x8F1BBCDC,
+                            0xCA62C1D6
+                            };
+    int        t;                 /* Loop counter                */
+    uint32_t      temp;              /* Temporary word value        */
+    uint32_t      W[80];             /* Word sequence               */
+    uint32_t      A, B, C, D, E;     /* Word buffers                */
+
+    /*
+     *  Initialize the first 16 words in the array W
+     */
+    for  (t = 0; t < 16; t++)
+    {
+        W[t] = ctx->Message_Block[t * 4] << 24;
+        W[t] |= ctx->Message_Block[t * 4 + 1] << 16;
+        W[t] |= ctx->Message_Block[t * 4 + 2] << 8;
+        W[t] |= ctx->Message_Block[t * 4 + 3];
+    }
+
+    for (t = 16; t < 80; t++)
+    {
+       W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]);
+    }
+
+    A = ctx->Intermediate_Hash[0];
+    B = ctx->Intermediate_Hash[1];
+    C = ctx->Intermediate_Hash[2];
+    D = ctx->Intermediate_Hash[3];
+    E = ctx->Intermediate_Hash[4];
+
+    for (t = 0; t < 20; t++)
+    {
+        temp =  SHA1CircularShift(5,A) +
+                ((B & C) | ((~B) & D)) + E + W[t] + K[0];
+        E = D;
+        D = C;
+        C = SHA1CircularShift(30,B);
+
+        B = A;
+        A = temp;
+    }
+
+    for (t = 20; t < 40; t++)
+    {
+        temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1];
+        E = D;
+        D = C;
+        C = SHA1CircularShift(30,B);
+        B = A;
+        A = temp;
+    }
+
+    for (t = 40; t < 60; t++)
+    {
+        temp = SHA1CircularShift(5,A) +
+               ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2];
+        E = D;
+        D = C;
+        C = SHA1CircularShift(30,B);
+        B = A;
+        A = temp;
+    }
+
+    for (t = 60; t < 80; t++)
+    {
+        temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3];
+        E = D;
+        D = C;
+        C = SHA1CircularShift(30,B);
+        B = A;
+        A = temp;
+    }
+
+    ctx->Intermediate_Hash[0] += A;
+    ctx->Intermediate_Hash[1] += B;
+    ctx->Intermediate_Hash[2] += C;
+    ctx->Intermediate_Hash[3] += D;
+    ctx->Intermediate_Hash[4] += E;
+    ctx->Message_Block_Index = 0;
+}
+
+/*
+ * According to the standard, the message must be padded to an even
+ * 512 bits.  The first padding bit must be a '1'.  The last 64
+ * bits represent the length of the original message.  All bits in
+ * between should be 0.  This function will pad the message
+ * according to those rules by filling the Message_Block array
+ * accordingly.  It will also call the ProcessMessageBlock function
+ * provided appropriately.  When it returns, it can be assumed that
+ * the message digest has been computed.
+ *
+ * @param ctx [in, out] The SHA1 context
+ */
+static void SHA1PadMessage(SHA1_CTX *ctx)
+{
+    /*
+     *  Check to see if the current message block is too small to hold
+     *  the initial padding bits and length.  If so, we will pad the
+     *  block, process it, and then continue padding into a second
+     *  block.
+     */
+    if (ctx->Message_Block_Index > 55)
+    {
+        ctx->Message_Block[ctx->Message_Block_Index++] = 0x80;
+        while(ctx->Message_Block_Index < 64)
+        {
+            ctx->Message_Block[ctx->Message_Block_Index++] = 0;
+        }
+
+        SHA1ProcessMessageBlock(ctx);
+
+        while (ctx->Message_Block_Index < 56)
+        {
+            ctx->Message_Block[ctx->Message_Block_Index++] = 0;
+        }
+    }
+    else
+    {
+        ctx->Message_Block[ctx->Message_Block_Index++] = 0x80;
+        while(ctx->Message_Block_Index < 56)
+        {
+
+            ctx->Message_Block[ctx->Message_Block_Index++] = 0;
+        }
+    }
+
+    /*
+     *  Store the message length as the last 8 octets
+     */
+    ctx->Message_Block[56] = ctx->Length_High >> 24;
+    ctx->Message_Block[57] = ctx->Length_High >> 16;
+    ctx->Message_Block[58] = ctx->Length_High >> 8;
+    ctx->Message_Block[59] = ctx->Length_High;
+    ctx->Message_Block[60] = ctx->Length_Low >> 24;
+    ctx->Message_Block[61] = ctx->Length_Low >> 16;
+    ctx->Message_Block[62] = ctx->Length_Low >> 8;
+    ctx->Message_Block[63] = ctx->Length_Low;
+    SHA1ProcessMessageBlock(ctx);
+}
diff --git a/src/dnssd.c b/src/dnssd.c
new file mode 100644 (file)
index 0000000..96e32dc
--- /dev/null
@@ -0,0 +1,285 @@
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <assert.h>
+
+#include "dnssd.h"
+#include "dnssdint.h"
+#include "global.h"
+#include "compat.h"
+#include "utils.h"
+
+#define MAX_DEVICEID 18
+#define MAX_SERVNAME 256
+
+#ifndef WIN32
+# include <dns_sd.h>
+#else
+# include <stdint.h>
+# if !defined(EFI32) && !defined(EFI64)
+#  define DNSSD_API __stdcall
+# else
+#  define DNSSD_API
+# endif
+
+typedef struct _DNSServiceRef_t *DNSServiceRef;
+typedef union _TXTRecordRef_t { char PrivateData[16]; char *ForceNaturalAlignment; } TXTRecordRef;
+
+typedef uint32_t DNSServiceFlags;
+typedef int32_t  DNSServiceErrorType;
+
+typedef void (DNSSD_API *DNSServiceRegisterReply)
+    (
+    DNSServiceRef                       sdRef,
+    DNSServiceFlags                     flags,
+    DNSServiceErrorType                 errorCode,
+    const char                          *name,
+    const char                          *regtype,
+    const char                          *domain,
+    void                                *context
+    );
+#endif
+
+typedef DNSServiceErrorType (DNSSD_API *DNSServiceRegister_t)
+    (
+    DNSServiceRef                       *sdRef,
+    DNSServiceFlags                     flags,
+    uint32_t                            interfaceIndex,
+    const char                          *name,
+    const char                          *regtype,
+    const char                          *domain,
+    const char                          *host,
+    uint16_t                            port,
+    uint16_t                            txtLen,
+    const void                          *txtRecord,
+    DNSServiceRegisterReply             callBack,
+    void                                *context
+    );
+typedef void (DNSSD_API *DNSServiceRefDeallocate_t)(DNSServiceRef sdRef);
+typedef void (DNSSD_API *TXTRecordCreate_t)
+    (
+    TXTRecordRef     *txtRecord,
+    uint16_t         bufferLen,
+    void             *buffer
+    );
+typedef void (DNSSD_API *TXTRecordDeallocate_t)(TXTRecordRef *txtRecord);
+typedef DNSServiceErrorType (DNSSD_API *TXTRecordSetValue_t)
+    (
+    TXTRecordRef     *txtRecord,
+    const char       *key,
+    uint8_t          valueSize,
+    const void       *value
+    );
+typedef uint16_t (DNSSD_API *TXTRecordGetLength_t)(const TXTRecordRef *txtRecord);
+typedef const void * (DNSSD_API *TXTRecordGetBytesPtr_t)(const TXTRecordRef *txtRecord);
+
+
+struct dnssd_s {
+#ifdef WIN32
+       HMODULE module;
+#endif
+
+       DNSServiceRegister_t       DNSServiceRegister;
+       DNSServiceRefDeallocate_t  DNSServiceRefDeallocate;
+       TXTRecordCreate_t          TXTRecordCreate;
+       TXTRecordSetValue_t        TXTRecordSetValue;
+       TXTRecordGetLength_t       TXTRecordGetLength;
+       TXTRecordGetBytesPtr_t     TXTRecordGetBytesPtr;
+       TXTRecordDeallocate_t      TXTRecordDeallocate;
+
+       char hwaddr[MAX_HWADDR_LEN];
+       int hwaddrlen;
+
+       DNSServiceRef raopService;
+       DNSServiceRef airplayService;
+};
+
+
+
+dnssd_t *
+dnssd_init(const char *hwaddr, int hwaddrlen, int *error)
+{
+       dnssd_t *dnssd;
+
+       if (error) *error = DNSSD_ERROR_NOERROR;
+       if (hwaddrlen > MAX_HWADDR_LEN) {
+               if (error) *error = DNSSD_ERROR_HWADDRLEN;
+               return NULL;
+       }
+
+       dnssd = calloc(1, sizeof(dnssd_t));
+       if (!dnssd) {
+               if (error) *error = DNSSD_ERROR_OUTOFMEM;
+               return NULL;
+       }
+
+#ifdef WIN32
+       dnssd->module = LoadLibraryA("dnssd.dll");
+       if (!dnssd->module) {
+               if (error) *error = DNSSD_ERROR_LIBNOTFOUND;
+               free(dnssd);
+               return NULL;
+       }
+       dnssd->DNSServiceRegister = (DNSServiceRegister_t)GetProcAddress(dnssd->module, "DNSServiceRegister");
+       dnssd->DNSServiceRefDeallocate = (DNSServiceRefDeallocate_t)GetProcAddress(dnssd->module, "DNSServiceRefDeallocate");
+       dnssd->TXTRecordCreate = (TXTRecordCreate_t)GetProcAddress(dnssd->module, "TXTRecordCreate");
+       dnssd->TXTRecordSetValue = (TXTRecordSetValue_t)GetProcAddress(dnssd->module, "TXTRecordSetValue");
+       dnssd->TXTRecordGetLength = (TXTRecordGetLength_t)GetProcAddress(dnssd->module, "TXTRecordGetLength");
+       dnssd->TXTRecordGetBytesPtr = (TXTRecordGetBytesPtr_t)GetProcAddress(dnssd->module, "TXTRecordGetBytesPtr");
+       dnssd->TXTRecordDeallocate = (TXTRecordDeallocate_t)GetProcAddress(dnssd->module, "TXTRecordDeallocate");
+
+       if (!dnssd->DNSServiceRegister || !dnssd->DNSServiceRefDeallocate || !dnssd->TXTRecordCreate ||
+           !dnssd->TXTRecordSetValue || !dnssd->TXTRecordGetLength || !dnssd->TXTRecordGetBytesPtr ||
+           !dnssd->TXTRecordDeallocate) {
+               if (error) *error = DNSSD_ERROR_PROCNOTFOUND;
+               FreeLibrary(dnssd->module);
+               free(dnssd);
+               return NULL;
+       }
+#else
+       dnssd->DNSServiceRegister = &DNSServiceRegister;
+       dnssd->DNSServiceRefDeallocate = &DNSServiceRefDeallocate;
+       dnssd->TXTRecordCreate = &TXTRecordCreate;
+       dnssd->TXTRecordSetValue = &TXTRecordSetValue;
+       dnssd->TXTRecordGetLength = &TXTRecordGetLength;
+       dnssd->TXTRecordGetBytesPtr = &TXTRecordGetBytesPtr;
+       dnssd->TXTRecordDeallocate = &TXTRecordDeallocate;
+#endif
+
+       memcpy(dnssd->hwaddr, hwaddr, hwaddrlen);
+       dnssd->hwaddrlen = hwaddrlen;
+
+       return dnssd;
+}
+
+void
+dnssd_destroy(dnssd_t *dnssd)
+{
+       if (dnssd) {
+#ifdef WIN32
+               FreeLibrary(dnssd->module);
+#endif
+               free(dnssd);
+       }
+}
+
+int
+dnssd_register_raop(dnssd_t *dnssd, const char *name, unsigned short port)
+{
+       TXTRecordRef txtRecord;
+       char servname[MAX_SERVNAME];
+       int ret;
+
+       assert(dnssd);
+
+       dnssd->TXTRecordCreate(&txtRecord, 0, NULL);
+       dnssd->TXTRecordSetValue(&txtRecord, "txtvers", strlen(RAOP_TXTVERS), RAOP_TXTVERS);
+       dnssd->TXTRecordSetValue(&txtRecord, "ch", strlen(RAOP_CH), RAOP_CH);
+       dnssd->TXTRecordSetValue(&txtRecord, "cn", strlen(RAOP_CN), RAOP_CN);
+       dnssd->TXTRecordSetValue(&txtRecord, "et", strlen(RAOP_ET), RAOP_ET);
+       dnssd->TXTRecordSetValue(&txtRecord, "sv", strlen(RAOP_SV), RAOP_SV);
+       dnssd->TXTRecordSetValue(&txtRecord, "da", strlen(RAOP_DA), RAOP_DA);
+       dnssd->TXTRecordSetValue(&txtRecord, "sr", strlen(RAOP_SR), RAOP_SR);
+       dnssd->TXTRecordSetValue(&txtRecord, "ss", strlen(RAOP_SS), RAOP_SS);
+       dnssd->TXTRecordSetValue(&txtRecord, "pw", strlen(RAOP_PW), RAOP_PW);
+       dnssd->TXTRecordSetValue(&txtRecord, "vn", strlen(RAOP_VN), RAOP_VN);
+       dnssd->TXTRecordSetValue(&txtRecord, "tp", strlen(RAOP_TP), RAOP_TP);
+       dnssd->TXTRecordSetValue(&txtRecord, "md", strlen(RAOP_MD), RAOP_MD);
+       dnssd->TXTRecordSetValue(&txtRecord, "vs", strlen(GLOBAL_VERSION), GLOBAL_VERSION);
+       dnssd->TXTRecordSetValue(&txtRecord, "am", strlen(RAOP_AM), RAOP_AM);
+       dnssd->TXTRecordSetValue(&txtRecord, "sf", strlen(RAOP_SF), RAOP_SF);
+
+       /* Convert hardware address to string */
+       ret = utils_hwaddr_raop(servname, sizeof(servname), dnssd->hwaddr, dnssd->hwaddrlen);
+       if (ret < 0) {
+               /* FIXME: handle better */
+               return -1;
+       }
+
+       /* Check that we have bytes for 'hw@name' format */
+       if (sizeof(servname) < strlen(servname)+1+strlen(name)+1) {
+               /* FIXME: handle better */
+               return -2;
+       }
+
+       strncat(servname, "@", sizeof(servname)-strlen(servname)-1);
+       strncat(servname, name, sizeof(servname)-strlen(servname)-1);
+
+       /* Register the service */
+       dnssd->DNSServiceRegister(&dnssd->raopService, 0, 0,
+                                 servname, "_raop._tcp",
+                                 NULL, NULL,
+                                 htons(port),
+                                 dnssd->TXTRecordGetLength(&txtRecord),
+                                 dnssd->TXTRecordGetBytesPtr(&txtRecord),
+                                 NULL, NULL);
+
+       /* Deallocate TXT record */
+       dnssd->TXTRecordDeallocate(&txtRecord);
+       return 1;
+}
+
+int
+dnssd_register_airplay(dnssd_t *dnssd, const char *name, unsigned short port)
+{
+       TXTRecordRef txtRecord;
+       char deviceid[3*MAX_HWADDR_LEN];
+       char features[16];
+       int ret;
+
+       assert(dnssd);
+
+       /* Convert hardware address to string */
+       ret = utils_hwaddr_airplay(deviceid, sizeof(deviceid), dnssd->hwaddr, dnssd->hwaddrlen);
+       if (ret < 0) {
+               /* FIXME: handle better */
+               return -1;
+       }
+
+       features[sizeof(features)-1] = '\0';
+       snprintf(features, sizeof(features)-1, "0x%x", GLOBAL_FEATURES);
+
+       dnssd->TXTRecordCreate(&txtRecord, 0, NULL);
+       dnssd->TXTRecordSetValue(&txtRecord, "deviceid", strlen(deviceid), deviceid);
+       dnssd->TXTRecordSetValue(&txtRecord, "features", strlen(features), features);
+       dnssd->TXTRecordSetValue(&txtRecord, "model", strlen(GLOBAL_MODEL), GLOBAL_MODEL);
+
+       /* Register the service */
+       dnssd->DNSServiceRegister(&dnssd->airplayService, 0, 0,
+                                 name, "_airplay._tcp",
+                                 NULL, NULL,
+                                 htons(port),
+                                 dnssd->TXTRecordGetLength(&txtRecord),
+                                 dnssd->TXTRecordGetBytesPtr(&txtRecord),
+                                 NULL, NULL);
+
+       /* Deallocate TXT record */
+       dnssd->TXTRecordDeallocate(&txtRecord);
+       return 0;
+}
+
+void
+dnssd_unregister_raop(dnssd_t *dnssd)
+{
+       assert(dnssd);
+
+       if (!dnssd->raopService) {
+               return;
+       }
+
+       dnssd->DNSServiceRefDeallocate(dnssd->raopService);
+       dnssd->raopService = NULL;
+}
+
+void
+dnssd_unregister_airplay(dnssd_t *dnssd)
+{
+       assert(dnssd);
+
+       if (!dnssd->airplayService) {
+               return;
+       }
+
+       dnssd->DNSServiceRefDeallocate(dnssd->airplayService);
+       dnssd->airplayService = NULL;
+}
diff --git a/src/dnssd.m b/src/dnssd.m
new file mode 100644 (file)
index 0000000..1335a73
--- /dev/null
@@ -0,0 +1,164 @@
+#include <stdlib.h>
+
+#include "dnssd.h"
+#include "dnssdint.h"
+#include "global.h"
+#include "utils.h"
+
+#import <Foundation/Foundation.h>
+
+#define MAX_SERVNAME 256
+
+struct dnssd_s {
+       char hwaddr[MAX_HWADDR_LEN];
+       int hwaddrlen;
+
+       NSNetService *raopService;
+       NSNetService *airplayService;
+};
+
+dnssd_t *
+dnssd_init(const char *hwaddr, int hwaddrlen, int *error)
+{
+       dnssd_t *dnssd;
+
+       if (error) *error = DNSSD_ERROR_NOERROR;
+       if (hwaddrlen > MAX_HWADDR_LEN) {
+               if (error) *error = DNSSD_ERROR_HWADDRLEN;
+               return NULL;
+       }
+
+       dnssd = calloc(1, sizeof(dnssd_t));
+       if (!dnssd) {
+               if (error) *error = DNSSD_ERROR_OUTOFMEM;
+               return NULL;
+       }
+       memcpy(dnssd->hwaddr, hwaddr, hwaddrlen);
+       dnssd->hwaddrlen = hwaddrlen;
+
+       return dnssd;
+}
+
+void
+dnssd_destroy(dnssd_t *dnssd)
+{
+       free(dnssd);
+}
+
+int
+dnssd_register_raop(dnssd_t *dnssd, const char *name, unsigned short port)
+{
+       char hwaddrstr[MAX_SERVNAME];
+       NSString *serviceString;
+       NSMutableDictionary *txtDict;
+       NSData *txtData;
+       int ret;
+
+       assert(dnssd);
+
+       if (dnssd->raopService != nil) {
+               return -1;
+       }
+
+       /* Convert the hardware address to string */
+       ret = utils_hwaddr_raop(hwaddrstr, sizeof(hwaddrstr), dnssd->hwaddr, dnssd->hwaddrlen);
+       if (ret < 0) {
+               return -2;
+       }
+       serviceString = [NSString stringWithFormat:@"%s@%s", hwaddrstr, name];
+
+       txtDict = [NSMutableDictionary dictionaryWithCapacity:0];
+       [txtDict setValue:[NSString stringWithUTF8String:RAOP_TXTVERS] forKey:@"txtvers"];
+       [txtDict setValue:[NSString stringWithUTF8String:RAOP_CH] forKey:@"ch"];
+       [txtDict setValue:[NSString stringWithUTF8String:RAOP_CN] forKey:@"cn"];
+       [txtDict setValue:[NSString stringWithUTF8String:RAOP_ET] forKey:@"et"];
+       [txtDict setValue:[NSString stringWithUTF8String:RAOP_SV] forKey:@"sv"];
+       [txtDict setValue:[NSString stringWithUTF8String:RAOP_DA] forKey:@"da"];
+       [txtDict setValue:[NSString stringWithUTF8String:RAOP_SR] forKey:@"sr"];
+       [txtDict setValue:[NSString stringWithUTF8String:RAOP_SS] forKey:@"ss"];
+       [txtDict setValue:[NSString stringWithUTF8String:RAOP_PW] forKey:@"pw"];
+       [txtDict setValue:[NSString stringWithUTF8String:RAOP_VN] forKey:@"vn"];
+       [txtDict setValue:[NSString stringWithUTF8String:RAOP_TP] forKey:@"tp"];
+       [txtDict setValue:[NSString stringWithUTF8String:RAOP_MD] forKey:@"md"];
+       [txtDict setValue:[NSString stringWithUTF8String:GLOBAL_VERSION] forKey:@"vs"];
+       [txtDict setValue:[NSString stringWithUTF8String:RAOP_AM] forKey:@"am"];
+       [txtDict setValue:[NSString stringWithUTF8String:RAOP_SF] forKey:@"sf"];
+       txtData = [NSNetService dataFromTXTRecordDictionary:txtDict];
+
+       /* Create the service and publish it */
+       dnssd->raopService = [[NSNetService alloc] initWithDomain:@""
+                                                  type:@"_raop._tcp"
+                                                  name:serviceString
+                                                  port:port];
+       [dnssd->raopService setTXTRecordData:txtData];
+       [dnssd->raopService publish];
+       return 1;
+}
+
+int
+dnssd_register_airplay(dnssd_t *dnssd, const char *name, unsigned short port)
+{
+       NSMutableDictionary *txtDict;
+       NSData *txtData;
+       char deviceid[3*MAX_HWADDR_LEN];
+       char features[16];
+       int ret;
+
+       assert(dnssd);
+
+       if (dnssd->airplayService != nil) {
+               return -1;
+       }
+
+       /* Convert hardware address to string */
+       ret = utils_hwaddr_airplay(deviceid, sizeof(deviceid), dnssd->hwaddr, dnssd->hwaddrlen);
+       if (ret < 0) {
+               return -2;
+       }
+
+       memset(features, 0, sizeof(features));
+       snprintf(features, sizeof(features)-1, "0x%x", GLOBAL_FEATURES);
+
+       txtDict = [NSMutableDictionary dictionaryWithCapacity:0];
+       [txtDict setValue:[NSString stringWithUTF8String:deviceid] forKey:@"deviceid"];
+       [txtDict setValue:[NSString stringWithUTF8String:features] forKey:@"features"];
+       [txtDict setValue:[NSString stringWithUTF8String:GLOBAL_MODEL] forKey:@"model"];
+       txtData = [NSNetService dataFromTXTRecordDictionary:txtDict];
+
+       /* Create the service and publish it */
+       dnssd->airplayService = [[NSNetService alloc] initWithDomain:@""
+                                                  type:@"_airplay._tcp"
+                                                  name:[NSString stringWithUTF8String:name]
+                                                  port:port];
+       [dnssd->airplayService setTXTRecordData:txtData];
+       [dnssd->airplayService publish];
+       return 1;
+}
+
+void
+dnssd_unregister_raop(dnssd_t *dnssd)
+{
+       assert(dnssd);
+
+       if (dnssd->raopService == nil) {
+               return;
+       }
+
+       [dnssd->raopService stop];
+       [dnssd->raopService release];
+       dnssd->raopService = nil;
+}
+
+void
+dnssd_unregister_airplay(dnssd_t *dnssd)
+{
+       assert(dnssd);
+
+       if (dnssd->airplayService == nil) {
+               return;
+       }
+
+       [dnssd->airplayService stop];
+       [dnssd->airplayService release];
+       dnssd->airplayService = nil;
+}
diff --git a/src/dnssdint.h b/src/dnssdint.h
new file mode 100644 (file)
index 0000000..803cc2b
--- /dev/null
@@ -0,0 +1,19 @@
+#ifndef DNSSDINT_H
+#define DNSSDINT_H
+
+#define RAOP_TXTVERS "1"
+#define RAOP_CH "2"
+#define RAOP_CN "0,1"
+#define RAOP_ET "1"
+#define RAOP_SV "false"
+#define RAOP_DA "true"
+#define RAOP_SR "44100"
+#define RAOP_SS "16"
+#define RAOP_PW "false"
+#define RAOP_VN "65537"
+#define RAOP_TP "TCP,UDP"
+#define RAOP_MD "0,1,2"
+#define RAOP_AM "AppleTV2,1"
+#define RAOP_SF "0x4"
+
+#endif
diff --git a/src/global.h b/src/global.h
new file mode 100644 (file)
index 0000000..4acd5bf
--- /dev/null
@@ -0,0 +1,10 @@
+#ifndef GLOBAL_H
+#define GLOBAL_H
+
+#define GLOBAL_FEATURES 0x7
+#define GLOBAL_MODEL    "AppleTV2,1"
+#define GLOBAL_VERSION  "104.29"
+
+#define MAX_HWADDR_LEN 6
+
+#endif
diff --git a/src/http_parser.c b/src/http_parser.c
new file mode 100644 (file)
index 0000000..2012330
--- /dev/null
@@ -0,0 +1,1820 @@
+/* Based on src/http/ngx_http_parse.c from NGINX copyright Igor Sysoev
+ *
+ * Additional changes are licensed under the same terms as NGINX and
+ * copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+#include "http_parser.h"
+#include <assert.h>
+#include <stddef.h>
+
+
+#ifndef MIN
+# define MIN(a,b) ((a) < (b) ? (a) : (b))
+#endif
+
+
+#if HTTP_PARSER_DEBUG
+#define SET_ERRNO(e)                                                 \
+do {                                                                 \
+  parser->http_errno = (e);                                          \
+  parser->error_lineno = __LINE__;                                   \
+} while (0)
+#else
+#define SET_ERRNO(e)                                                 \
+do {                                                                 \
+  parser->http_errno = (e);                                          \
+} while(0)
+#endif
+
+
+#define CALLBACK2(FOR)                                               \
+do {                                                                 \
+  if (settings->on_##FOR) {                                          \
+    if (0 != settings->on_##FOR(parser)) {                           \
+      SET_ERRNO(HPE_CB_##FOR);                                       \
+      return (p - data);                                             \
+    }                                                                \
+  }                                                                  \
+} while (0)
+
+
+#define MARK(FOR)                                                    \
+do {                                                                 \
+  FOR##_mark = p;                                                    \
+} while (0)
+
+#define CALLBACK(FOR)                                                \
+do {                                                                 \
+  if (FOR##_mark) {                                                  \
+    if (settings->on_##FOR) {                                        \
+      if (0 != settings->on_##FOR(parser,                            \
+                                 FOR##_mark,                         \
+                                 p - FOR##_mark))                    \
+      {                                                              \
+        SET_ERRNO(HPE_CB_##FOR);                                     \
+        return (p - data);                                           \
+      }                                                              \
+    }                                                                \
+    FOR##_mark = NULL;                                               \
+  }                                                                  \
+} while (0)
+
+
+#define PROXY_CONNECTION "proxy-connection"
+#define CONNECTION "connection"
+#define CONTENT_LENGTH "content-length"
+#define TRANSFER_ENCODING "transfer-encoding"
+#define UPGRADE "upgrade"
+#define CHUNKED "chunked"
+#define KEEP_ALIVE "keep-alive"
+#define CLOSE "close"
+
+
+static const char *method_strings[] =
+  { "DELETE"
+  , "GET"
+  , "HEAD"
+  , "POST"
+  , "PUT"
+  , "CONNECT"
+  , "OPTIONS"
+  , "TRACE"
+  , "COPY"
+  , "LOCK"
+  , "MKCOL"
+  , "MOVE"
+  , "PROPFIND"
+  , "PROPPATCH"
+  , "UNLOCK"
+  , "REPORT"
+  , "MKACTIVITY"
+  , "CHECKOUT"
+  , "MERGE"
+  , "M-SEARCH"
+  , "NOTIFY"
+  , "SUBSCRIBE"
+  , "UNSUBSCRIBE"
+  , "PATCH"
+  , "DESCRIBE"
+  , "ANNOUNCE"
+  , "SETUP"
+  , "PLAY"
+  , "PAUSE"
+  , "TEARDOWN"
+  , "GET_PARAMETER"
+  , "SET_PARAMETER"
+  , "REDIRECT"
+  , "RECORD"
+  , "FLUSH"
+  };
+
+
+/* Tokens as defined by rfc 2616. Also lowercases them.
+ *        token       = 1*<any CHAR except CTLs or separators>
+ *     separators     = "(" | ")" | "<" | ">" | "@"
+ *                    | "," | ";" | ":" | "\" | <">
+ *                    | "/" | "[" | "]" | "?" | "="
+ *                    | "{" | "}" | SP | HT
+ */
+static const char tokens[256] = {
+/*   0 nul    1 soh    2 stx    3 etx    4 eot    5 enq    6 ack    7 bel  */
+        0,       0,       0,       0,       0,       0,       0,       0,
+/*   8 bs     9 ht    10 nl    11 vt    12 np    13 cr    14 so    15 si   */
+        0,       0,       0,       0,       0,       0,       0,       0,
+/*  16 dle   17 dc1   18 dc2   19 dc3   20 dc4   21 nak   22 syn   23 etb */
+        0,       0,       0,       0,       0,       0,       0,       0,
+/*  24 can   25 em    26 sub   27 esc   28 fs    29 gs    30 rs    31 us  */
+        0,       0,       0,       0,       0,       0,       0,       0,
+/*  32 sp    33  !    34  "    35  #    36  $    37  %    38  &    39  '  */
+       ' ',      '!',     '"',     '#',     '$',     '%',     '&',    '\'',
+/*  40  (    41  )    42  *    43  +    44  ,    45  -    46  .    47  /  */
+        0,       0,      '*',     '+',      0,      '-',     '.',     '/',
+/*  48  0    49  1    50  2    51  3    52  4    53  5    54  6    55  7  */
+       '0',     '1',     '2',     '3',     '4',     '5',     '6',     '7',
+/*  56  8    57  9    58  :    59  ;    60  <    61  =    62  >    63  ?  */
+       '8',     '9',      0,       0,       0,       0,       0,       0,
+/*  64  @    65  A    66  B    67  C    68  D    69  E    70  F    71  G  */
+        0,      'a',     'b',     'c',     'd',     'e',     'f',     'g',
+/*  72  H    73  I    74  J    75  K    76  L    77  M    78  N    79  O  */
+       'h',     'i',     'j',     'k',     'l',     'm',     'n',     'o',
+/*  80  P    81  Q    82  R    83  S    84  T    85  U    86  V    87  W  */
+       'p',     'q',     'r',     's',     't',     'u',     'v',     'w',
+/*  88  X    89  Y    90  Z    91  [    92  \    93  ]    94  ^    95  _  */
+       'x',     'y',     'z',      0,       0,       0,      '^',     '_',
+/*  96  `    97  a    98  b    99  c   100  d   101  e   102  f   103  g  */
+       '`',     'a',     'b',     'c',     'd',     'e',     'f',     'g',
+/* 104  h   105  i   106  j   107  k   108  l   109  m   110  n   111  o  */
+       'h',     'i',     'j',     'k',     'l',     'm',     'n',     'o',
+/* 112  p   113  q   114  r   115  s   116  t   117  u   118  v   119  w  */
+       'p',     'q',     'r',     's',     't',     'u',     'v',     'w',
+/* 120  x   121  y   122  z   123  {   124  |   125  }   126  ~   127 del */
+       'x',     'y',     'z',      0,      '|',     '}',     '~',       0 };
+
+
+static const int8_t unhex[256] =
+  {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1
+  ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  };
+
+
+static const uint8_t normal_url_char[256] = {
+/*   0 nul    1 soh    2 stx    3 etx    4 eot    5 enq    6 ack    7 bel  */
+        0,       0,       0,       0,       0,       0,       0,       0,
+/*   8 bs     9 ht    10 nl    11 vt    12 np    13 cr    14 so    15 si   */
+        0,       0,       0,       0,       0,       0,       0,       0,
+/*  16 dle   17 dc1   18 dc2   19 dc3   20 dc4   21 nak   22 syn   23 etb */
+        0,       0,       0,       0,       0,       0,       0,       0,
+/*  24 can   25 em    26 sub   27 esc   28 fs    29 gs    30 rs    31 us  */
+        0,       0,       0,       0,       0,       0,       0,       0,
+/*  32 sp    33  !    34  "    35  #    36  $    37  %    38  &    39  '  */
+        0,       1,       1,       0,       1,       1,       1,       1,
+/*  40  (    41  )    42  *    43  +    44  ,    45  -    46  .    47  /  */
+        1,       1,       1,       1,       1,       1,       1,       1,
+/*  48  0    49  1    50  2    51  3    52  4    53  5    54  6    55  7  */
+        1,       1,       1,       1,       1,       1,       1,       1,
+/*  56  8    57  9    58  :    59  ;    60  <    61  =    62  >    63  ?  */
+        1,       1,       1,       1,       1,       1,       1,       0,
+/*  64  @    65  A    66  B    67  C    68  D    69  E    70  F    71  G  */
+        1,       1,       1,       1,       1,       1,       1,       1,
+/*  72  H    73  I    74  J    75  K    76  L    77  M    78  N    79  O  */
+        1,       1,       1,       1,       1,       1,       1,       1,
+/*  80  P    81  Q    82  R    83  S    84  T    85  U    86  V    87  W  */
+        1,       1,       1,       1,       1,       1,       1,       1,
+/*  88  X    89  Y    90  Z    91  [    92  \    93  ]    94  ^    95  _  */
+        1,       1,       1,       1,       1,       1,       1,       1,
+/*  96  `    97  a    98  b    99  c   100  d   101  e   102  f   103  g  */
+        1,       1,       1,       1,       1,       1,       1,       1,
+/* 104  h   105  i   106  j   107  k   108  l   109  m   110  n   111  o  */
+        1,       1,       1,       1,       1,       1,       1,       1,
+/* 112  p   113  q   114  r   115  s   116  t   117  u   118  v   119  w  */
+        1,       1,       1,       1,       1,       1,       1,       1,
+/* 120  x   121  y   122  z   123  {   124  |   125  }   126  ~   127 del */
+        1,       1,       1,       1,       1,       1,       1,       0, };
+
+
+enum state
+  { s_dead = 1 /* important that this is > 0 */
+
+  , s_start_req_or_res
+  , s_res_or_resp_H
+  , s_start_res
+  , s_res_H
+  , s_res_HT
+  , s_res_HTT
+  , s_res_HTTP
+  , s_res_first_http_major
+  , s_res_http_major
+  , s_res_first_http_minor
+  , s_res_http_minor
+  , s_res_first_status_code
+  , s_res_status_code
+  , s_res_status
+  , s_res_line_almost_done
+
+  , s_start_req
+
+  , s_req_method
+  , s_req_spaces_before_url
+  , s_req_schema
+  , s_req_schema_slash
+  , s_req_schema_slash_slash
+  , s_req_host
+  , s_req_port
+  , s_req_path
+  , s_req_query_string_start
+  , s_req_query_string
+  , s_req_fragment_start
+  , s_req_fragment
+  , s_req_http_start
+  , s_req_http_H
+  , s_req_http_HT
+  , s_req_http_HTT
+  , s_req_http_HTTP
+  , s_req_first_http_major
+  , s_req_http_major
+  , s_req_first_http_minor
+  , s_req_http_minor
+  , s_req_line_almost_done
+
+  , s_header_field_start
+  , s_header_field
+  , s_header_value_start
+  , s_header_value
+  , s_header_value_lws
+
+  , s_header_almost_done
+
+  , s_chunk_size_start
+  , s_chunk_size
+  , s_chunk_parameters
+  , s_chunk_size_almost_done
+  
+  , s_headers_almost_done
+  /* Important: 's_headers_almost_done' must be the last 'header' state. All
+   * states beyond this must be 'body' states. It is used for overflow
+   * checking. See the PARSING_HEADER() macro.
+   */
+
+  , s_chunk_data
+  , s_chunk_data_almost_done
+  , s_chunk_data_done
+
+  , s_body_identity
+  , s_body_identity_eof
+  };
+
+
+#define PARSING_HEADER(state) (state <= s_headers_almost_done)
+
+
+enum header_states
+  { h_general = 0
+  , h_C
+  , h_CO
+  , h_CON
+
+  , h_matching_connection
+  , h_matching_proxy_connection
+  , h_matching_content_length
+  , h_matching_transfer_encoding
+  , h_matching_upgrade
+
+  , h_connection
+  , h_content_length
+  , h_transfer_encoding
+  , h_upgrade
+
+  , h_matching_transfer_encoding_chunked
+  , h_matching_connection_keep_alive
+  , h_matching_connection_close
+
+  , h_transfer_encoding_chunked
+  , h_connection_keep_alive
+  , h_connection_close
+  };
+
+
+/* Macros for character classes; depends on strict-mode  */
+#define CR                  '\r'
+#define LF                  '\n'
+#define LOWER(c)            (unsigned char)(c | 0x20)
+#define TOKEN(c)            (tokens[(unsigned char)c])
+#define IS_ALPHA(c)         (LOWER(c) >= 'a' && LOWER(c) <= 'z')
+#define IS_NUM(c)           ((c) >= '0' && (c) <= '9')
+#define IS_ALPHANUM(c)      (IS_ALPHA(c) || IS_NUM(c))
+#define IS_NUMERIC_CHAR(c)  (IS_NUM(c) || (LOWER(c) >= 'a' && LOWER(c) <= 'f') || (c) == '.' || (c) == ':')
+
+#if HTTP_PARSER_STRICT
+#define IS_URL_CHAR(c)      (normal_url_char[(unsigned char) (c)])
+#define IS_HOST_CHAR(c)     (IS_ALPHANUM(c) || (c) == '.' || (c) == '-')
+#else
+#define IS_URL_CHAR(c)                                                         \
+  (normal_url_char[(unsigned char) (c)] || ((c) & 0x80))
+#define IS_HOST_CHAR(c)                                                        \
+  (IS_ALPHANUM(c) || (c) == '.' || (c) == '-' || (c) == '_')
+#endif
+
+
+#define start_state (parser->type == HTTP_REQUEST ? s_start_req : s_start_res)
+
+
+#if HTTP_PARSER_STRICT
+# define STRICT_CHECK(cond)                                          \
+do {                                                                 \
+  if (cond) {                                                        \
+    SET_ERRNO(HPE_STRICT);                                           \
+    goto error;                                                      \
+  }                                                                  \
+} while (0)
+# define NEW_MESSAGE() (http_should_keep_alive(parser) ? start_state : s_dead)
+#else
+# define STRICT_CHECK(cond)
+# define NEW_MESSAGE() start_state
+#endif
+
+
+/* Map errno values to strings for human-readable output */
+#define HTTP_STRERROR_GEN(n, s) { "HPE_" #n, s },
+static struct {
+  const char *name;
+  const char *description;
+} http_strerror_tab[] = {
+  HTTP_ERRNO_MAP(HTTP_STRERROR_GEN)
+};
+#undef HTTP_STRERROR_GEN
+
+
+size_t http_parser_execute (http_parser *parser,
+                            const http_parser_settings *settings,
+                            const char *data,
+                            size_t len)
+{
+  char c, ch;
+  int8_t unhex_val;
+  const char *p = data, *pe;
+  int64_t to_read;
+  enum state state;
+  enum header_states header_state;
+  uint64_t index = parser->index;
+  uint64_t nread = parser->nread;
+
+  /* technically we could combine all of these (except for url_mark) into one
+     variable, saving stack space, but it seems more clear to have them
+     separated. */
+  const char *header_field_mark = 0;
+  const char *header_value_mark = 0;
+  const char *url_mark = 0;
+
+  /* We're in an error state. Don't bother doing anything. */
+  if (HTTP_PARSER_ERRNO(parser) != HPE_OK) {
+    return 0;
+  }
+
+  state = (enum state) parser->state;
+  header_state = (enum header_states) parser->header_state;
+
+  if (len == 0) {
+    switch (state) {
+      case s_body_identity_eof:
+        CALLBACK2(message_complete);
+        return 0;
+
+      case s_dead:
+      case s_start_req_or_res:
+      case s_start_res:
+      case s_start_req:
+        return 0;
+
+      default:
+        SET_ERRNO(HPE_INVALID_EOF_STATE);
+        return 1;
+    }
+  }
+
+
+  if (state == s_header_field)
+    header_field_mark = data;
+  if (state == s_header_value)
+    header_value_mark = data;
+  if (state == s_req_path || state == s_req_schema || state == s_req_schema_slash
+      || state == s_req_schema_slash_slash || state == s_req_port
+      || state == s_req_query_string_start || state == s_req_query_string
+      || state == s_req_host
+      || state == s_req_fragment_start || state == s_req_fragment)
+    url_mark = data;
+
+  for (p=data, pe=data+len; p != pe; p++) {
+    ch = *p;
+
+    if (PARSING_HEADER(state)) {
+      ++nread;
+      /* Buffer overflow attack */
+      if (nread > HTTP_MAX_HEADER_SIZE) {
+        SET_ERRNO(HPE_HEADER_OVERFLOW);
+        goto error;
+      }
+    }
+
+    switch (state) {
+
+      case s_dead:
+        /* this state is used after a 'Connection: close' message
+         * the parser will error out if it reads another message
+         */
+        SET_ERRNO(HPE_CLOSED_CONNECTION);
+        goto error;
+
+      case s_start_req_or_res:
+      {
+        if (ch == CR || ch == LF)
+          break;
+        parser->flags = 0;
+        parser->content_length = -1;
+
+        CALLBACK2(message_begin);
+
+        if (ch == 'H')
+          state = s_res_or_resp_H;
+        else {
+          parser->type = HTTP_REQUEST;
+          goto start_req_method_assign;
+        }
+        break;
+      }
+
+      case s_res_or_resp_H:
+        if (ch == 'T') {
+          parser->type = HTTP_RESPONSE;
+          state = s_res_HT;
+        } else {
+          if (ch != 'E') {
+            SET_ERRNO(HPE_INVALID_CONSTANT);
+            goto error;
+          }
+
+          parser->type = HTTP_REQUEST;
+          parser->method = HTTP_HEAD;
+          index = 2;
+          state = s_req_method;
+        }
+        break;
+
+      case s_start_res:
+      {
+        parser->flags = 0;
+        parser->content_length = -1;
+
+        CALLBACK2(message_begin);
+
+        switch (ch) {
+          case 'H':
+            state = s_res_H;
+            break;
+
+          case CR:
+          case LF:
+            break;
+
+          default:
+            SET_ERRNO(HPE_INVALID_CONSTANT);
+            goto error;
+        }
+        break;
+      }
+
+      case s_res_H:
+        STRICT_CHECK(ch != 'T');
+        state = s_res_HT;
+        break;
+
+      case s_res_HT:
+        STRICT_CHECK(ch != 'T');
+        state = s_res_HTT;
+        break;
+
+      case s_res_HTT:
+        STRICT_CHECK(ch != 'P');
+        state = s_res_HTTP;
+        break;
+
+      case s_res_HTTP:
+        STRICT_CHECK(ch != '/');
+        state = s_res_first_http_major;
+        break;
+
+      case s_res_first_http_major:
+        if (ch < '0' || ch > '9') {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_major = ch - '0';
+        state = s_res_http_major;
+        break;
+
+      /* major HTTP version or dot */
+      case s_res_http_major:
+      {
+        if (ch == '.') {
+          state = s_res_first_http_minor;
+          break;
+        }
+
+        if (!IS_NUM(ch)) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_major *= 10;
+        parser->http_major += ch - '0';
+
+        if (parser->http_major > 999) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        break;
+      }
+
+      /* first digit of minor HTTP version */
+      case s_res_first_http_minor:
+        if (!IS_NUM(ch)) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_minor = ch - '0';
+        state = s_res_http_minor;
+        break;
+
+      /* minor HTTP version or end of request line */
+      case s_res_http_minor:
+      {
+        if (ch == ' ') {
+          state = s_res_first_status_code;
+          break;
+        }
+
+        if (!IS_NUM(ch)) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_minor *= 10;
+        parser->http_minor += ch - '0';
+
+        if (parser->http_minor > 999) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        break;
+      }
+
+      case s_res_first_status_code:
+      {
+        if (!IS_NUM(ch)) {
+          if (ch == ' ') {
+            break;
+          }
+
+          SET_ERRNO(HPE_INVALID_STATUS);
+          goto error;
+        }
+        parser->status_code = ch - '0';
+        state = s_res_status_code;
+        break;
+      }
+
+      case s_res_status_code:
+      {
+        if (!IS_NUM(ch)) {
+          switch (ch) {
+            case ' ':
+              state = s_res_status;
+              break;
+            case CR:
+              state = s_res_line_almost_done;
+              break;
+            case LF:
+              state = s_header_field_start;
+              break;
+            default:
+              SET_ERRNO(HPE_INVALID_STATUS);
+              goto error;
+          }
+          break;
+        }
+
+        parser->status_code *= 10;
+        parser->status_code += ch - '0';
+
+        if (parser->status_code > 999) {
+          SET_ERRNO(HPE_INVALID_STATUS);
+          goto error;
+        }
+
+        break;
+      }
+
+      case s_res_status:
+        /* the human readable status. e.g. "NOT FOUND"
+         * we are not humans so just ignore this */
+        if (ch == CR) {
+          state = s_res_line_almost_done;
+          break;
+        }
+
+        if (ch == LF) {
+          state = s_header_field_start;
+          break;
+        }
+        break;
+
+      case s_res_line_almost_done:
+        STRICT_CHECK(ch != LF);
+        state = s_header_field_start;
+        break;
+
+      case s_start_req:
+      {
+        if (ch == CR || ch == LF)
+          break;
+        parser->flags = 0;
+        parser->content_length = -1;
+
+        CALLBACK2(message_begin);
+
+        if (!IS_ALPHA(ch)) {
+          SET_ERRNO(HPE_INVALID_METHOD);
+          goto error;
+        }
+
+      start_req_method_assign:
+        parser->method = (enum http_method) 0;
+        index = 1;
+        switch (ch) {
+          case 'A': parser->method = HTTP_ANNOUNCE; break;
+          case 'C': parser->method = HTTP_CONNECT; /* or COPY, CHECKOUT */ break;
+          case 'D': parser->method = HTTP_DELETE; /* or DESCRIBE */ break;
+          case 'F': parser->method = HTTP_FLUSH; break;
+          case 'G': parser->method = HTTP_GET; /* or GET_PARAMETER */ break;
+          case 'H': parser->method = HTTP_HEAD; break;
+          case 'L': parser->method = HTTP_LOCK; break;
+          case 'M': parser->method = HTTP_MKCOL; /* or MOVE, MKACTIVITY, MERGE, M-SEARCH */ break;
+          case 'N': parser->method = HTTP_NOTIFY; break;
+          case 'O': parser->method = HTTP_OPTIONS; break;
+          case 'P': parser->method = HTTP_POST;
+            /* or PROPFIND or PROPPATCH or PUT or PATCH or PLAY or PAUSE */
+            break;
+          case 'R': parser->method = HTTP_REPORT; /* or REDIRECT, RECORD */ break;
+          case 'S': parser->method = HTTP_SUBSCRIBE; /* or SETUP, SET_PARAMETER */ break;
+          case 'T': parser->method = HTTP_TRACE; /* or TEARDOWN */ break;
+          case 'U': parser->method = HTTP_UNLOCK; /* or UNSUBSCRIBE */ break;
+          default:
+            SET_ERRNO(HPE_INVALID_METHOD);
+            goto error;
+        }
+        state = s_req_method;
+        break;
+      }
+
+      case s_req_method:
+      {
+        const char *matcher;
+        if (ch == '\0') {
+          SET_ERRNO(HPE_INVALID_METHOD);
+          goto error;
+        }
+
+        matcher = method_strings[parser->method];
+        if (ch == ' ' && matcher[index] == '\0') {
+          state = s_req_spaces_before_url;
+        } else if (ch == matcher[index]) {
+          ; /* nada */
+        } else if (parser->method == HTTP_CONNECT) {
+          if (index == 1 && ch == 'H') {
+            parser->method = HTTP_CHECKOUT;
+          } else if (index == 2  && ch == 'P') {
+            parser->method = HTTP_COPY;
+          } else {
+            goto error;
+          }
+        } else if (index == 2 && parser->method == HTTP_DELETE && ch == 'S') {
+          parser->method = HTTP_DESCRIBE;
+        } else if (index == 3 && parser->method == HTTP_GET && ch == '_') {
+          parser->method = HTTP_GET_PARAMETER;
+        } else if (parser->method == HTTP_MKCOL) {
+          if (index == 1 && ch == 'O') {
+            parser->method = HTTP_MOVE;
+          } else if (index == 1 && ch == 'E') {
+            parser->method = HTTP_MERGE;
+          } else if (index == 1 && ch == '-') {
+            parser->method = HTTP_MSEARCH;
+          } else if (index == 2 && ch == 'A') {
+            parser->method = HTTP_MKACTIVITY;
+          } else {
+            goto error;
+          }
+        } else if (index == 1 && parser->method == HTTP_POST) {
+          if (ch == 'R') {
+            parser->method = HTTP_PROPFIND; /* or HTTP_PROPPATCH */
+          } else if (ch == 'U') {
+            parser->method = HTTP_PUT;
+          } else if (ch == 'A') {
+            parser->method = HTTP_PATCH; /* or HTTP_PAUSE */
+          } else if (ch == 'L') {
+            parser->method = HTTP_PLAY;
+          } else {
+            goto error;
+          }
+        } else if (index == 2 && parser->method == HTTP_REPORT) {
+          if (ch == 'D') {
+            parser->method = HTTP_REDIRECT;
+          } else if (ch == 'C') {
+            parser->method = HTTP_RECORD;
+          } else {
+            goto error;
+          }
+        } else if (index == 1 && parser->method == HTTP_SUBSCRIBE && ch == 'E') {
+          parser->method = HTTP_SETUP; /* or HTTP_SET_PARAMETER */
+        } else if (index == 3 && parser->method == HTTP_SETUP && ch == '_') {
+          parser->method = HTTP_SET_PARAMETER;
+        } else if (index == 1 && parser->method == HTTP_TRACE && ch == 'E') {
+          parser->method = HTTP_TEARDOWN;
+        } else if (index == 2 && parser->method == HTTP_UNLOCK && ch == 'S') {
+          parser->method = HTTP_UNSUBSCRIBE;
+        } else if (index == 4 && parser->method == HTTP_PROPFIND && ch == 'P') {
+          parser->method = HTTP_PROPPATCH;
+        } else if (index == 2 && parser->method == HTTP_PATCH && ch == 'U') {
+          parser->method = HTTP_PAUSE;
+        } else {
+          SET_ERRNO(HPE_INVALID_METHOD);
+          goto error;
+        }
+
+        ++index;
+        break;
+      }
+      case s_req_spaces_before_url:
+      {
+        if (ch == ' ') break;
+
+        if (ch == '/' || ch == '*') {
+          MARK(url);
+          state = s_req_path;
+          break;
+        }
+
+        /* Proxied requests are followed by scheme of an absolute URI (alpha).
+         * CONNECT is followed by a hostname, which begins with alphanum.
+         * All other methods are followed by '/' or '*' (handled above).
+         */
+        if (IS_ALPHA(ch) || (parser->method == HTTP_CONNECT && IS_NUM(ch))) {
+          MARK(url);
+          state = (parser->method == HTTP_CONNECT) ? s_req_host : s_req_schema;
+          break;
+        }
+
+        SET_ERRNO(HPE_INVALID_URL);
+        goto error;
+      }
+
+      case s_req_schema:
+      {
+        if (IS_ALPHA(ch)) break;
+
+        if (ch == ':') {
+          state = s_req_schema_slash;
+          break;
+        }
+
+        SET_ERRNO(HPE_INVALID_URL);
+        goto error;
+      }
+
+      case s_req_schema_slash:
+        STRICT_CHECK(ch != '/');
+        state = s_req_schema_slash_slash;
+        break;
+
+      case s_req_schema_slash_slash:
+        STRICT_CHECK(ch != '/');
+        state = s_req_host;
+        break;
+
+      case s_req_host:
+      {
+        if (parser->numerichost) {
+          if (IS_NUMERIC_CHAR(ch)) break;
+        } else {
+          if (IS_HOST_CHAR(ch)) break;
+        }
+        switch (ch) {
+          case ':':
+            state = s_req_port;
+            break;
+          case '/':
+            state = s_req_path;
+            break;
+          case ' ':
+            /* The request line looks like:
+             *   "GET http://foo.bar.com HTTP/1.1"
+             * That is, there is no path.
+             */
+            CALLBACK(url);
+            state = s_req_http_start;
+            break;
+          case '?':
+            state = s_req_query_string_start;
+            break;
+          default:
+            SET_ERRNO(HPE_INVALID_HOST);
+            goto error;
+        }
+        break;
+      }
+
+      case s_req_port:
+      {
+        if (IS_NUM(ch)) break;
+        switch (ch) {
+          case '/':
+            state = s_req_path;
+            break;
+          case ' ':
+            /* The request line looks like:
+             *   "GET http://foo.bar.com:1234 HTTP/1.1"
+             * That is, there is no path.
+             */
+            CALLBACK(url);
+            state = s_req_http_start;
+            break;
+          case '?':
+            state = s_req_query_string_start;
+            break;
+          default:
+            SET_ERRNO(HPE_INVALID_PORT);
+            goto error;
+        }
+        break;
+      }
+
+      case s_req_path:
+      {
+        if (IS_URL_CHAR(ch)) break;
+
+        switch (ch) {
+          case ' ':
+            CALLBACK(url);
+            state = s_req_http_start;
+            break;
+          case CR:
+            CALLBACK(url);
+            parser->http_major = 0;
+            parser->http_minor = 9;
+            state = s_req_line_almost_done;
+            break;
+          case LF:
+            CALLBACK(url);
+            parser->http_major = 0;
+            parser->http_minor = 9;
+            state = s_header_field_start;
+            break;
+          case '?':
+            state = s_req_query_string_start;
+            break;
+          case '#':
+            state = s_req_fragment_start;
+            break;
+          default:
+            SET_ERRNO(HPE_INVALID_PATH);
+            goto error;
+        }
+        break;
+      }
+
+      case s_req_query_string_start:
+      {
+        if (IS_URL_CHAR(ch)) {
+          state = s_req_query_string;
+          break;
+        }
+
+        switch (ch) {
+          case '?':
+            break; /* XXX ignore extra '?' ... is this right? */
+          case ' ':
+            CALLBACK(url);
+            state = s_req_http_start;
+            break;
+          case CR:
+            CALLBACK(url);
+            parser->http_major = 0;
+            parser->http_minor = 9;
+            state = s_req_line_almost_done;
+            break;
+          case LF:
+            CALLBACK(url);
+            parser->http_major = 0;
+            parser->http_minor = 9;
+            state = s_header_field_start;
+            break;
+          case '#':
+            state = s_req_fragment_start;
+            break;
+          default:
+            SET_ERRNO(HPE_INVALID_QUERY_STRING);
+            goto error;
+        }
+        break;
+      }
+
+      case s_req_query_string:
+      {
+        if (IS_URL_CHAR(ch)) break;
+
+        switch (ch) {
+          case '?':
+            /* allow extra '?' in query string */
+            break;
+          case ' ':
+            CALLBACK(url);
+            state = s_req_http_start;
+            break;
+          case CR:
+            CALLBACK(url);
+            parser->http_major = 0;
+            parser->http_minor = 9;
+            state = s_req_line_almost_done;
+            break;
+          case LF:
+            CALLBACK(url);
+            parser->http_major = 0;
+            parser->http_minor = 9;
+            state = s_header_field_start;
+            break;
+          case '#':
+            state = s_req_fragment_start;
+            break;
+          default:
+            SET_ERRNO(HPE_INVALID_QUERY_STRING);
+            goto error;
+        }
+        break;
+      }
+
+      case s_req_fragment_start:
+      {
+        if (IS_URL_CHAR(ch)) {
+          state = s_req_fragment;
+          break;
+        }
+
+        switch (ch) {
+          case ' ':
+            CALLBACK(url);
+            state = s_req_http_start;
+            break;
+          case CR:
+            CALLBACK(url);
+            parser->http_major = 0;
+            parser->http_minor = 9;
+            state = s_req_line_almost_done;
+            break;
+          case LF:
+            CALLBACK(url);
+            parser->http_major = 0;
+            parser->http_minor = 9;
+            state = s_header_field_start;
+            break;
+          case '?':
+            state = s_req_fragment;
+            break;
+          case '#':
+            break;
+          default:
+            SET_ERRNO(HPE_INVALID_FRAGMENT);
+            goto error;
+        }
+        break;
+      }
+
+      case s_req_fragment:
+      {
+        if (IS_URL_CHAR(ch)) break;
+
+        switch (ch) {
+          case ' ':
+            CALLBACK(url);
+            state = s_req_http_start;
+            break;
+          case CR:
+            CALLBACK(url);
+            parser->http_major = 0;
+            parser->http_minor = 9;
+            state = s_req_line_almost_done;
+            break;
+          case LF:
+            CALLBACK(url);
+            parser->http_major = 0;
+            parser->http_minor = 9;
+            state = s_header_field_start;
+            break;
+          case '?':
+          case '#':
+            break;
+          default:
+            SET_ERRNO(HPE_INVALID_FRAGMENT);
+            goto error;
+        }
+        break;
+      }
+
+      case s_req_http_start:
+        switch (ch) {
+          case 'H':
+          case 'R':
+            state = s_req_http_H;
+            break;
+          case ' ':
+            break;
+          default:
+            SET_ERRNO(HPE_INVALID_CONSTANT);
+            goto error;
+        }
+        break;
+
+      case s_req_http_H:
+        STRICT_CHECK(ch != 'T');
+        state = s_req_http_HT;
+        break;
+
+      case s_req_http_HT:
+        STRICT_CHECK(ch != 'T');
+        state = s_req_http_HTT;
+        break;
+
+      case s_req_http_HTT:
+        STRICT_CHECK(ch != 'P');
+        state = s_req_http_HTTP;
+        break;
+
+      case s_req_http_HTTP:
+        STRICT_CHECK(ch != '/');
+        state = s_req_first_http_major;
+        break;
+
+      /* first digit of major HTTP version */
+      case s_req_first_http_major:
+        if (ch < '1' || ch > '9') {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_major = ch - '0';
+        state = s_req_http_major;
+        break;
+
+      /* major HTTP version or dot */
+      case s_req_http_major:
+      {
+        if (ch == '.') {
+          state = s_req_first_http_minor;
+          break;
+        }
+
+        if (!IS_NUM(ch)) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_major *= 10;
+        parser->http_major += ch - '0';
+
+        if (parser->http_major > 999) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        break;
+      }
+
+      /* first digit of minor HTTP version */
+      case s_req_first_http_minor:
+        if (!IS_NUM(ch)) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_minor = ch - '0';
+        state = s_req_http_minor;
+        break;
+
+      /* minor HTTP version or end of request line */
+      case s_req_http_minor:
+      {
+        if (ch == CR) {
+          state = s_req_line_almost_done;
+          break;
+        }
+
+        if (ch == LF) {
+          state = s_header_field_start;
+          break;
+        }
+
+        /* XXX allow spaces after digit? */
+
+        if (!IS_NUM(ch)) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_minor *= 10;
+        parser->http_minor += ch - '0';
+
+        if (parser->http_minor > 999) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        break;
+      }
+
+      /* end of request line */
+      case s_req_line_almost_done:
+      {
+        if (ch != LF) {
+          SET_ERRNO(HPE_LF_EXPECTED);
+          goto error;
+        }
+
+        state = s_header_field_start;
+        break;
+      }
+
+      case s_header_field_start:
+      header_field_start:
+      {
+        if (ch == CR) {
+          state = s_headers_almost_done;
+          break;
+        }
+
+        if (ch == LF) {
+          /* they might be just sending \n instead of \r\n so this would be
+           * the second \n to denote the end of headers*/
+          state = s_headers_almost_done;
+          goto headers_almost_done;
+        }
+
+        c = TOKEN(ch);
+
+        if (!c) {
+          SET_ERRNO(HPE_INVALID_HEADER_TOKEN);
+          goto error;
+        }
+
+        MARK(header_field);
+
+        index = 0;
+        state = s_header_field;
+
+        switch (c) {
+          case 'c':
+            header_state = h_C;
+            break;
+
+          case 'p':
+            header_state = h_matching_proxy_connection;
+            break;
+
+          case 't':
+            header_state = h_matching_transfer_encoding;
+            break;
+
+          case 'u':
+            header_state = h_matching_upgrade;
+            break;
+
+          default:
+            header_state = h_general;
+            break;
+        }
+        break;
+      }
+
+      case s_header_field:
+      {
+        c = TOKEN(ch);
+
+        if (c) {
+          switch (header_state) {
+            case h_general:
+              break;
+
+            case h_C:
+              index++;
+              header_state = (c == 'o' ? h_CO : h_general);
+              break;
+
+            case h_CO:
+              index++;
+              header_state = (c == 'n' ? h_CON : h_general);
+              break;
+
+            case h_CON:
+              index++;
+              switch (c) {
+                case 'n':
+                  header_state = h_matching_connection;
+                  break;
+                case 't':
+                  header_state = h_matching_content_length;
+                  break;
+                default:
+                  header_state = h_general;
+                  break;
+              }
+              break;
+
+            /* connection */
+
+            case h_matching_connection:
+              index++;
+              if (index > sizeof(CONNECTION)-1
+                  || c != CONNECTION[index]) {
+                header_state = h_general;
+              } else if (index == sizeof(CONNECTION)-2) {
+                header_state = h_connection;
+              }
+              break;
+
+            /* proxy-connection */
+
+            case h_matching_proxy_connection:
+              index++;
+              if (index > sizeof(PROXY_CONNECTION)-1
+                  || c != PROXY_CONNECTION[index]) {
+                header_state = h_general;
+              } else if (index == sizeof(PROXY_CONNECTION)-2) {
+                header_state = h_connection;
+              }
+              break;
+
+            /* content-length */
+
+            case h_matching_content_length:
+              index++;
+              if (index > sizeof(CONTENT_LENGTH)-1
+                  || c != CONTENT_LENGTH[index]) {
+                header_state = h_general;
+              } else if (index == sizeof(CONTENT_LENGTH)-2) {
+                header_state = h_content_length;
+              }
+              break;
+
+            /* transfer-encoding */
+
+            case h_matching_transfer_encoding:
+              index++;
+              if (index > sizeof(TRANSFER_ENCODING)-1
+                  || c != TRANSFER_ENCODING[index]) {
+                header_state = h_general;
+              } else if (index == sizeof(TRANSFER_ENCODING)-2) {
+                header_state = h_transfer_encoding;
+              }
+              break;
+
+            /* upgrade */
+
+            case h_matching_upgrade:
+              index++;
+              if (index > sizeof(UPGRADE)-1
+                  || c != UPGRADE[index]) {
+                header_state = h_general;
+              } else if (index == sizeof(UPGRADE)-2) {
+                header_state = h_upgrade;
+              }
+              break;
+
+            case h_connection:
+            case h_content_length:
+            case h_transfer_encoding:
+            case h_upgrade:
+              if (ch != ' ') header_state = h_general;
+              break;
+
+            default:
+              assert(0 && "Unknown header_state");
+              break;
+          }
+          break;
+        }
+
+        if (ch == ':') {
+          CALLBACK(header_field);
+          state = s_header_value_start;
+          break;
+        }
+
+        if (ch == CR) {
+          state = s_header_almost_done;
+          CALLBACK(header_field);
+          break;
+        }
+
+        if (ch == LF) {
+          CALLBACK(header_field);
+          state = s_header_field_start;
+          break;
+        }
+
+        SET_ERRNO(HPE_INVALID_HEADER_TOKEN);
+        goto error;
+      }
+
+      case s_header_value_start:
+      {
+        if (ch == ' ' || ch == '\t') break;
+
+        MARK(header_value);
+
+        state = s_header_value;
+        index = 0;
+
+        if (ch == CR) {
+          CALLBACK(header_value);
+          header_state = h_general;
+          state = s_header_almost_done;
+          break;
+        }
+
+        if (ch == LF) {
+          CALLBACK(header_value);
+          state = s_header_field_start;
+          break;
+        }
+
+        c = LOWER(ch);
+
+        switch (header_state) {
+          case h_upgrade:
+            parser->flags |= F_UPGRADE;
+            header_state = h_general;
+            break;
+
+          case h_transfer_encoding:
+            /* looking for 'Transfer-Encoding: chunked' */
+            if ('c' == c) {
+              header_state = h_matching_transfer_encoding_chunked;
+            } else {
+              header_state = h_general;
+            }
+            break;
+
+          case h_content_length:
+            if (!IS_NUM(ch)) {
+              SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);
+              goto error;
+            }
+
+            parser->content_length = ch - '0';
+            break;
+
+          case h_connection:
+            /* looking for 'Connection: keep-alive' */
+            if (c == 'k') {
+              header_state = h_matching_connection_keep_alive;
+            /* looking for 'Connection: close' */
+            } else if (c == 'c') {
+              header_state = h_matching_connection_close;
+            } else {
+              header_state = h_general;
+            }
+            break;
+
+          default:
+            header_state = h_general;
+            break;
+        }
+        break;
+      }
+
+      case s_header_value:
+      {
+
+        if (ch == CR) {
+          CALLBACK(header_value);
+          state = s_header_almost_done;
+          break;
+        }
+
+        if (ch == LF) {
+          CALLBACK(header_value);
+          goto header_almost_done;
+        }
+
+        c = LOWER(ch);
+
+        switch (header_state) {
+          case h_general:
+            break;
+
+          case h_connection:
+          case h_transfer_encoding:
+            assert(0 && "Shouldn't get here.");
+            break;
+
+          case h_content_length:
+            if (ch == ' ') break;
+            if (!IS_NUM(ch)) {
+              SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);
+              goto error;
+            }
+
+            parser->content_length *= 10;
+            parser->content_length += ch - '0';
+            break;
+
+          /* Transfer-Encoding: chunked */
+          case h_matching_transfer_encoding_chunked:
+            index++;
+            if (index > sizeof(CHUNKED)-1
+                || c != CHUNKED[index]) {
+              header_state = h_general;
+            } else if (index == sizeof(CHUNKED)-2) {
+              header_state = h_transfer_encoding_chunked;
+            }
+            break;
+
+          /* looking for 'Connection: keep-alive' */
+          case h_matching_connection_keep_alive:
+            index++;
+            if (index > sizeof(KEEP_ALIVE)-1
+                || c != KEEP_ALIVE[index]) {
+              header_state = h_general;
+            } else if (index == sizeof(KEEP_ALIVE)-2) {
+              header_state = h_connection_keep_alive;
+            }
+            break;
+
+          /* looking for 'Connection: close' */
+          case h_matching_connection_close:
+            index++;
+            if (index > sizeof(CLOSE)-1 || c != CLOSE[index]) {
+              header_state = h_general;
+            } else if (index == sizeof(CLOSE)-2) {
+              header_state = h_connection_close;
+            }
+            break;
+
+          case h_transfer_encoding_chunked:
+          case h_connection_keep_alive:
+          case h_connection_close:
+            if (ch != ' ') header_state = h_general;
+            break;
+
+          default:
+            state = s_header_value;
+            header_state = h_general;
+            break;
+        }
+        break;
+      }
+
+      case s_header_almost_done:
+      header_almost_done:
+      {
+        STRICT_CHECK(ch != LF);
+
+        state = s_header_value_lws;
+
+        switch (header_state) {
+          case h_connection_keep_alive:
+            parser->flags |= F_CONNECTION_KEEP_ALIVE;
+            break;
+          case h_connection_close:
+            parser->flags |= F_CONNECTION_CLOSE;
+            break;
+          case h_transfer_encoding_chunked:
+            parser->flags |= F_CHUNKED;
+            break;
+          default:
+            break;
+        }
+        break;
+      }
+
+      case s_header_value_lws:
+      {
+        if (ch == ' ' || ch == '\t')
+          state = s_header_value_start;
+        else
+        {
+          state = s_header_field_start;
+          goto header_field_start;
+        }
+        break;
+      }
+
+      case s_headers_almost_done:
+      headers_almost_done:
+      {
+        STRICT_CHECK(ch != LF);
+
+        if (parser->flags & F_TRAILING) {
+          /* End of a chunked request */
+          CALLBACK2(message_complete);
+          state = NEW_MESSAGE();
+          break;
+        }
+
+        nread = 0;
+
+        if (parser->flags & F_UPGRADE || parser->method == HTTP_CONNECT) {
+          parser->upgrade = 1;
+        }
+
+        /* Here we call the headers_complete callback. This is somewhat
+         * different than other callbacks because if the user returns 1, we
+         * will interpret that as saying that this message has no body. This
+         * is needed for the annoying case of recieving a response to a HEAD
+         * request.
+         */
+        if (settings->on_headers_complete) {
+          switch (settings->on_headers_complete(parser)) {
+            case 0:
+              break;
+
+            case 1:
+              parser->flags |= F_SKIPBODY;
+              break;
+
+            default:
+              parser->state = state;
+              SET_ERRNO(HPE_CB_headers_complete);
+              return p - data; /* Error */
+          }
+        }
+
+        /* Exit, the rest of the connect is in a different protocol. */
+        if (parser->upgrade) {
+          CALLBACK2(message_complete);
+          return (p - data) + 1;
+        }
+
+        if (parser->flags & F_SKIPBODY) {
+          CALLBACK2(message_complete);
+          state = NEW_MESSAGE();
+        } else if (parser->flags & F_CHUNKED) {
+          /* chunked encoding - ignore Content-Length header */
+          state = s_chunk_size_start;
+        } else {
+          if (parser->content_length == 0) {
+            /* Content-Length header given but zero: Content-Length: 0\r\n */
+            CALLBACK2(message_complete);
+            state = NEW_MESSAGE();
+          } else if (parser->content_length > 0) {
+            /* Content-Length header given and non-zero */
+            state = s_body_identity;
+          } else {
+            if (parser->type == HTTP_REQUEST || http_should_keep_alive(parser)) {
+              /* Assume content-length 0 - read the next */
+              CALLBACK2(message_complete);
+              state = NEW_MESSAGE();
+            } else {
+              /* Read body until EOF */
+              state = s_body_identity_eof;
+            }
+          }
+        }
+
+        break;
+      }
+
+      case s_body_identity:
+        to_read = MIN(pe - p, (int64_t)parser->content_length);
+        if (to_read > 0) {
+          if (settings->on_body) settings->on_body(parser, p, to_read);
+          p += to_read - 1;
+          parser->content_length -= to_read;
+          if (parser->content_length == 0) {
+            CALLBACK2(message_complete);
+            state = NEW_MESSAGE();
+          }
+        }
+        break;
+
+      /* read until EOF */
+      case s_body_identity_eof:
+        to_read = pe - p;
+        if (to_read > 0) {
+          if (settings->on_body) settings->on_body(parser, p, to_read);
+          p += to_read - 1;
+        }
+        break;
+
+      case s_chunk_size_start:
+      {
+        assert(nread == 1);
+        assert(parser->flags & F_CHUNKED);
+
+        unhex_val = unhex[(unsigned char)ch];
+        if (unhex_val == -1) {
+          SET_ERRNO(HPE_INVALID_CHUNK_SIZE);
+          goto error;
+        }
+
+        parser->content_length = unhex_val;
+        state = s_chunk_size;
+        break;
+      }
+
+      case s_chunk_size:
+      {
+        assert(parser->flags & F_CHUNKED);
+
+        if (ch == CR) {
+          state = s_chunk_size_almost_done;
+          break;
+        }
+
+        unhex_val = unhex[(unsigned char)ch];
+
+        if (unhex_val == -1) {
+          if (ch == ';' || ch == ' ') {
+            state = s_chunk_parameters;
+            break;
+          }
+
+          SET_ERRNO(HPE_INVALID_CHUNK_SIZE);
+          goto error;
+        }
+
+        parser->content_length *= 16;
+        parser->content_length += unhex_val;
+        break;
+      }
+
+      case s_chunk_parameters:
+      {
+        assert(parser->flags & F_CHUNKED);
+        /* just ignore this shit. TODO check for overflow */
+        if (ch == CR) {
+          state = s_chunk_size_almost_done;
+          break;
+        }
+        break;
+      }
+
+      case s_chunk_size_almost_done:
+      {
+        assert(parser->flags & F_CHUNKED);
+        STRICT_CHECK(ch != LF);
+
+        nread = 0;
+
+        if (parser->content_length == 0) {
+          parser->flags |= F_TRAILING;
+          state = s_header_field_start;
+        } else {
+          state = s_chunk_data;
+        }
+        break;
+      }
+
+      case s_chunk_data:
+      {
+        assert(parser->flags & F_CHUNKED);
+
+        to_read = MIN(pe - p, (int64_t)(parser->content_length));
+
+        if (to_read > 0) {
+          if (settings->on_body) settings->on_body(parser, p, to_read);
+          p += to_read - 1;
+        }
+
+        if (to_read == parser->content_length) {
+          state = s_chunk_data_almost_done;
+        }
+
+        parser->content_length -= to_read;
+        break;
+      }
+
+      case s_chunk_data_almost_done:
+        assert(parser->flags & F_CHUNKED);
+        STRICT_CHECK(ch != CR);
+        state = s_chunk_data_done;
+        break;
+
+      case s_chunk_data_done:
+        assert(parser->flags & F_CHUNKED);
+        STRICT_CHECK(ch != LF);
+        state = s_chunk_size_start;
+        break;
+
+      default:
+        assert(0 && "unhandled state");
+        SET_ERRNO(HPE_INVALID_INTERNAL_STATE);
+        goto error;
+    }
+  }
+
+  CALLBACK(header_field);
+  CALLBACK(header_value);
+  CALLBACK(url);
+
+  parser->state = state;
+  parser->header_state = header_state;
+  parser->index = index;
+  parser->nread = nread;
+
+  return len;
+
+error:
+  if (HTTP_PARSER_ERRNO(parser) == HPE_OK) {
+    SET_ERRNO(HPE_UNKNOWN);
+  }
+
+  return (p - data);
+}
+
+
+int
+http_should_keep_alive (http_parser *parser)
+{
+  if (parser->http_major > 0 && parser->http_minor > 0) {
+    /* HTTP/1.1 */
+    if (parser->flags & F_CONNECTION_CLOSE) {
+      return 0;
+    } else {
+      return 1;
+    }
+  } else {
+    /* HTTP/1.0 or earlier */
+    if (parser->flags & F_CONNECTION_KEEP_ALIVE) {
+      return 1;
+    } else {
+      return 0;
+    }
+  }
+}
+
+
+const char * http_method_str (enum http_method m)
+{
+  return method_strings[m];
+}
+
+
+void
+http_parser_init (http_parser *parser, enum http_parser_type t, char numerichost)
+{
+  parser->numerichost = numerichost;
+  parser->type = t;
+  parser->state = (t == HTTP_REQUEST ? s_start_req : (t == HTTP_RESPONSE ? s_start_res : s_start_req_or_res));
+  parser->nread = 0;
+  parser->upgrade = 0;
+  parser->flags = 0;
+  parser->method = 0;
+  parser->http_errno = 0;
+}
+
+const char *
+http_errno_name(enum http_errno err) {
+  assert(err < (sizeof(http_strerror_tab)/sizeof(http_strerror_tab[0])));
+  return http_strerror_tab[err].name;
+}
+
+const char *
+http_errno_description(enum http_errno err) {
+  assert(err < (sizeof(http_strerror_tab)/sizeof(http_strerror_tab[0])));
+  return http_strerror_tab[err].description;
+}
diff --git a/src/http_parser.h b/src/http_parser.h
new file mode 100644 (file)
index 0000000..4898fda
--- /dev/null
@@ -0,0 +1,290 @@
+/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+#ifndef http_parser_h
+#define http_parser_h
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define HTTP_PARSER_VERSION_MAJOR 1
+#define HTTP_PARSER_VERSION_MINOR 0
+
+#include <sys/types.h>
+#if defined(_WIN32) && !defined(__MINGW32__) && !defined(_MSC_VER)
+typedef __int8 int8_t;
+typedef unsigned __int8 uint8_t;
+typedef __int16 int16_t;
+typedef unsigned __int16 uint16_t;
+typedef __int32 int32_t;
+typedef unsigned __int32 uint32_t;
+typedef __int64 int64_t;
+typedef unsigned __int64 uint64_t;
+
+typedef unsigned int size_t;
+typedef int ssize_t;
+#else
+#include <stdint.h>
+#endif
+
+/* Compile with -DHTTP_PARSER_STRICT=0 to make less checks, but run
+ * faster
+ */
+#ifndef HTTP_PARSER_STRICT
+# define HTTP_PARSER_STRICT 0
+#endif
+
+/* Compile with -DHTTP_PARSER_DEBUG=1 to add extra debugging information to
+ * the error reporting facility.
+ */
+#ifndef HTTP_PARSER_DEBUG
+# define HTTP_PARSER_DEBUG 0
+#endif
+
+
+/* Maximium header size allowed */
+#define HTTP_MAX_HEADER_SIZE (80*1024)
+
+
+typedef struct http_parser http_parser;
+typedef struct http_parser_settings http_parser_settings;
+typedef struct http_parser_result http_parser_result;
+
+
+/* Callbacks should return non-zero to indicate an error. The parser will
+ * then halt execution.
+ *
+ * The one exception is on_headers_complete. In a HTTP_RESPONSE parser
+ * returning '1' from on_headers_complete will tell the parser that it
+ * should not expect a body. This is used when receiving a response to a
+ * HEAD request which may contain 'Content-Length' or 'Transfer-Encoding:
+ * chunked' headers that indicate the presence of a body.
+ *
+ * http_data_cb does not return data chunks. It will be call arbitrarally
+ * many times for each string. E.G. you might get 10 callbacks for "on_path"
+ * each providing just a few characters more data.
+ */
+typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);
+typedef int (*http_cb) (http_parser*);
+
+
+/* Request Methods */
+enum http_method
+  { HTTP_DELETE    = 0
+  , HTTP_GET
+  , HTTP_HEAD
+  , HTTP_POST
+  , HTTP_PUT
+  /* pathological */
+  , HTTP_CONNECT
+  , HTTP_OPTIONS
+  , HTTP_TRACE
+  /* webdav */
+  , HTTP_COPY
+  , HTTP_LOCK
+  , HTTP_MKCOL
+  , HTTP_MOVE
+  , HTTP_PROPFIND
+  , HTTP_PROPPATCH
+  , HTTP_UNLOCK
+  /* subversion */
+  , HTTP_REPORT
+  , HTTP_MKACTIVITY
+  , HTTP_CHECKOUT
+  , HTTP_MERGE
+  /* upnp */
+  , HTTP_MSEARCH
+  , HTTP_NOTIFY
+  , HTTP_SUBSCRIBE
+  , HTTP_UNSUBSCRIBE
+  /* RFC-5789 */
+  , HTTP_PATCH
+  /* RTSP RFC 2326 */
+  , HTTP_DESCRIBE
+  , HTTP_ANNOUNCE
+  , HTTP_SETUP
+  , HTTP_PLAY
+  , HTTP_PAUSE
+  , HTTP_TEARDOWN
+  , HTTP_GET_PARAMETER
+  , HTTP_SET_PARAMETER
+  , HTTP_REDIRECT
+  , HTTP_RECORD
+  /* RAOP FLUSH */
+  , HTTP_FLUSH
+  };
+
+
+enum http_parser_type { HTTP_REQUEST, HTTP_RESPONSE, HTTP_BOTH };
+
+
+/* Flag values for http_parser.flags field */
+enum flags
+  { F_CHUNKED               = 1 << 0
+  , F_CONNECTION_KEEP_ALIVE = 1 << 1
+  , F_CONNECTION_CLOSE      = 1 << 2
+  , F_TRAILING              = 1 << 3
+  , F_UPGRADE               = 1 << 4
+  , F_SKIPBODY              = 1 << 5
+  };
+
+
+/* Map for errno-related constants
+ * 
+ * The provided argument should be a macro that takes 2 arguments.
+ */
+#define HTTP_ERRNO_MAP(XX)                                           \
+  /* No error */                                                     \
+  XX(OK, "success")                                                  \
+                                                                     \
+  /* Callback-related errors */                                      \
+  XX(CB_message_begin, "the on_message_begin callback failed")       \
+  XX(CB_path, "the on_path callback failed")                         \
+  XX(CB_query_string, "the on_query_string callback failed")         \
+  XX(CB_url, "the on_url callback failed")                           \
+  XX(CB_fragment, "the on_fragment callback failed")                 \
+  XX(CB_header_field, "the on_header_field callback failed")         \
+  XX(CB_header_value, "the on_header_value callback failed")         \
+  XX(CB_headers_complete, "the on_headers_complete callback failed") \
+  XX(CB_body, "the on_body callback failed")                         \
+  XX(CB_message_complete, "the on_message_complete callback failed") \
+                                                                     \
+  /* Parsing-related errors */                                       \
+  XX(INVALID_EOF_STATE, "stream ended at an unexpected time")        \
+  XX(HEADER_OVERFLOW,                                                \
+     "too many header bytes seen; overflow detected")                \
+  XX(CLOSED_CONNECTION,                                              \
+     "data received after completed connection: close message")      \
+  XX(INVALID_VERSION, "invalid HTTP version")                        \
+  XX(INVALID_STATUS, "invalid HTTP status code")                     \
+  XX(INVALID_METHOD, "invalid HTTP method")                          \
+  XX(INVALID_URL, "invalid URL")                                     \
+  XX(INVALID_HOST, "invalid host")                                   \
+  XX(INVALID_PORT, "invalid port")                                   \
+  XX(INVALID_PATH, "invalid path")                                   \
+  XX(INVALID_QUERY_STRING, "invalid query string")                   \
+  XX(INVALID_FRAGMENT, "invalid fragment")                           \
+  XX(LF_EXPECTED, "LF character expected")                           \
+  XX(INVALID_HEADER_TOKEN, "invalid character in header")            \
+  XX(INVALID_CONTENT_LENGTH,                                         \
+     "invalid character in content-length header")                   \
+  XX(INVALID_CHUNK_SIZE,                                             \
+     "invalid character in chunk size header")                       \
+  XX(INVALID_CONSTANT, "invalid constant string")                    \
+  XX(INVALID_INTERNAL_STATE, "encountered unexpected internal state")\
+  XX(STRICT, "strict mode assertion failed")                         \
+  XX(UNKNOWN, "an unknown error occurred")
+
+
+/* Define HPE_* values for each errno value above */
+#define HTTP_ERRNO_GEN(n, s) HPE_##n,
+enum http_errno {
+  HTTP_ERRNO_MAP(HTTP_ERRNO_GEN)
+};
+#undef HTTP_ERRNO_GEN
+
+
+/* Get an http_errno value from an http_parser */
+#define HTTP_PARSER_ERRNO(p)            ((enum http_errno) (p)->http_errno)
+
+/* Get the line number that generated the current error */
+#if HTTP_PARSER_DEBUG
+#define HTTP_PARSER_ERRNO_LINE(p)       ((p)->error_lineno)
+#else
+#define HTTP_PARSER_ERRNO_LINE(p)       0
+#endif
+
+
+struct http_parser {
+  /** PRIVATE **/
+  unsigned char numerichost;
+  unsigned char type : 2;
+  unsigned char flags : 6; /* F_* values from 'flags' enum; semi-public */
+  unsigned char state;
+  unsigned char header_state;
+  unsigned char index;
+
+  uint32_t nread;
+  int64_t content_length;
+
+  /** READ-ONLY **/
+  unsigned short http_major;
+  unsigned short http_minor;
+  unsigned short status_code; /* responses only */
+  unsigned char method;    /* requests only */
+  unsigned char http_errno : 7;
+
+  /* 1 = Upgrade header was present and the parser has exited because of that.
+   * 0 = No upgrade header present.
+   * Should be checked when http_parser_execute() returns in addition to
+   * error checking.
+   */
+  unsigned char upgrade : 1;
+
+#if HTTP_PARSER_DEBUG
+  uint32_t error_lineno;
+#endif
+
+  /** PUBLIC **/
+  void *data; /* A pointer to get hook to the "connection" or "socket" object */
+};
+
+
+struct http_parser_settings {
+  http_cb      on_message_begin;
+  http_data_cb on_url;
+  http_data_cb on_header_field;
+  http_data_cb on_header_value;
+  http_cb      on_headers_complete;
+  http_data_cb on_body;
+  http_cb      on_message_complete;
+};
+
+
+void http_parser_init(http_parser *parser, enum http_parser_type type, char numerichost);
+
+
+size_t http_parser_execute(http_parser *parser,
+                           const http_parser_settings *settings,
+                           const char *data,
+                           size_t len);
+
+
+/* If http_should_keep_alive() in the on_headers_complete or
+ * on_message_complete callback returns true, then this will be should be
+ * the last message on the connection.
+ * If you are the server, respond with the "Connection: close" header.
+ * If you are the client, close the connection.
+ */
+int http_should_keep_alive(http_parser *parser);
+
+/* Returns a string version of the HTTP method. */
+const char *http_method_str(enum http_method m);
+
+/* Return a string name of the given error */
+const char *http_errno_name(enum http_errno err);
+
+/* Return a string description of the given error */
+const char *http_errno_description(enum http_errno err);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/src/http_request.c b/src/http_request.c
new file mode 100644 (file)
index 0000000..656ccee
--- /dev/null
@@ -0,0 +1,238 @@
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#include "http_request.h"
+#include "http_parser.h"
+
+struct http_request_s {
+       http_parser parser;
+       http_parser_settings parser_settings;
+
+       const char *method;
+       char *url;
+
+       char **headers;
+       int headers_size;
+       int headers_index;
+
+       char *data;
+       int datalen;
+
+       int complete;
+};
+
+static int
+on_url(http_parser *parser, const char *at, size_t length)
+{
+       http_request_t *request = parser->data;
+       int urllen = request->url ? strlen(request->url) : 0;
+
+       request->url = realloc(request->url, urllen+length+1);
+       assert(request->url);
+
+       request->url[urllen] = '\0';
+       strncat(request->url, at, length);
+       return 0;
+}
+
+static int
+on_header_field(http_parser *parser, const char *at, size_t length)
+{
+       http_request_t *request = parser->data;
+
+       /* Check if our index is a value */
+       if (request->headers_index%2 == 1) {
+               request->headers_index++;
+       }
+
+       /* Allocate space for new field-value pair */
+       if (request->headers_index == request->headers_size) {
+               request->headers_size += 2;
+               request->headers = realloc(request->headers,
+                                          request->headers_size*sizeof(char*));
+               assert(request->headers);
+               request->headers[request->headers_index] = NULL;
+               request->headers[request->headers_index+1] = NULL;
+       }
+
+       /* Allocate space in the current header string */
+       if (request->headers[request->headers_index] == NULL) {
+               request->headers[request->headers_index] = calloc(1, length+1);
+       } else {
+               request->headers[request->headers_index] = realloc(
+                       request->headers[request->headers_index],
+                       strlen(request->headers[request->headers_index])+length+1
+               );
+       }
+       assert(request->headers[request->headers_index]);
+
+       strncat(request->headers[request->headers_index], at, length);
+       return 0;
+}
+
+static int
+on_header_value(http_parser *parser, const char *at, size_t length)
+{
+       http_request_t *request = parser->data;
+
+       /* Check if our index is a field */
+       if (request->headers_index%2 == 0) {
+               request->headers_index++;
+       }
+
+       /* Allocate space in the current header string */
+       if (request->headers[request->headers_index] == NULL) {
+               request->headers[request->headers_index] = calloc(1, length+1);
+       } else {
+               request->headers[request->headers_index] = realloc(
+                       request->headers[request->headers_index],
+                       strlen(request->headers[request->headers_index])+length+1
+               );
+       }
+       assert(request->headers[request->headers_index]);
+
+       strncat(request->headers[request->headers_index], at, length);
+       return 0;
+}
+
+static int
+on_body(http_parser *parser, const char *at, size_t length)
+{
+       http_request_t *request = parser->data;
+
+       request->data = realloc(request->data, request->datalen+length);
+       assert(request->data);
+
+       memcpy(request->data+request->datalen, at, length);
+       request->datalen += length;
+       return 0;
+}
+
+static int
+on_message_complete(http_parser *parser)
+{
+       http_request_t *request = parser->data;
+
+       request->method = http_method_str(request->parser.method);
+       request->complete = 1;
+       return 0;
+}
+
+http_request_t *
+http_request_init(int numerichost)
+{
+       http_request_t *request;
+
+       request = calloc(1, sizeof(http_request_t));
+       if (!request) {
+               return NULL;
+       }
+       http_parser_init(&request->parser, HTTP_REQUEST, !!numerichost);
+       request->parser.data = request;
+
+       request->parser_settings.on_url = &on_url;
+       request->parser_settings.on_header_field = &on_header_field;
+       request->parser_settings.on_header_value = &on_header_value;
+       request->parser_settings.on_body = &on_body;
+       request->parser_settings.on_message_complete = &on_message_complete;
+
+       return request;
+}
+
+void
+http_request_destroy(http_request_t *request)
+{
+       int i;
+
+       if (request) {
+               free(request->url);
+               for (i=0; i<request->headers_size; i++) {
+                       free(request->headers[i]);
+               }
+               free(request->headers);
+               free(request->data);
+               free(request);
+       }
+}
+
+int
+http_request_add_data(http_request_t *request, const char *data, int datalen)
+{
+       int ret;
+
+       assert(request);
+
+       ret = http_parser_execute(&request->parser,
+                                 &request->parser_settings,
+                                 data, datalen);
+       return ret;
+}
+
+int
+http_request_is_complete(http_request_t *request)
+{
+       assert(request);
+       return request->complete;
+}
+
+int
+http_request_has_error(http_request_t *request)
+{
+       assert(request);
+       return (HTTP_PARSER_ERRNO(&request->parser) != HPE_OK);
+}
+
+const char *
+http_request_get_error_name(http_request_t *request)
+{
+       assert(request);
+       return http_errno_name(HTTP_PARSER_ERRNO(&request->parser));
+}
+
+const char *
+http_request_get_error_description(http_request_t *request)
+{
+       assert(request);
+       return http_errno_description(HTTP_PARSER_ERRNO(&request->parser));
+}
+
+const char *
+http_request_get_method(http_request_t *request)
+{
+       assert(request);
+       return request->method;
+}
+
+const char *
+http_request_get_url(http_request_t *request)
+{
+       assert(request);
+       return request->url;
+}
+
+const char *
+http_request_get_header(http_request_t *request, const char *name)
+{
+       int i;
+
+       assert(request);
+
+       for (i=0; i<request->headers_size; i+=2) {
+               if (!strcmp(request->headers[i], name)) {
+                       return request->headers[i+1];
+               }
+       }
+       return NULL;
+}
+
+const char *
+http_request_get_data(http_request_t *request, int *datalen)
+{
+       assert(request);
+
+       if (datalen) {
+               *datalen = request->datalen;
+       }
+       return request->data;
+}
diff --git a/src/http_request.h b/src/http_request.h
new file mode 100644 (file)
index 0000000..2323af5
--- /dev/null
@@ -0,0 +1,22 @@
+#ifndef HTTP_REQUEST_H
+#define HTTP_REQUEST_H
+
+typedef struct http_request_s http_request_t;
+
+
+http_request_t *http_request_init(int numerichost);
+
+int http_request_add_data(http_request_t *request, const char *data, int datalen);
+int http_request_is_complete(http_request_t *request);
+int http_request_has_error(http_request_t *request);
+
+const char *http_request_get_error_name(http_request_t *request);
+const char *http_request_get_error_description(http_request_t *request);
+const char *http_request_get_method(http_request_t *request);
+const char *http_request_get_url(http_request_t *request);
+const char *http_request_get_header(http_request_t *request, const char *name);
+const char *http_request_get_data(http_request_t *request, int *datalen);
+
+void http_request_destroy(http_request_t *request);
+
+#endif
diff --git a/src/http_response.c b/src/http_response.c
new file mode 100644 (file)
index 0000000..c3fe6c8
--- /dev/null
@@ -0,0 +1,133 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+
+#include "http_response.h"
+
+struct http_response_s {
+       int complete;
+
+       char *data;
+       int data_size;
+       int data_length;
+};
+
+
+static void
+http_response_add_data(http_response_t *response, const char *data, int datalen)
+{
+       int newdatasize;
+
+       assert(response);
+       assert(data);
+       assert(datalen > 0);
+
+       newdatasize = response->data_size;
+       while (response->data_size+datalen > newdatasize) {
+               newdatasize *= 2;
+       }
+       if (newdatasize != response->data_size) {
+               response->data = realloc(response->data, newdatasize);
+               assert(response->data);
+       }
+       memcpy(response->data+response->data_length, data, datalen);
+       response->data_length += datalen;
+}
+
+http_response_t *
+http_response_init(const char *protocol, int code, const char *message)
+{
+       http_response_t *response;
+       char codestr[4];
+
+       assert(code >= 100 && code < 1000);
+
+       /* Convert code into string */
+       memset(codestr, 0, sizeof(codestr));
+       snprintf(codestr, sizeof(codestr), "%u", code);
+
+       response = calloc(1, sizeof(http_response_t));
+       if (!response) {
+               return NULL;
+       }
+
+       /* Allocate response data */
+       response->data_size = 1024;
+       response->data = malloc(response->data_size);
+       if (!response->data) {
+               free(response);
+               return NULL;
+       }
+
+       /* Add first line of response to the data array */
+       http_response_add_data(response, protocol, strlen(protocol));
+       http_response_add_data(response, " ", 1);
+       http_response_add_data(response, codestr, strlen(codestr));
+       http_response_add_data(response, " ", 1);
+       http_response_add_data(response, message, strlen(message));
+       http_response_add_data(response, "\r\n", 2);
+
+       return response;
+}
+
+void
+http_response_destroy(http_response_t *response)
+{
+       if (response) {
+               free(response->data);
+               free(response);
+       }
+}
+
+void
+http_response_add_header(http_response_t *response, const char *name, const char *value)
+{
+       assert(response);
+       assert(name);
+       assert(value);
+
+       http_response_add_data(response, name, strlen(name));
+       http_response_add_data(response, ": ", 2);
+       http_response_add_data(response, value, strlen(value));
+       http_response_add_data(response, "\r\n", 2);
+}
+
+void
+http_response_finish(http_response_t *response, const char *data, int datalen)
+{
+       assert(response);
+       assert(datalen==0 || (data && datalen > 0));
+
+       if (data && datalen > 0) {
+               const char *hdrname = "Content-Length";
+               char hdrvalue[16];
+
+               memset(hdrvalue, 0, sizeof(hdrvalue));
+               snprintf(hdrvalue, sizeof(hdrvalue)-1, "%d", datalen);
+
+               /* Add Content-Length header first */
+               http_response_add_data(response, hdrname, strlen(hdrname));
+               http_response_add_data(response, ": ", 2);
+               http_response_add_data(response, hdrvalue, strlen(hdrvalue));
+               http_response_add_data(response, "\r\n\r\n", 4);
+
+               /* Add data to the end of response */
+               http_response_add_data(response, data, datalen);
+       } else {
+               /* Add extra end of line after headers */
+               http_response_add_data(response, "\r\n", 2);
+       }
+       response->complete = 1;
+}
+
+const char *
+http_response_get_data(http_response_t *response, int *datalen)
+{
+       assert(response);
+       assert(datalen);
+       assert(response->complete);
+
+       *datalen = response->data_length;
+       return response->data;
+}
diff --git a/src/http_response.h b/src/http_response.h
new file mode 100644 (file)
index 0000000..2e813f9
--- /dev/null
@@ -0,0 +1,15 @@
+#ifndef HTTP_RESPONSE_H
+#define HTTP_RESPONSE_H
+
+typedef struct http_response_s http_response_t;
+
+http_response_t *http_response_init(const char *protocol, int code, const char *message);
+
+void http_response_add_header(http_response_t *response, const char *name, const char *value);
+void http_response_finish(http_response_t *response, const char *data, int datalen);
+
+const char *http_response_get_data(http_response_t *response, int *datalen);
+
+void http_response_destroy(http_response_t *response);
+
+#endif
diff --git a/src/httpd.c b/src/httpd.c
new file mode 100644 (file)
index 0000000..8a5dcba
--- /dev/null
@@ -0,0 +1,339 @@
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <assert.h>
+
+#include "httpd.h"
+#include "netutils.h"
+#include "http_request.h"
+#include "compat.h"
+#include "logger.h"
+
+struct http_connection_s {
+       int connected;
+
+       int socket_fd;
+       void *user_data;
+       http_request_t *request;
+};
+typedef struct http_connection_s http_connection_t;
+
+struct httpd_s {
+       logger_t *logger;
+       httpd_callbacks_t callbacks;
+
+       int use_rtsp;
+
+       int max_connections;
+       http_connection_t *connections;
+
+       /* These variables only edited mutex locked */
+       int running;
+       int joined;
+       thread_handle_t thread;
+       mutex_handle_t run_mutex;
+
+       /* Server fd for accepting connections */
+       int server_fd;
+};
+
+httpd_t *
+httpd_init(logger_t *logger, httpd_callbacks_t *callbacks, int max_connections, int use_rtsp)
+{
+       httpd_t *httpd;
+
+       assert(logger);
+       assert(callbacks);
+       assert(max_connections > 0);
+
+       /* Allocate the httpd_t structure */
+       httpd = calloc(1, sizeof(httpd_t));
+       if (!httpd) {
+               return NULL;
+       }
+
+       httpd->use_rtsp = !!use_rtsp;
+       httpd->max_connections = max_connections;
+       httpd->connections = calloc(max_connections, sizeof(http_connection_t));
+       if (!httpd->connections) {
+               free(httpd);
+               return NULL;
+       }
+
+       /* Use the logger provided */
+       httpd->logger = logger;
+
+       /* Save callback pointers */
+       memcpy(&httpd->callbacks, callbacks, sizeof(httpd_callbacks_t));
+
+       /* Initial status joined */
+       httpd->running = 0;
+       httpd->joined = 1;
+
+       return httpd;
+}
+
+void
+httpd_destroy(httpd_t *httpd)
+{
+       if (httpd) {
+               httpd_stop(httpd);
+
+               free(httpd->connections);
+               free(httpd);
+       }
+}
+
+static void
+httpd_add_connection(httpd_t *httpd, int fd, unsigned char *local, int local_len, unsigned char *remote, int remote_len)
+{
+       int i;
+
+       for (i=0; i<httpd->max_connections; i++) {
+               if (!httpd->connections[i].connected) {
+                       break;
+               }
+       }
+       if (i == httpd->max_connections) {
+               logger_log(httpd->logger, LOGGER_INFO, "Max connections reached\n");
+               shutdown(fd, SHUT_RDWR);
+               closesocket(fd);
+               return;
+       }
+
+       httpd->connections[i].socket_fd = fd;
+       httpd->connections[i].connected = 1;
+       httpd->connections[i].user_data = httpd->callbacks.conn_init(httpd->callbacks.opaque, local, local_len, remote, remote_len);
+}
+
+static void
+httpd_remove_connection(httpd_t *httpd, http_connection_t *connection)
+{
+       if (connection->request) {
+               http_request_destroy(connection->request);
+               connection->request = NULL;
+       }
+       httpd->callbacks.conn_destroy(connection->user_data);
+       shutdown(connection->socket_fd, SHUT_WR);
+       closesocket(connection->socket_fd);
+       connection->connected = 0;
+}
+
+static THREAD_RETVAL
+httpd_thread(void *arg)
+{
+       httpd_t *httpd = arg;
+       char buffer[1024];
+       int i;
+
+       assert(httpd);
+
+       while (1) {
+               fd_set rfds;
+               struct timeval tv;
+               int nfds=0;
+               int ret;
+
+               MUTEX_LOCK(httpd->run_mutex);
+               if (!httpd->running) {
+                       MUTEX_UNLOCK(httpd->run_mutex);
+                       break;
+               }
+               MUTEX_UNLOCK(httpd->run_mutex);
+
+               /* Set timeout value to 5ms */
+               tv.tv_sec = 1;
+               tv.tv_usec = 5000;
+
+               /* Get the correct nfds value and set rfds */
+               FD_ZERO(&rfds);
+               FD_SET(httpd->server_fd, &rfds);
+               nfds = httpd->server_fd+1;
+               for (i=0; i<httpd->max_connections; i++) {
+                       int socket_fd;
+                       if (!httpd->connections[i].connected) {
+                               continue;
+                       }
+                       socket_fd = httpd->connections[i].socket_fd;
+                       FD_SET(socket_fd, &rfds);
+                       if (nfds <= socket_fd) {
+                               nfds = socket_fd+1;
+                       }
+               }
+
+               ret = select(nfds, &rfds, NULL, NULL, &tv);
+               if (ret == 0) {
+                       /* Timeout happened */
+                       continue;
+               } else if (ret == -1) {
+                       /* FIXME: Error happened */
+                       logger_log(httpd->logger, LOGGER_INFO, "Error in select\n");
+                       break;
+               }
+
+               if (FD_ISSET(httpd->server_fd, &rfds)) {
+                       struct sockaddr_storage remote_saddr;
+                       socklen_t remote_saddrlen;
+                       struct sockaddr_storage local_saddr;
+                       socklen_t local_saddrlen;
+                       unsigned char *local, *remote;
+                       int local_len, remote_len;
+                       int fd;
+
+                       remote_saddrlen = sizeof(remote_saddr);
+                       fd = accept(httpd->server_fd, (struct sockaddr *)&remote_saddr, &remote_saddrlen);
+                       if (fd == -1) {
+                               /* FIXME: Error happened */
+                               break;
+                       }
+
+                       local_saddrlen = sizeof(local_saddr);
+                       ret = getsockname(fd, (struct sockaddr *)&local_saddr, &local_saddrlen);
+                       if (ret == -1) {
+                               closesocket(fd);
+                               continue;
+                       }
+
+                       logger_log(httpd->logger, LOGGER_INFO, "Accepted client on socket %d\n", fd);
+                       local = netutils_get_address(&local_saddr, &local_len);
+                       remote = netutils_get_address(&remote_saddr, &remote_len);
+
+                       httpd_add_connection(httpd, fd, local, local_len, remote, remote_len);
+               }
+               for (i=0; i<httpd->max_connections; i++) {
+                       http_connection_t *connection = &httpd->connections[i];
+
+                       if (!connection->connected) {
+                               continue;
+                       }
+                       if (!FD_ISSET(connection->socket_fd, &rfds)) {
+                               continue;
+                       }
+
+                       /* If not in the middle of request, allocate one */
+                       if (!connection->request) {
+                               connection->request = http_request_init(httpd->use_rtsp);
+                               assert(connection->request);
+                       }
+
+                       logger_log(httpd->logger, LOGGER_INFO, "Receiving on socket %d\n", httpd->connections[i].socket_fd);
+                       ret = recv(connection->socket_fd, buffer, sizeof(buffer), 0);
+                       if (ret == 0) {
+                               logger_log(httpd->logger, LOGGER_INFO, "Connection closed\n");
+                               httpd_remove_connection(httpd, connection);
+                               continue;
+                       }
+
+                       /* Parse HTTP request from data read from connection */
+                       http_request_add_data(connection->request, buffer, ret);
+                       if (http_request_has_error(connection->request)) {
+                               logger_log(httpd->logger, LOGGER_INFO, "Error in parsing: %s\n", http_request_get_error_name(connection->request));
+                               httpd_remove_connection(httpd, connection);
+                               continue;
+                       }
+
+                       /* If request is finished, process and deallocate */
+                       if (http_request_is_complete(connection->request)) {
+                               http_response_t *response = NULL;
+
+                               httpd->callbacks.conn_request(connection->user_data, connection->request, &response);
+                               http_request_destroy(connection->request);
+                               connection->request = NULL;
+
+                               if (response) {
+                                       const char *data;
+                                       int datalen;
+                                       int written;
+                                       int ret;
+
+                                       /* Get response data and datalen */
+                                       data = http_response_get_data(response, &datalen);
+
+                                       written = 0;
+                                       while (written < datalen) {
+                                               ret = send(connection->socket_fd, data+written, datalen-written, 0);
+                                               if (ret == -1) {
+                                                       /* FIXME: Error happened */
+                                                       logger_log(httpd->logger, LOGGER_INFO, "Error in sending data\n");
+                                                       break;
+                                               }
+                                               written += ret;
+                                       }
+                               } else {
+                                       logger_log(httpd->logger, LOGGER_INFO, "Didn't get response\n");
+                               }
+                               http_response_destroy(response);
+                       }
+               }
+       }
+
+       /* Remove all connections that are still connected */
+       for (i=0; i<httpd->max_connections; i++) {
+               http_connection_t *connection = &httpd->connections[i];
+
+               if (!connection->connected) {
+                       continue;
+               }
+               logger_log(httpd->logger, LOGGER_INFO, "Removing connection\n");
+               httpd_remove_connection(httpd, connection);
+       }
+
+       logger_log(httpd->logger, LOGGER_INFO, "Exiting thread\n");
+
+       return 0;
+}
+
+int
+httpd_start(httpd_t *httpd, unsigned short *port)
+{
+       assert(httpd);
+       assert(port);
+
+       MUTEX_LOCK(httpd->run_mutex);
+       if (httpd->running || !httpd->joined) {
+               MUTEX_UNLOCK(httpd->run_mutex);
+               return 0;
+       }
+
+       httpd->server_fd = netutils_init_socket(port, 1, 0);
+       if (httpd->server_fd == -1) {
+               logger_log(httpd->logger, LOGGER_INFO, "Error initialising socket %d\n", SOCKET_GET_ERROR());
+               MUTEX_UNLOCK(httpd->run_mutex);
+               return -1;
+       }
+       if (listen(httpd->server_fd, 5) == -1) {
+               logger_log(httpd->logger, LOGGER_INFO, "Error listening to socket\n");
+               MUTEX_UNLOCK(httpd->run_mutex);
+               return -2;
+       }
+       logger_log(httpd->logger, LOGGER_INFO, "Initialized server socket\n");
+
+       /* Set values correctly and create new thread */
+       httpd->running = 1;
+       httpd->joined = 0;
+       THREAD_CREATE(httpd->thread, httpd_thread, httpd);
+       MUTEX_UNLOCK(httpd->run_mutex);
+
+       return 1;
+}
+
+void
+httpd_stop(httpd_t *httpd)
+{
+       assert(httpd);
+
+       MUTEX_LOCK(httpd->run_mutex);
+       if (!httpd->running || httpd->joined) {
+               MUTEX_UNLOCK(httpd->run_mutex);
+               return;
+       }
+       httpd->running = 0;
+       MUTEX_UNLOCK(httpd->run_mutex);
+
+       THREAD_JOIN(httpd->thread);
+
+       MUTEX_LOCK(httpd->run_mutex);
+       httpd->joined = 1;
+       MUTEX_UNLOCK(httpd->run_mutex);
+}
+
diff --git a/src/httpd.h b/src/httpd.h
new file mode 100644 (file)
index 0000000..08062ed
--- /dev/null
@@ -0,0 +1,27 @@
+#ifndef HTTPD_H
+#define HTTPD_H
+
+#include "logger.h"
+#include "http_request.h"
+#include "http_response.h"
+
+typedef struct httpd_s httpd_t;
+
+struct httpd_callbacks_s {
+       void* opaque;
+       void* (*conn_init)(void *opaque, unsigned char *local, int locallen, unsigned char *remote, int remotelen);
+       void  (*conn_request)(void *ptr, http_request_t *request, http_response_t **response);
+       void  (*conn_destroy)(void *ptr);
+};
+typedef struct httpd_callbacks_s httpd_callbacks_t;
+
+
+httpd_t *httpd_init(logger_t *logger, httpd_callbacks_t *callbacks, int max_connections, int use_rtsp);
+
+int httpd_start(httpd_t *httpd, unsigned short *port);
+void httpd_stop(httpd_t *httpd);
+
+void httpd_destroy(httpd_t *httpd);
+
+
+#endif
diff --git a/src/logger.c b/src/logger.c
new file mode 100644 (file)
index 0000000..0ea1867
--- /dev/null
@@ -0,0 +1,90 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <assert.h>
+
+#include "logger.h"
+
+void
+logger_init(logger_t *logger)
+{
+       assert(logger);
+
+       logger->level = LOGGER_INFO;
+       logger->callback = NULL;
+}
+
+void
+logger_set_level(logger_t *logger, int level)
+{
+       assert(logger);
+
+       logger->level = level;
+}
+
+void
+logger_set_callback(logger_t *logger, logger_callback_t callback)
+{
+       assert(logger);
+
+       logger->callback = callback;
+}
+
+static char *
+logger_utf8_to_local(const char *str)
+{
+       char *ret = NULL;
+
+/* FIXME: This is only implemented on Windows for now */
+#if defined(_WIN32) || defined(_WIN64)
+       int wclen, mblen;
+       WCHAR *wcstr;
+       BOOL failed;
+
+       wclen = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
+       wcstr = malloc(sizeof(WCHAR) * wclen);
+       MultiByteToWideChar(CP_UTF8, 0, str, -1, wcstr, wclen);
+
+       mblen = WideCharToMultiByte(CP_ACP, 0, wcstr, wclen, NULL, 0, NULL, &failed);
+       if (failed) {
+               /* Invalid characters in input, conversion failed */
+               free(wcstr);
+               return NULL;
+       }
+
+       ret = malloc(sizeof(CHAR) * mblen);
+       WideCharToMultiByte(CP_ACP, 0, wcstr, wclen, ret, mblen, NULL, NULL);
+       free(wcstr);
+#endif
+
+       return ret;
+}
+
+void
+logger_log(logger_t *logger, int level, const char *fmt, ...)
+{
+       char buffer[4096];
+       va_list ap;
+
+       if (level > logger->level)
+               return;
+
+       buffer[sizeof(buffer)-1] = '\0';
+       va_start(ap, fmt);
+       vsnprintf(buffer, sizeof(buffer)-1, fmt, ap);
+       va_end(ap);
+
+       if (logger->callback) {
+               logger->callback(level, buffer);
+       } else {
+               char *local = logger_utf8_to_local(buffer);
+
+               if (local) {
+                       fprintf(stderr, "%s", local);
+                       free(local);
+               } else {
+                       fprintf(stderr, "%s", buffer);
+               }
+       }
+}
+
diff --git a/src/logger.h b/src/logger.h
new file mode 100644 (file)
index 0000000..ba8b95f
--- /dev/null
@@ -0,0 +1,28 @@
+#ifndef LOGGER_H
+#define LOGGER_H
+
+/* Define syslog style log levels */
+#define LOGGER_EMERG       0       /* system is unusable */
+#define LOGGER_ALERT       1       /* action must be taken immediately */
+#define LOGGER_CRIT        2       /* critical conditions */
+#define LOGGER_ERR         3       /* error conditions */
+#define LOGGER_WARNING     4       /* warning conditions */
+#define LOGGER_NOTICE      5       /* normal but significant condition */
+#define LOGGER_INFO        6       /* informational */
+#define LOGGER_DEBUG       7       /* debug-level messages */
+
+typedef void (*logger_callback_t)(int level, char *msg);
+
+struct logger_s {
+       int level;
+       logger_callback_t callback;
+};
+typedef struct logger_s logger_t;
+
+void logger_init(logger_t *logger);
+void logger_set_level(logger_t *logger, int level);
+void logger_set_callback(logger_t *logger, logger_callback_t callback);
+
+void logger_log(logger_t *logger, int level, const char *fmt, ...);
+
+#endif
diff --git a/src/memalign.h b/src/memalign.h
new file mode 100644 (file)
index 0000000..422e241
--- /dev/null
@@ -0,0 +1,39 @@
+#ifndef MEMALIGN_H
+#define MEMALIGN_H
+
+#if defined(WIN32)
+
+#define SYSTEM_GET_PAGESIZE(ret) do {\
+       SYSTEM_INFO si;\
+       GetSystemInfo(&si);\
+       ret = si.dwPageSize;\
+} while(0)
+#define SYSTEM_GET_TIME(ret) ret = timeGetTime()
+
+#define ALIGNED_MALLOC(memptr, alignment, size) do {\
+       char *ptr = malloc(sizeof(void*) + (size) + (alignment)-1);\
+       memptr = NULL;\
+       if (ptr) {\
+               size_t ptrval = (size_t)ptr + sizeof(void*) + (alignment)-1;\
+               ptrval = ptrval / (alignment) * (alignment);\
+               memptr = (void *)ptrval;\
+               *(((void **)memptr)-1) = ptr;\
+       }\
+} while(0)
+#define ALIGNED_FREE(memptr) free(*(((void **)memptr)-1))
+
+#else
+
+#define SYSTEM_GET_PAGESIZE(ret) ret = sysconf(_SC_PAGESIZE)
+#define SYSTEM_GET_TIME(ret) do {\
+       struct timeval tv;\
+       gettimeofday(&tv, NULL);\
+       ret = (unsigned int)(tv.tv_sec*1000 + tv.tv_usec/1000);\
+} while(0)
+
+#define ALIGNED_MALLOC(memptr, alignment, size) if (posix_memalign((void **)&memptr, alignment, size)) memptr = NULL
+#define ALIGNED_FREE(memptr) free(memptr)
+
+#endif
+
+#endif
diff --git a/src/netutils.c b/src/netutils.c
new file mode 100644 (file)
index 0000000..255822b
--- /dev/null
@@ -0,0 +1,139 @@
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#include "compat.h"
+
+int
+netutils_init()
+{
+#ifdef WIN32
+       WORD wVersionRequested;
+       WSADATA wsaData;
+       int ret;
+
+       wVersionRequested = MAKEWORD(2, 2);
+       ret = WSAStartup(wVersionRequested, &wsaData);
+       if (ret) {
+               return -1;
+       }
+
+       if (LOBYTE(wsaData.wVersion) != 2 ||
+           HIBYTE(wsaData.wVersion) != 2) {
+               /* Version mismatch, requested version not found */
+               return -1;
+       }
+#endif
+       return 0;
+}
+
+void
+netutils_cleanup()
+{
+#ifdef WIN32
+       WSACleanup();
+#endif
+}
+
+int
+netutils_init_socket(unsigned short *port, int use_ipv6, int use_udp)
+{
+       int family = use_ipv6 ? AF_INET6 : AF_INET;
+       int type = use_udp ? SOCK_DGRAM : SOCK_STREAM;
+       int proto = use_udp ? IPPROTO_UDP : IPPROTO_TCP;
+
+       struct sockaddr_storage saddr;
+       socklen_t socklen;
+       int server_fd;
+       int ret;
+
+       assert(port);
+
+       server_fd = socket(family, type, proto);
+       if (server_fd == -1) {
+               goto cleanup;
+       }
+
+       memset(&saddr, 0, sizeof(saddr));
+       if (use_ipv6) {
+               struct sockaddr_in6 *sin6ptr = (struct sockaddr_in6 *)&saddr;
+
+               /* Initialize sockaddr for bind */
+               sin6ptr->sin6_family = family;
+               sin6ptr->sin6_addr = in6addr_any;
+               sin6ptr->sin6_port = htons(*port);
+
+               socklen = sizeof(*sin6ptr);
+               ret = bind(server_fd, (struct sockaddr *)sin6ptr, socklen);
+               if (ret == -1) {
+                       goto cleanup;
+               }
+
+               ret = getsockname(server_fd, (struct sockaddr *)sin6ptr, &socklen);
+               if (ret == -1) {
+                       goto cleanup;
+               }
+               *port = ntohs(sin6ptr->sin6_port);
+       } else {
+               struct sockaddr_in *sinptr = (struct sockaddr_in *)&saddr;
+
+               /* Initialize sockaddr for bind */
+               sinptr->sin_family = family;
+               sinptr->sin_addr.s_addr = INADDR_ANY;
+               sinptr->sin_port = htons(*port);
+
+               socklen = sizeof(*sinptr);
+               ret = bind(server_fd, (struct sockaddr *)sinptr, socklen);
+               if (ret == -1) {
+                       goto cleanup;
+               }
+
+               ret = getsockname(server_fd, (struct sockaddr *)sinptr, &socklen);
+               if (ret == -1) {
+                       goto cleanup;
+               }
+               *port = ntohs(sinptr->sin_port);
+       }
+       return server_fd;
+
+cleanup:
+       ret = SOCKET_GET_ERROR();
+       if (server_fd != -1) {
+               closesocket(server_fd);
+       }
+       SOCKET_SET_ERROR(ret);
+       return -1;
+}
+
+unsigned char *
+netutils_get_address(void *sockaddr, int *length)
+{
+       unsigned char ipv4_prefix[] = { 0,0,0,0,0,0,0,0,0,0,255,255 };
+       struct sockaddr *address = sockaddr;
+
+       assert(address);
+       assert(length);
+
+       if (address->sa_family == AF_INET) {
+               struct sockaddr_in *sin;
+
+               sin = (struct sockaddr_in *)address;
+               *length = sizeof(sin->sin_addr.s_addr);
+               return (unsigned char *)&sin->sin_addr.s_addr;
+       } else if (address->sa_family == AF_INET6) {
+               struct sockaddr_in6 *sin6;
+
+               sin6 = (struct sockaddr_in6 *)address;
+               if (!memcmp(sin6->sin6_addr.s6_addr, ipv4_prefix, 12)) {
+                       /* Actually an embedded IPv4 address */
+                       *length = sizeof(sin6->sin6_addr.s6_addr)-12;
+                       return (sin6->sin6_addr.s6_addr+12);
+               }
+               *length = sizeof(sin6->sin6_addr.s6_addr);
+               return sin6->sin6_addr.s6_addr;
+       }
+
+       *length = 0;
+       return NULL;
+}
+
diff --git a/src/netutils.h b/src/netutils.h
new file mode 100644 (file)
index 0000000..c469162
--- /dev/null
@@ -0,0 +1,10 @@
+#ifndef NETUTILS_H
+#define NETUTILS_H
+
+int netutils_init();
+void netutils_cleanup();
+
+int netutils_init_socket(unsigned short *port, int use_ipv6, int use_udp);
+unsigned char *netutils_get_address(void *sockaddr, int *length);
+
+#endif
diff --git a/src/raop.c b/src/raop.c
new file mode 100644 (file)
index 0000000..a83bb98
--- /dev/null
@@ -0,0 +1,340 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+
+#include "raop.h"
+#include "raop_rtp.h"
+#include "rsakey.h"
+#include "httpd.h"
+#include "sdp.h"
+
+#include "global.h"
+#include "utils.h"
+#include "netutils.h"
+#include "logger.h"
+
+/* Actually 345 bytes for 2048-bit key */
+#define MAX_SIGNATURE_LEN 512
+
+struct raop_s {
+       /* Callbacks for audio */
+       raop_callbacks_t callbacks;
+
+       /* Logger instance */
+       logger_t logger;
+
+       /* HTTP daemon and RSA key */
+       httpd_t *httpd;
+       rsakey_t *rsakey;
+
+       /* Hardware address information */
+       unsigned char hwaddr[MAX_HWADDR_LEN];
+       int hwaddrlen;
+};
+
+struct raop_conn_s {
+       raop_t *raop;
+       raop_rtp_t *raop_rtp;
+
+       unsigned char *local;
+       int locallen;
+
+       unsigned char *remote;
+       int remotelen;
+};
+typedef struct raop_conn_s raop_conn_t;
+
+static void *
+conn_init(void *opaque, unsigned char *local, int locallen, unsigned char *remote, int remotelen)
+{
+       raop_conn_t *conn;
+       int i;
+
+       conn = calloc(1, sizeof(raop_conn_t));
+       if (!conn) {
+               return NULL;
+       }
+       conn->raop = opaque;
+       conn->raop_rtp = NULL;
+
+       logger_log(&conn->raop->logger, LOGGER_INFO, "Local: ");
+       for (i=0; i<locallen; i++) {
+               logger_log(&conn->raop->logger, LOGGER_INFO, "%02x", local[i]);
+       }
+       logger_log(&conn->raop->logger, LOGGER_INFO, "Remote: ");
+       for (i=0; i<remotelen; i++) {
+               logger_log(&conn->raop->logger, LOGGER_INFO, "%02x", remote[i]);
+       }
+       logger_log(&conn->raop->logger, LOGGER_INFO, "\n");
+
+       conn->local = malloc(locallen);
+       assert(conn->local);
+       memcpy(conn->local, local, locallen);
+
+       conn->remote = malloc(remotelen);
+       assert(conn->remote);
+       memcpy(conn->remote, remote, remotelen);
+
+       conn->locallen = locallen;
+       conn->remotelen = remotelen;
+       return conn;
+}
+
+static void
+conn_request(void *ptr, http_request_t *request, http_response_t **response)
+{
+       raop_conn_t *conn = ptr;
+       raop_t *raop = conn->raop;
+
+       http_response_t *res;
+       const char *method;
+       const char *cseq;
+       const char *challenge;
+
+       method = http_request_get_method(request);
+       cseq = http_request_get_header(request, "CSeq");
+       if (!method || !cseq) {
+               return;
+       }
+
+       res = http_response_init("RTSP/1.0", 200, "OK");
+       http_response_add_header(res, "CSeq", cseq);
+       http_response_add_header(res, "Apple-Jack-Status", "connected; type=analog");
+
+       challenge = http_request_get_header(request, "Apple-Challenge");
+       if (challenge) {
+               char signature[MAX_SIGNATURE_LEN];
+
+               memset(signature, 0, sizeof(signature));
+               rsakey_sign(raop->rsakey, signature, sizeof(signature), challenge,
+                           conn->local, conn->locallen, raop->hwaddr, raop->hwaddrlen);
+               logger_log(&conn->raop->logger, LOGGER_INFO, "Got signature: %s\n", signature);
+               http_response_add_header(res, "Apple-Response", signature);
+       }
+       if (!strcmp(method, "OPTIONS")) {
+               http_response_add_header(res, "Public", "ANNOUNCE, SETUP, RECORD, PAUSE, FLUSH, TEARDOWN, OPTIONS, GET_PARAMETER, SET_PARAMETER");
+       } else if (!strcmp(method, "ANNOUNCE")) {
+               const char *data;
+               int datalen;
+
+               unsigned char aeskey[16];
+               unsigned char aesiv[16];
+               int aeskeylen, aesivlen;
+
+               data = http_request_get_data(request, &datalen);
+               if (data) {
+                       sdp_t *sdp = sdp_init(data, datalen);
+                       logger_log(&conn->raop->logger, LOGGER_INFO, "rsaaeskey: %s\n", sdp_get_rsaaeskey(sdp));
+                       logger_log(&conn->raop->logger, LOGGER_INFO, "aesiv: %s\n", sdp_get_aesiv(sdp));
+
+                       aeskeylen = rsakey_decrypt(raop->rsakey, aeskey, sizeof(aeskey),
+                                                  sdp_get_rsaaeskey(sdp));
+                       aesivlen = rsakey_parseiv(raop->rsakey, aesiv, sizeof(aesiv),
+                                                 sdp_get_aesiv(sdp));
+                       logger_log(&conn->raop->logger, LOGGER_INFO, "aeskeylen: %d\n", aeskeylen);
+                       logger_log(&conn->raop->logger, LOGGER_INFO, "aesivlen: %d\n", aesivlen);
+
+                       conn->raop_rtp = raop_rtp_init(&raop->logger, &raop->callbacks, sdp_get_fmtp(sdp), aeskey, aesiv);
+                       sdp_destroy(sdp);
+               }
+       } else if (!strcmp(method, "SETUP")) {
+               unsigned short cport=0, tport=0, dport=0;
+               const char *transport;
+               char buffer[1024];
+               int use_udp;
+
+               transport = http_request_get_header(request, "Transport");
+               assert(transport);
+
+               logger_log(&conn->raop->logger, LOGGER_INFO, "Transport: %s\n", transport);
+               use_udp = strncmp(transport, "RTP/AVP/TCP", 11);
+
+               /* FIXME: Should use the parsed ports for resend */
+               raop_rtp_start(conn->raop_rtp, use_udp, 1234, 1234, &cport, &tport, &dport);
+               logger_log(&conn->raop->logger, LOGGER_INFO, "cport %d tport %d dport %d\n", cport, tport, dport);
+
+               memset(buffer, 0, sizeof(buffer));
+               if (use_udp) {
+                       snprintf(buffer, sizeof(buffer)-1,
+                                "RTP/AVP/UDP;unicast;mode=record;timing_port=%u;events;control_port=%u;server_port=%u",
+                                tport, cport, dport);
+               } else {
+                       snprintf(buffer, sizeof(buffer)-1,
+                                "RTP/AVP/TCP;unicast;interleaved=0-1;mode=record;server_port=%u",
+                                dport);
+               }
+               logger_log(&conn->raop->logger, LOGGER_INFO, "Responding with %s\n", buffer);
+               http_response_add_header(res, "Transport", buffer);
+               http_response_add_header(res, "Session", "DEADBEEF");
+       } else if (!strcmp(method, "SET_PARAMETER")) {
+               const char *data;
+               int datalen;
+               char *datastr;
+
+               data = http_request_get_data(request, &datalen);
+               datastr = calloc(1, datalen+1);
+               if (datastr) {
+                       memcpy(datastr, data, datalen);
+                       if (!strncmp(datastr, "volume: ", 8)) {
+                               float vol = 0.0;
+                               sscanf(data+8, "%f", &vol);
+                               raop_rtp_set_volume(conn->raop_rtp, vol);
+                       }
+               }
+       } else if (!strcmp(method, "FLUSH")) {
+               const char *rtpinfo;
+               int next_seq = -1;
+
+               rtpinfo = http_request_get_header(request, "RTP-Info");
+               assert(rtpinfo);
+
+               logger_log(&conn->raop->logger, LOGGER_INFO, "RTP-Info: %s\n", rtpinfo);
+               if (!strncmp(rtpinfo, "seq=", 4)) {
+                       next_seq = strtol(rtpinfo+4, NULL, 10);
+               }
+               raop_rtp_flush(conn->raop_rtp, next_seq);
+       } else if (!strcmp(method, "TEARDOWN")) {
+               http_response_add_header(res, "Connection", "close");
+               raop_rtp_stop(conn->raop_rtp);
+               raop_rtp_destroy(conn->raop_rtp);
+               conn->raop_rtp = NULL;
+       }
+       http_response_finish(res, NULL, 0);
+
+       logger_log(&conn->raop->logger, LOGGER_INFO, "Got request %s with URL %s\n", method, http_request_get_url(request));
+       *response = res;
+}
+
+static void
+conn_destroy(void *ptr)
+{
+       raop_conn_t *conn = ptr;
+
+       if (conn->raop_rtp) {
+               raop_rtp_destroy(conn->raop_rtp);
+       }
+       free(conn->local);
+       free(conn->remote);
+       free(conn);
+}
+
+raop_t *
+raop_init(raop_callbacks_t *callbacks, const char *pemkey, const char *hwaddr, int hwaddrlen)
+{
+       raop_t *raop;
+       httpd_t *httpd;
+       rsakey_t *rsakey;
+       httpd_callbacks_t httpd_cbs;
+
+       assert(callbacks);
+       assert(pemkey);
+       assert(hwaddr);
+
+       /* Initialize the network */
+       if (netutils_init() < 0) {
+               return NULL;
+       }
+
+       /* Validate the callbacks structure */
+       if (!callbacks->audio_init || !callbacks->audio_set_volume ||
+           !callbacks->audio_process || !callbacks->audio_flush ||
+           !callbacks->audio_destroy) {
+               return NULL;
+       }
+
+       /* Validate hardware address */
+       if (hwaddrlen > MAX_HWADDR_LEN) {
+               return NULL;
+       }
+
+       /* Allocate the raop_t structure */
+       raop = calloc(1, sizeof(raop_t));
+       if (!raop) {
+               return NULL;
+       }
+
+       /* Initialize the logger */
+       logger_init(&raop->logger);
+
+       /* Set HTTP callbacks to our handlers */
+       memset(&httpd_cbs, 0, sizeof(httpd_cbs));
+       httpd_cbs.opaque = raop;
+       httpd_cbs.conn_init = &conn_init;
+       httpd_cbs.conn_request = &conn_request;
+       httpd_cbs.conn_destroy = &conn_destroy;
+
+       /* Initialize the http daemon */
+       httpd = httpd_init(&raop->logger, &httpd_cbs, 10, 1);
+       if (!httpd) {
+               free(raop);
+               return NULL;
+       }
+
+       /* Copy callbacks structure */
+       memcpy(&raop->callbacks, callbacks, sizeof(raop_callbacks_t));
+
+       /* Initialize RSA key handler */
+       rsakey = rsakey_init_pem(pemkey);
+       if (!rsakey) {
+               free(httpd);
+               free(raop);
+               return NULL;
+       }
+
+       raop->httpd = httpd;
+       raop->rsakey = rsakey;
+
+       /* Copy hwaddr to resulting structure */
+       memcpy(raop->hwaddr, hwaddr, hwaddrlen);
+       raop->hwaddrlen = hwaddrlen;
+
+       return raop;
+}
+
+raop_t *
+raop_init_from_keyfile(raop_callbacks_t *callbacks, const char *keyfile, const char *hwaddr, int hwaddrlen)
+{
+       raop_t *raop;
+       char *pemstr;
+
+       if (utils_read_file(&pemstr, keyfile) < 0) {
+               return NULL;
+       }
+       raop = raop_init(callbacks, pemstr, hwaddr, hwaddrlen);
+       free(pemstr);
+       return raop;
+}
+
+void
+raop_destroy(raop_t *raop)
+{
+       if (raop) {
+               raop_stop(raop);
+
+               httpd_destroy(raop->httpd);
+               rsakey_destroy(raop->rsakey);
+               free(raop);
+
+               /* Cleanup the network */
+               netutils_cleanup();
+       }
+}
+
+int
+raop_start(raop_t *raop, unsigned short *port)
+{
+       assert(raop);
+       assert(port);
+
+       return httpd_start(raop->httpd, port);
+}
+
+void
+raop_stop(raop_t *raop)
+{
+       assert(raop);
+
+       httpd_stop(raop->httpd);
+}
+
diff --git a/src/raop_buffer.c b/src/raop_buffer.c
new file mode 100644 (file)
index 0000000..45a1aeb
--- /dev/null
@@ -0,0 +1,380 @@
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <math.h>
+
+#include "raop_buffer.h"
+#include "raop_rtp.h"
+#include "utils.h"
+
+#include <stdint.h>
+#include "crypto/crypto.h"
+#include "alac/alac.h"
+
+#define RAOP_BUFFER_LENGTH 16
+
+typedef struct {
+       /* Packet available */
+       int available;
+
+       /* RTP header */
+       unsigned char flags;
+       unsigned char type;
+       unsigned short seqnum;
+       unsigned int timestamp;
+       unsigned int ssrc;
+
+       /* Audio buffer of valid length */
+       int audio_buffer_size;
+       int audio_buffer_len;
+       void *audio_buffer;
+} raop_buffer_entry_t;
+
+struct raop_buffer_s {
+       /* AES key and IV */
+       unsigned char aeskey[RAOP_AESKEY_LEN];
+       unsigned char aesiv[RAOP_AESIV_LEN];
+
+       /* ALAC decoder */
+       ALACSpecificConfig alacConfig;
+       alac_file *alac;
+
+       /* First and last seqnum */
+       int is_empty;
+       unsigned short first_seqnum;
+       unsigned short last_seqnum;
+
+       /* RTP buffer entries */
+       raop_buffer_entry_t entries[RAOP_BUFFER_LENGTH];
+
+       /* Buffer of all audio buffers */
+       int buffer_size;
+       void *buffer;
+};
+
+
+
+static int
+get_fmtp_info(ALACSpecificConfig *config, const char *fmtp)
+{
+       int intarr[12];
+       char *strptr;
+       int i;
+
+       /* Parse fmtp string to integers */
+       strptr = strdup(fmtp);
+       for (i=0; i<12; i++) {
+               if (strptr == NULL) {
+                       free(strptr);
+                       return -1;
+               }
+               intarr[i] = atoi(utils_strsep(&strptr, " "));
+       }
+       free(strptr);
+       strptr = NULL;
+
+       /* Fill the config struct */
+       config->frameLength = intarr[1];
+       config->compatibleVersion = intarr[2];
+       config->bitDepth = intarr[3];
+       config->pb = intarr[4];
+       config->mb = intarr[5];
+       config->kb = intarr[6];
+       config->numChannels = intarr[7];
+       config->maxRun = intarr[8];
+       config->maxFrameBytes = intarr[9];
+       config->avgBitRate = intarr[10];
+       config->sampleRate = intarr[11];
+
+       /* Validate supported audio types */
+       if (config->bitDepth != 16) {
+               return -2;
+       }
+       if (config->numChannels != 2) {
+               return -3;
+       }
+
+       return 0;
+}
+
+static void
+set_decoder_info(alac_file *alac, ALACSpecificConfig *config)
+{
+       unsigned char decoder_info[48];
+       memset(decoder_info, 0, sizeof(decoder_info));
+
+#define SET_UINT16(buf, value)do{\
+       (buf)[0] = (unsigned char)((value) >> 8);\
+       (buf)[1] = (unsigned char)(value);\
+       }while(0)
+
+#define SET_UINT32(buf, value)do{\
+       (buf)[0] = (unsigned char)((value) >> 24);\
+       (buf)[1] = (unsigned char)((value) >> 16);\
+       (buf)[2] = (unsigned char)((value) >> 8);\
+       (buf)[3] = (unsigned char)(value);\
+       }while(0)
+
+       /* Construct decoder info buffer */
+       SET_UINT32(&decoder_info[24], config->frameLength);
+       decoder_info[28] = config->compatibleVersion;
+       decoder_info[29] = config->bitDepth;
+       decoder_info[30] = config->pb;
+       decoder_info[31] = config->mb;
+       decoder_info[32] = config->kb;
+       decoder_info[33] = config->numChannels;
+       SET_UINT16(&decoder_info[34], config->maxRun);
+       SET_UINT32(&decoder_info[36], config->maxFrameBytes);
+       SET_UINT32(&decoder_info[40], config->avgBitRate);
+       SET_UINT32(&decoder_info[44], config->sampleRate);
+       alac_set_info(alac, (char *) decoder_info);
+}
+
+raop_buffer_t *
+raop_buffer_init(const char *fmtp,
+                 const unsigned char *aeskey,
+                 const unsigned char *aesiv)
+{
+       raop_buffer_t *raop_buffer;
+       int audio_buffer_size;
+       ALACSpecificConfig *alacConfig;
+       int i;
+
+       assert(fmtp);
+       assert(aeskey);
+       assert(aesiv);
+
+       raop_buffer = calloc(1, sizeof(raop_buffer_t));
+       if (!raop_buffer) {
+               return NULL;
+       }
+
+       /* Parse fmtp information */
+       alacConfig = &raop_buffer->alacConfig;
+       if (get_fmtp_info(alacConfig, fmtp) < 0) {
+               free(raop_buffer);
+               return NULL;
+       }
+
+       /* Allocate the output audio buffers */
+       audio_buffer_size = alacConfig->frameLength *
+                           alacConfig->numChannels *
+                           alacConfig->bitDepth/8;
+       raop_buffer->buffer_size = audio_buffer_size *
+                                  RAOP_BUFFER_LENGTH;
+       raop_buffer->buffer = malloc(raop_buffer->buffer_size);
+       if (!raop_buffer->buffer) {
+               free(raop_buffer);
+               return NULL;
+       }
+       for (i=0; i<RAOP_BUFFER_LENGTH; i++) {
+               raop_buffer_entry_t *entry = &raop_buffer->entries[i];
+               entry->audio_buffer_size = audio_buffer_size;
+               entry->audio_buffer_len = 0;
+               entry->audio_buffer = raop_buffer->buffer+i*audio_buffer_size;
+       }
+
+       /* Initialize ALAC decoder */
+       raop_buffer->alac = create_alac(alacConfig->bitDepth,
+                                       alacConfig->numChannels);
+       if (!raop_buffer->alac) {
+               free(raop_buffer->buffer);
+               free(raop_buffer);
+               return NULL;
+       }
+       set_decoder_info(raop_buffer->alac, alacConfig);
+
+       /* Initialize AES keys */
+       memcpy(raop_buffer->aeskey, aeskey, RAOP_AESKEY_LEN);
+       memcpy(raop_buffer->aesiv, aesiv, RAOP_AESIV_LEN);
+
+       /* Mark buffer as empty */
+       raop_buffer->is_empty = 1;
+       return raop_buffer;
+}
+
+void
+raop_buffer_destroy(raop_buffer_t *raop_buffer)
+{
+       if (raop_buffer) {
+               free(raop_buffer->buffer);
+               free(raop_buffer->alac);
+               free(raop_buffer);
+       }
+}
+
+const ALACSpecificConfig *
+raop_buffer_get_config(raop_buffer_t *raop_buffer)
+{
+       assert(raop_buffer);
+
+       return &raop_buffer->alacConfig;
+}
+
+static short
+seqnum_cmp(unsigned short s1, unsigned short s2)
+{
+       return (s1 - s2);
+}
+
+int
+raop_buffer_queue(raop_buffer_t *raop_buffer, unsigned char *data, unsigned short datalen, int use_seqnum)
+{
+       unsigned char packetbuf[RAOP_PACKET_LEN];
+       unsigned short seqnum;
+       raop_buffer_entry_t *entry;
+       int encryptedlen;
+       AES_CTX aes_ctx;
+       int outputlen;
+
+       assert(raop_buffer);
+
+       /* Check packet data length is valid */
+       if (datalen < 12 || datalen > RAOP_PACKET_LEN) {
+               return -1;
+       }
+
+       /* Get correct seqnum for the packet */
+       if (use_seqnum) {
+               seqnum = (data[2] << 8) | data[3];
+       } else {
+               seqnum = raop_buffer->first_seqnum;
+       }
+
+       /* If this packet is too late, just skip it */
+       if (!raop_buffer->is_empty && seqnum_cmp(seqnum, raop_buffer->first_seqnum) < 0) {
+               return 0;
+       }
+
+       /* Check that there is always space in the buffer, otherwise flush */
+       if (seqnum_cmp(seqnum, raop_buffer->first_seqnum+RAOP_BUFFER_LENGTH) >= 0) {
+               raop_buffer_flush(raop_buffer, seqnum);
+       }
+
+       /* Get entry corresponding our seqnum */
+       entry = &raop_buffer->entries[seqnum % RAOP_BUFFER_LENGTH];
+       if (entry->available && seqnum_cmp(entry->seqnum, seqnum) == 0) {
+               /* Packet resend, we can safely ignore */
+               return 0;
+       }
+
+       /* Update the raop_buffer entry header */
+       entry->flags = data[0];
+       entry->type = data[1];
+       entry->seqnum = seqnum;
+       entry->timestamp = (data[4] << 24) | (data[5] << 16) |
+                          (data[6] << 8) | data[7];
+       entry->ssrc = (data[8] << 24) | (data[9] << 16) |
+                     (data[10] << 8) | data[11];
+       entry->available = 1;
+
+       /* Decrypt audio data */
+       encryptedlen = (datalen-12)/16*16;
+       AES_set_key(&aes_ctx, raop_buffer->aeskey, raop_buffer->aesiv, AES_MODE_128);
+       AES_convert_key(&aes_ctx);
+       AES_cbc_decrypt(&aes_ctx, &data[12], packetbuf, encryptedlen);
+       memcpy(packetbuf+encryptedlen, &data[12+encryptedlen], datalen-12-encryptedlen);
+
+       /* Decode ALAC audio data */
+       outputlen = entry->audio_buffer_size;
+       decode_frame(raop_buffer->alac, packetbuf, entry->audio_buffer, &outputlen);
+       entry->audio_buffer_len = outputlen;
+
+       /* Update the raop_buffer seqnums */
+       if (raop_buffer->is_empty) {
+               raop_buffer->first_seqnum = seqnum;
+               raop_buffer->last_seqnum = seqnum;
+               raop_buffer->is_empty = 0;
+       }
+       if (seqnum_cmp(seqnum, raop_buffer->last_seqnum) > 0) {
+               raop_buffer->last_seqnum = seqnum;
+       }
+       return 1;
+}
+
+const void *
+raop_buffer_dequeue(raop_buffer_t *raop_buffer, int *length, int no_resend)
+{
+       short buflen;
+       raop_buffer_entry_t *entry;
+
+       /* Calculate number of entries in the current buffer */
+       buflen = seqnum_cmp(raop_buffer->last_seqnum, raop_buffer->first_seqnum)+1;
+
+       /* Cannot dequeue from empty buffer */
+       if (raop_buffer->is_empty || buflen <= 0) {
+               return NULL;
+       }
+
+       /* Get the first buffer entry for inspection */
+       entry = &raop_buffer->entries[raop_buffer->first_seqnum % RAOP_BUFFER_LENGTH];
+       if (no_resend) {
+               /* If we do no resends, always return the first entry */
+       } else if (!entry->available) {
+               /* Check how much we have space left in the buffer */
+               if (buflen < RAOP_BUFFER_LENGTH) {
+                       /* Return nothing and hope resend gets on time */
+                       return NULL;
+               }
+               /* Risk of buffer overrun, return empty buffer */
+       }
+
+       /* Update buffer and validate entry */
+       raop_buffer->first_seqnum += 1;
+       if (!entry->available) {
+               /* Return an empty audio buffer to skip audio */
+               *length = entry->audio_buffer_size;
+               memset(entry->audio_buffer, 0, *length);
+               return entry->audio_buffer;
+       }
+       entry->available = 0;
+
+       /* Return entry audio buffer */
+       *length = entry->audio_buffer_len;
+       entry->audio_buffer_len = 0;
+       return entry->audio_buffer;
+}
+
+void
+raop_buffer_handle_resends(raop_buffer_t *raop_buffer, raop_resend_cb_t resend_cb, void *opaque)
+{
+       raop_buffer_entry_t *entry;
+
+       assert(raop_buffer);
+       assert(resend_cb);
+
+       if (seqnum_cmp(raop_buffer->first_seqnum, raop_buffer->last_seqnum) < 0) {
+               int seqnum, count;
+
+               for (seqnum=raop_buffer->first_seqnum; seqnum_cmp(seqnum, raop_buffer->last_seqnum)<0; seqnum++) {
+                       entry = &raop_buffer->entries[seqnum % RAOP_BUFFER_LENGTH];
+                       if (entry->available) {
+                               break;
+                       }
+               }
+               if (seqnum_cmp(seqnum, raop_buffer->first_seqnum) == 0) {
+                       return;
+               }
+               count = seqnum_cmp(seqnum, raop_buffer->first_seqnum);
+               resend_cb(opaque, raop_buffer->first_seqnum, count);
+       }
+}
+
+void
+raop_buffer_flush(raop_buffer_t *raop_buffer, int next_seq)
+{
+       int i;
+
+       assert(raop_buffer);
+
+       for (i=0; i<RAOP_BUFFER_LENGTH; i++) {
+               raop_buffer->entries[i].available = 0;
+               raop_buffer->entries[i].audio_buffer_len = 0;
+       }
+       if (next_seq < 0 || next_seq > 0xffff) {
+               raop_buffer->is_empty = 1;
+       } else {
+               raop_buffer->first_seqnum = next_seq;
+               raop_buffer->last_seqnum = next_seq-1;
+       }
+}
diff --git a/src/raop_buffer.h b/src/raop_buffer.h
new file mode 100644 (file)
index 0000000..619d8b2
--- /dev/null
@@ -0,0 +1,35 @@
+#ifndef RAOP_BUFFER_H
+#define RAOP_BUFFER_H
+
+typedef struct raop_buffer_s raop_buffer_t;
+
+/* From ALACMagicCookieDescription.txt at http://http://alac.macosforge.org/ */
+typedef struct {
+       unsigned int frameLength;
+       unsigned char compatibleVersion;
+       unsigned char bitDepth;
+       unsigned char pb;
+       unsigned char mb;
+       unsigned char kb;
+       unsigned char numChannels;
+       unsigned short maxRun;
+       unsigned int maxFrameBytes;
+       unsigned int avgBitRate;
+       unsigned int sampleRate;
+} ALACSpecificConfig;
+
+typedef int (*raop_resend_cb_t)(void *opaque, unsigned short seqno, unsigned short count);
+
+raop_buffer_t *raop_buffer_init(const char *fmtp,
+                                const unsigned char *aeskey,
+                                const unsigned char *aesiv);
+
+const ALACSpecificConfig *raop_buffer_get_config(raop_buffer_t *raop_buffer);
+int raop_buffer_queue(raop_buffer_t *raop_buffer, unsigned char *data, unsigned short datalen, int use_seqnum);
+const void *raop_buffer_dequeue(raop_buffer_t *raop_buffer, int *length, int no_resend);
+void raop_buffer_handle_resends(raop_buffer_t *raop_buffer, raop_resend_cb_t resend_cb, void *opaque);
+void raop_buffer_flush(raop_buffer_t *raop_buffer, int next_seq);
+
+void raop_buffer_destroy(raop_buffer_t *raop_buffer);
+
+#endif
diff --git a/src/raop_rtp.c b/src/raop_rtp.c
new file mode 100644 (file)
index 0000000..075770c
--- /dev/null
@@ -0,0 +1,521 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+#include <errno.h>
+
+#include "raop_rtp.h"
+#include "raop.h"
+#include "raop_buffer.h"
+#include "netutils.h"
+#include "compat.h"
+#include "logger.h"
+
+#define NO_FLUSH (-42)
+
+struct raop_rtp_s {
+       logger_t *logger;
+       raop_callbacks_t callbacks;
+
+       raop_buffer_t *buffer;
+
+       /* These variables only edited mutex locked */
+       int running;
+       int joined;
+       float volume;
+       int flush;
+       thread_handle_t thread;
+       mutex_handle_t run_mutex;
+
+       /* Remote control and timing ports */
+       unsigned short control_rport;
+       unsigned short timing_rport;
+
+       /* Sockets for control, timing and data */
+       int csock, tsock, dsock;
+
+       /* Local control, timing and data ports */
+       unsigned short control_lport;
+       unsigned short timing_lport;
+       unsigned short data_lport;
+
+       struct sockaddr_storage control_saddr;
+       socklen_t control_saddr_len;
+       unsigned short control_seqnum;
+};
+
+raop_rtp_t *
+raop_rtp_init(logger_t *logger, raop_callbacks_t *callbacks, const char *fmtp,
+              const unsigned char *aeskey, const unsigned char *aesiv)
+{
+       raop_rtp_t *raop_rtp;
+
+       assert(logger);
+
+       raop_rtp = calloc(1, sizeof(raop_rtp_t));
+       if (!raop_rtp) {
+               return NULL;
+       }
+       raop_rtp->logger = logger;
+       memcpy(&raop_rtp->callbacks, callbacks, sizeof(raop_callbacks_t));
+       raop_rtp->buffer = raop_buffer_init(fmtp, aeskey, aesiv);
+       if (!raop_rtp->buffer) {
+               free(raop_rtp);
+               return NULL;
+       }
+
+       raop_rtp->running = 0;
+       raop_rtp->joined = 1;
+       raop_rtp->flush = NO_FLUSH;
+       MUTEX_CREATE(raop_rtp->run_mutex);
+
+       return raop_rtp;
+}
+
+void
+raop_rtp_destroy(raop_rtp_t *raop_rtp)
+{
+       if (raop_rtp) {
+               raop_rtp_stop(raop_rtp);
+
+               MUTEX_DESTROY(raop_rtp->run_mutex);
+               raop_buffer_destroy(raop_rtp->buffer);
+               free(raop_rtp);
+       }
+}
+
+static int
+raop_rtp_init_sockets(raop_rtp_t *raop_rtp, int use_ipv6, int use_udp)
+{
+       int csock = -1, tsock = -1, dsock = -1;
+       unsigned short cport = 0, tport = 0, dport = 0;
+
+       assert(raop_rtp);
+
+       if (use_udp) {
+               csock = netutils_init_socket(&cport, use_ipv6, use_udp);
+               tsock = netutils_init_socket(&tport, use_ipv6, use_udp);
+               if (csock == -1 || tsock == -1) {
+                       goto sockets_cleanup;
+               }
+       }
+       dsock = netutils_init_socket(&dport, use_ipv6, use_udp);
+       if (dsock == -1) {
+               goto sockets_cleanup;
+       }
+
+       /* Listen to the data socket if using TCP */
+       if (!use_udp) {
+               if (listen(dsock, 1) < 0)
+                       goto sockets_cleanup;
+       }
+
+       /* Set socket descriptors */
+       raop_rtp->csock = csock;
+       raop_rtp->tsock = tsock;
+       raop_rtp->dsock = dsock;
+
+       /* Set port values */
+       raop_rtp->control_lport = cport;
+       raop_rtp->timing_lport = tport;
+       raop_rtp->data_lport = dport;
+       return 0;
+
+sockets_cleanup:
+       if (csock != -1) closesocket(csock);
+       if (tsock != -1) closesocket(tsock);
+       if (dsock != -1) closesocket(dsock);
+       return -1;
+}
+
+static int
+raop_rtp_resend_callback(void *opaque, unsigned short seqnum, unsigned short count)
+{
+       raop_rtp_t *raop_rtp = opaque;
+       unsigned char packet[8];
+       unsigned short ourseqnum;
+       struct sockaddr *addr;
+       socklen_t addrlen;
+
+       addr = (struct sockaddr *)&raop_rtp->control_saddr;
+       addrlen = raop_rtp->control_saddr_len;
+
+       logger_log(raop_rtp->logger, LOGGER_INFO, "Got resend request %d %d\n", seqnum, count);
+       ourseqnum = raop_rtp->control_seqnum++;
+
+       /* Fill the request buffer */
+       packet[0] = 0x80;
+       packet[1] = 0x55|0x80;
+       packet[2] = (ourseqnum >> 8);
+       packet[3] =  ourseqnum;
+       packet[4] = (seqnum >> 8);
+       packet[5] =  seqnum;
+       packet[6] = (count >> 8);
+       packet[7] =  count;
+
+       sendto(raop_rtp->csock, (const char *)packet, sizeof(packet), 0, addr, addrlen);
+       return 0;
+}
+
+static THREAD_RETVAL
+raop_rtp_thread_udp(void *arg)
+{
+       raop_rtp_t *raop_rtp = arg;
+       unsigned char packet[RAOP_PACKET_LEN];
+       unsigned int packetlen;
+       struct sockaddr_storage saddr;
+       socklen_t saddrlen;
+
+       const ALACSpecificConfig *config;
+       void *cb_data = NULL;
+
+       assert(raop_rtp);
+
+       config = raop_buffer_get_config(raop_rtp->buffer);
+       raop_rtp->callbacks.audio_init(raop_rtp->callbacks.cls, &cb_data,
+                                      config->bitDepth,
+                                      config->numChannels,
+                                      config->sampleRate);
+
+       while(1) {
+               int volume_changed;
+               float volume;
+               int flush;
+
+               fd_set rfds;
+               struct timeval tv;
+               int nfds, ret;
+
+               MUTEX_LOCK(raop_rtp->run_mutex);
+               if (!raop_rtp->running) {
+                       MUTEX_UNLOCK(raop_rtp->run_mutex);
+                       break;
+               }
+               /* Read the volume level */
+               volume_changed = (volume != raop_rtp->volume);
+               volume = raop_rtp->volume;
+
+               /* Read the flush value */
+               flush = raop_rtp->flush;
+               raop_rtp->flush = NO_FLUSH;
+               MUTEX_UNLOCK(raop_rtp->run_mutex);
+
+               /* Call set_volume callback if changed */
+               if (volume_changed) {
+                       raop_rtp->callbacks.audio_set_volume(raop_rtp->callbacks.cls, cb_data, volume);
+               }
+               if (flush != NO_FLUSH) {
+                       raop_buffer_flush(raop_rtp->buffer, flush);
+                       raop_rtp->callbacks.audio_flush(raop_rtp->callbacks.cls, cb_data);
+               }
+
+               /* Set timeout value to 5ms */
+               tv.tv_sec = 0;
+               tv.tv_usec = 5000;
+
+               /* Get the correct nfds value */
+               nfds = raop_rtp->csock+1;
+               if (raop_rtp->tsock >= nfds)
+                       nfds = raop_rtp->tsock+1;
+               if (raop_rtp->dsock >= nfds)
+                       nfds = raop_rtp->dsock+1;
+
+               /* Set rfds and call select */
+               FD_ZERO(&rfds);
+               FD_SET(raop_rtp->csock, &rfds);
+               FD_SET(raop_rtp->tsock, &rfds);
+               FD_SET(raop_rtp->dsock, &rfds);
+               ret = select(nfds, &rfds, NULL, NULL, &tv);
+               if (ret == 0) {
+                       /* Timeout happened */
+                       continue;
+               } else if (ret == -1) {
+                       /* FIXME: Error happened */
+                       break;
+               }
+
+               if (FD_ISSET(raop_rtp->csock, &rfds)) {
+                       saddrlen = sizeof(saddr);
+                       packetlen = recvfrom(raop_rtp->csock, (char *)packet, sizeof(packet), 0,
+                                            (struct sockaddr *)&saddr, &saddrlen);
+
+                       /* FIXME: Get destination address here */
+                       memcpy(&raop_rtp->control_saddr, &saddr, saddrlen);
+                       raop_rtp->control_saddr_len = saddrlen;
+
+                       if (packetlen >= 12) {
+                               char type = packet[1] & ~0x80;
+
+                               logger_log(raop_rtp->logger, LOGGER_INFO, "Got control packet of type 0x%02x\n", type);
+                               if (type == 0x56) {
+                                       /* Handle resent data packet */
+                                       int ret = raop_buffer_queue(raop_rtp->buffer, packet+4, packetlen-4, 1);
+                                       assert(ret >= 0);
+                               }
+                       }
+               } else if (FD_ISSET(raop_rtp->tsock, &rfds)) {
+                       logger_log(raop_rtp->logger, LOGGER_INFO, "Would have timing packet in queue\n");
+               } else if (FD_ISSET(raop_rtp->dsock, &rfds)) {
+                       saddrlen = sizeof(saddr);
+                       packetlen = recvfrom(raop_rtp->dsock, (char *)packet, sizeof(packet), 0,
+                                            (struct sockaddr *)&saddr, &saddrlen);
+                       if (packetlen >= 12) {
+                               int no_resend = (raop_rtp->control_rport == 0);
+                               int ret;
+
+                               const void *audiobuf;
+                               int audiobuflen;
+
+                               ret = raop_buffer_queue(raop_rtp->buffer, packet, packetlen, 1);
+                               assert(ret >= 0);
+
+                               /* Decode all frames in queue */
+                               while ((audiobuf = raop_buffer_dequeue(raop_rtp->buffer, &audiobuflen, no_resend))) {
+                                       raop_rtp->callbacks.audio_process(raop_rtp->callbacks.cls, cb_data, audiobuf, audiobuflen);
+                               }
+
+                               /* Handle possible resend requests */
+                               if (!no_resend) {
+                                       raop_buffer_handle_resends(raop_rtp->buffer, raop_rtp_resend_callback, raop_rtp);
+                               }
+                       }
+               }
+       }
+       logger_log(raop_rtp->logger, LOGGER_INFO, "Exiting thread\n");
+       raop_rtp->callbacks.audio_destroy(raop_rtp->callbacks.cls, cb_data);
+
+       return 0;
+}
+
+static THREAD_RETVAL
+raop_rtp_thread_tcp(void *arg)
+{
+       raop_rtp_t *raop_rtp = arg;
+       int stream_fd = -1;
+       unsigned char packet[RAOP_PACKET_LEN];
+       unsigned int packetlen = 0;
+
+       const ALACSpecificConfig *config;
+       void *cb_data = NULL;
+
+       assert(raop_rtp);
+
+       config = raop_buffer_get_config(raop_rtp->buffer);
+       raop_rtp->callbacks.audio_init(raop_rtp->callbacks.cls, &cb_data,
+                                      config->bitDepth,
+                                      config->numChannels,
+                                      config->sampleRate);
+
+       while (1) {
+               int volume_changed;
+               float volume;
+
+               fd_set rfds;
+               struct timeval tv;
+               int nfds, ret;
+
+               MUTEX_LOCK(raop_rtp->run_mutex);
+               if (!raop_rtp->running) {
+                       MUTEX_UNLOCK(raop_rtp->run_mutex);
+                       break;
+               }
+               volume_changed = (volume != raop_rtp->volume);
+               volume = raop_rtp->volume;
+               MUTEX_UNLOCK(raop_rtp->run_mutex);
+
+               /* Call set_volume callback if changed */
+               if (volume_changed) {
+                       raop_rtp->callbacks.audio_set_volume(raop_rtp->callbacks.cls, cb_data, volume);
+               }
+
+               /* Set timeout value to 5ms */
+               tv.tv_sec = 0;
+               tv.tv_usec = 5000;
+
+               /* Get the correct nfds value and set rfds */
+               FD_ZERO(&rfds);
+               if (stream_fd == -1) {
+                       FD_SET(raop_rtp->dsock, &rfds);
+                       nfds = raop_rtp->dsock+1;
+               } else {
+                       FD_SET(stream_fd, &rfds);
+                       nfds = stream_fd+1;
+               }
+               ret = select(nfds, &rfds, NULL, NULL, &tv);
+               if (ret == 0) {
+                       /* Timeout happened */
+                       continue;
+               } else if (ret == -1) {
+                       /* FIXME: Error happened */
+                       logger_log(raop_rtp->logger, LOGGER_INFO, "Error in select\n");
+                       break;
+               }
+               if (stream_fd == -1 && FD_ISSET(raop_rtp->dsock, &rfds)) {
+                       struct sockaddr_storage saddr;
+                       socklen_t saddrlen;
+
+                       logger_log(raop_rtp->logger, LOGGER_INFO, "Accepting client\n");
+                       saddrlen = sizeof(saddr);
+                       stream_fd = accept(raop_rtp->dsock, (struct sockaddr *)&saddr, &saddrlen);
+                       if (stream_fd == -1) {
+                               /* FIXME: Error happened */
+                               logger_log(raop_rtp->logger, LOGGER_INFO, "Error in accept %d %s\n", errno, strerror(errno));
+                               break;
+                       }
+               }
+               if (stream_fd != -1 && FD_ISSET(stream_fd, &rfds)) {
+                       unsigned int rtplen=0;
+                       char type;
+
+                       const void *audiobuf;
+                       int audiobuflen;
+
+                       ret = recv(stream_fd, (char *)(packet+packetlen), sizeof(packet)-packetlen, 0);
+                       if (ret == 0) {
+                               /* TCP socket closed */
+                               logger_log(raop_rtp->logger, LOGGER_INFO, "TCP socket closed\n");
+                               break;
+                       } else if (ret == -1) {
+                               /* FIXME: Error happened */
+                               logger_log(raop_rtp->logger, LOGGER_INFO, "Error in recv\n");
+                               break;
+                       }
+                       packetlen += ret;
+
+                       /* Check that we have enough bytes */
+                       if (packetlen < 4) {
+                               continue;
+                       }
+                       if (packet[0] != '$' || packet[1] != '\0') {
+                               /* FIXME: Incorrect RTP magic bytes */
+                               break;
+                       }
+                       rtplen = (packet[2] << 8) | packet[3];
+                       if (rtplen > sizeof(packet)) {
+                               /* FIXME: Too long packet */
+                               logger_log(raop_rtp->logger, LOGGER_INFO, "Error, packet too long %d\n", rtplen);
+                               break;
+                       }
+                       if (packetlen < 4+rtplen) {
+                               continue;
+                       }
+
+                       /* Packet is valid, process it */
+                       type = packet[4+1] & ~0x80;
+                       ret = raop_buffer_queue(raop_rtp->buffer, packet+4, rtplen, 0);
+                       assert(ret >= 0);
+
+                       /* Remove processed bytes from packet buffer */
+                       memmove(packet, packet+4+rtplen, packetlen-rtplen);
+                       packetlen -= 4+rtplen;
+
+                       /* Decode the received frame */
+                       if ((audiobuf = raop_buffer_dequeue(raop_rtp->buffer, &audiobuflen, 1))) {
+                               raop_rtp->callbacks.audio_process(raop_rtp->callbacks.cls, cb_data, audiobuf, audiobuflen);
+                       }
+               }
+       }
+
+       /* Close the stream file descriptor */
+       if (stream_fd != -1) {
+               closesocket(stream_fd);
+       }
+
+       logger_log(raop_rtp->logger, LOGGER_INFO, "Exiting thread\n");
+       raop_rtp->callbacks.audio_destroy(raop_rtp->callbacks.cls, cb_data);
+
+       return 0;
+}
+
+void
+raop_rtp_start(raop_rtp_t *raop_rtp, int use_udp, unsigned short control_rport, unsigned short timing_rport,
+               unsigned short *control_lport, unsigned short *timing_lport, unsigned short *data_lport)
+{
+       assert(raop_rtp);
+
+       MUTEX_LOCK(raop_rtp->run_mutex);
+       if (raop_rtp->running || !raop_rtp->joined) {
+               MUTEX_UNLOCK(raop_rtp->run_mutex);
+               return;
+       }
+
+       /* Initialize ports and sockets */
+       raop_rtp->control_rport = control_rport;
+       raop_rtp->timing_rport = timing_rport;
+       if (raop_rtp_init_sockets(raop_rtp, 1, use_udp) < 0) {
+               logger_log(raop_rtp->logger, LOGGER_INFO, "Initializing sockets failed\n");
+               MUTEX_UNLOCK(raop_rtp->run_mutex);
+               return;
+       }
+       if (control_lport) *control_lport = raop_rtp->control_lport;
+       if (timing_lport) *timing_lport = raop_rtp->timing_lport;
+       if (data_lport) *data_lport = raop_rtp->data_lport;
+       
+       /* Create the thread and initialize running values */
+       raop_rtp->running = 1;
+       raop_rtp->joined = 0;
+       if (use_udp) {
+               THREAD_CREATE(raop_rtp->thread, raop_rtp_thread_udp, raop_rtp);
+       } else {
+               THREAD_CREATE(raop_rtp->thread, raop_rtp_thread_tcp, raop_rtp);
+       }
+       MUTEX_UNLOCK(raop_rtp->run_mutex);
+}
+
+void
+raop_rtp_set_volume(raop_rtp_t *raop_rtp, float volume)
+{
+       assert(raop_rtp);
+
+       if (volume > 0.0f) {
+               volume = 0.0f;
+       } else if (volume < -144.0f) {
+               volume = -144.0f;
+       }
+
+       /* Set volume in thread instead */
+       MUTEX_LOCK(raop_rtp->run_mutex);
+       raop_rtp->volume = volume;
+       MUTEX_UNLOCK(raop_rtp->run_mutex);
+}
+
+void
+raop_rtp_flush(raop_rtp_t *raop_rtp, int next_seq)
+{
+       assert(raop_rtp);
+
+       /* Call flush in thread instead */
+       MUTEX_LOCK(raop_rtp->run_mutex);
+       raop_rtp->flush = next_seq;
+       MUTEX_UNLOCK(raop_rtp->run_mutex);
+}
+
+void
+raop_rtp_stop(raop_rtp_t *raop_rtp)
+{
+       assert(raop_rtp);
+
+       /* Check that we are running and thread is not
+        * joined (should never be while still running) */
+       MUTEX_LOCK(raop_rtp->run_mutex);
+       if (!raop_rtp->running || raop_rtp->joined) {
+               MUTEX_UNLOCK(raop_rtp->run_mutex);
+               return;
+       }
+       raop_rtp->running = 0;
+       MUTEX_UNLOCK(raop_rtp->run_mutex);
+
+       /* Join the thread */
+       THREAD_JOIN(raop_rtp->thread);
+       if (raop_rtp->csock != -1) closesocket(raop_rtp->csock);
+       if (raop_rtp->tsock != -1) closesocket(raop_rtp->tsock);
+       if (raop_rtp->dsock != -1) closesocket(raop_rtp->dsock);
+
+       /* Flush buffer into initial state */
+       raop_buffer_flush(raop_rtp->buffer, -1);
+
+       /* Mark thread as joined */
+       MUTEX_LOCK(raop_rtp->run_mutex);
+       raop_rtp->joined = 1;
+       MUTEX_UNLOCK(raop_rtp->run_mutex);
+}
diff --git a/src/raop_rtp.h b/src/raop_rtp.h
new file mode 100644 (file)
index 0000000..25755e4
--- /dev/null
@@ -0,0 +1,23 @@
+#ifndef RAOP_RTP_H
+#define RAOP_RTP_H
+
+/* For raop_callbacks_t */
+#include "raop.h"
+#include "logger.h"
+
+#define RAOP_AESKEY_LEN 16
+#define RAOP_AESIV_LEN  16
+#define RAOP_PACKET_LEN 32768
+
+typedef struct raop_rtp_s raop_rtp_t;
+
+raop_rtp_t *raop_rtp_init(logger_t *logger, raop_callbacks_t *callbacks, const char *fmtp,
+                          const unsigned char *aeskey, const unsigned char *aesiv);
+void raop_rtp_start(raop_rtp_t *raop_rtp, int use_udp, unsigned short control_rport, unsigned short timing_rport,
+                    unsigned short *control_lport, unsigned short *timing_lport, unsigned short *data_lport);
+void raop_rtp_set_volume(raop_rtp_t *raop_rtp, float volume);
+void raop_rtp_flush(raop_rtp_t *raop_rtp, int next_seq);
+void raop_rtp_stop(raop_rtp_t *raop_rtp);
+void raop_rtp_destroy(raop_rtp_t *raop_rtp);
+
+#endif
diff --git a/src/rsakey.c b/src/rsakey.c
new file mode 100644 (file)
index 0000000..485e21e
--- /dev/null
@@ -0,0 +1,371 @@
+#include <stdlib.h>
+#include <string.h>
+#include <stdint.h>
+#include <assert.h>
+
+#include "rsakey.h"
+#include "rsapem.h"
+#include "base64.h"
+#include "crypto/crypto.h"
+
+#define RSA_MIN_PADLEN 8
+#define MAX_KEYLEN 512
+
+struct rsakey_s {
+       int keylen;             /* length of modulus in bytes */
+       BI_CTX *bi_ctx;         /* bigint context */
+
+       bigint *n;              /* modulus */
+       bigint *e;              /* public exponent */
+       bigint *d;              /* private exponent */
+
+       int use_crt;            /* use chinese remainder theorem */
+       bigint *p;              /* p as in m = pq */
+       bigint *q;              /* q as in m = pq */
+       bigint *dP;             /* d mod (p-1) */
+       bigint *dQ;             /* d mod (q-1) */
+       bigint *qInv;           /* q^-1 mod p */
+
+       base64_t *base64;
+};
+
+rsakey_t *
+rsakey_init(const unsigned char *modulus, int mod_len,
+            const unsigned char *pub_exp, int pub_len,
+            const unsigned char *priv_exp, int priv_len,
+            /* Optional, used for crt optimization */
+            const unsigned char *p, int p_len,
+            const unsigned char *q, int q_len,
+            const unsigned char *dP, int dP_len,
+            const unsigned char *dQ, int dQ_len,
+            const unsigned char *qInv, int qInv_len)
+{
+       rsakey_t *rsakey;
+       int i;
+
+       if (mod_len > MAX_KEYLEN) {
+               return NULL;
+       }
+
+       rsakey = calloc(1, sizeof(rsakey_t));
+       if (!rsakey) {
+               return NULL;
+       }
+       rsakey->base64 = base64_init(NULL, 0, 0);
+       if (!rsakey->base64) {
+               free(rsakey);
+               return NULL;
+       }
+
+       /* Initialize structure */
+       for (i=0; !modulus[i] && i<mod_len; i++);
+       rsakey->keylen = mod_len-i;
+       rsakey->bi_ctx = bi_initialize();
+
+       /* Import public and private keys */
+       rsakey->n = bi_import(rsakey->bi_ctx, modulus, mod_len);
+       rsakey->e = bi_import(rsakey->bi_ctx, pub_exp, pub_len);
+       rsakey->d = bi_import(rsakey->bi_ctx, priv_exp, priv_len);
+
+       if (p && q && dP && dQ && qInv) {
+               /* Import crt optimization keys */
+               rsakey->p = bi_import(rsakey->bi_ctx, p, p_len);
+               rsakey->q = bi_import(rsakey->bi_ctx, q, q_len);
+               rsakey->dP = bi_import(rsakey->bi_ctx, dP, dP_len);
+               rsakey->dQ = bi_import(rsakey->bi_ctx, dQ, dQ_len);
+               rsakey->qInv = bi_import(rsakey->bi_ctx, qInv, qInv_len);
+       
+               /* Set imported keys either permanent or modulo */
+               bi_permanent(rsakey->dP);
+               bi_permanent(rsakey->dQ);
+               bi_permanent(rsakey->qInv);
+               bi_set_mod(rsakey->bi_ctx, rsakey->p, BIGINT_P_OFFSET);
+               bi_set_mod(rsakey->bi_ctx, rsakey->q, BIGINT_Q_OFFSET);
+
+               rsakey->use_crt = 1;
+       }
+
+       /* Add keys to the bigint context */
+       bi_set_mod(rsakey->bi_ctx, rsakey->n, BIGINT_M_OFFSET);
+       bi_permanent(rsakey->e);
+       bi_permanent(rsakey->d);
+       return rsakey;
+}
+
+rsakey_t *
+rsakey_init_pem(const char *pemstr)
+{
+       rsapem_t *rsapem;
+       unsigned char *modulus=NULL; unsigned int mod_len=0;
+       unsigned char *pub_exp=NULL; unsigned int pub_len=0;
+       unsigned char *priv_exp=NULL; unsigned int priv_len=0;
+       unsigned char *p=NULL; unsigned int p_len=0;
+       unsigned char *q=NULL; unsigned int q_len=0;
+       unsigned char *dP=NULL; unsigned int dP_len=0;
+       unsigned char *dQ=NULL; unsigned int dQ_len=0;
+       unsigned char *qInv=NULL; unsigned int qInv_len=0;
+       rsakey_t *rsakey=NULL;
+
+       rsapem = rsapem_init(pemstr);
+       if (!rsapem) {
+               return NULL;
+       }
+
+       /* Read public and private keys */
+       mod_len = rsapem_read_vector(rsapem, &modulus);
+       pub_len = rsapem_read_vector(rsapem, &pub_exp);
+       priv_len = rsapem_read_vector(rsapem, &priv_exp);
+       /* Read private keys for crt optimization */
+       p_len = rsapem_read_vector(rsapem, &p);
+       q_len = rsapem_read_vector(rsapem, &q);
+       dP_len = rsapem_read_vector(rsapem, &dP);
+       dQ_len = rsapem_read_vector(rsapem, &dQ);
+       qInv_len = rsapem_read_vector(rsapem, &qInv);
+       
+       if (modulus && pub_exp && priv_exp) {
+               /* Initialize rsakey value */
+               rsakey = rsakey_init(modulus, mod_len, pub_exp, pub_len, priv_exp, priv_len,
+                                    p, p_len, q, q_len, dP, dP_len, dQ, dQ_len, qInv, qInv_len);
+       }
+
+       free(modulus);
+       free(pub_exp);
+       free(priv_exp);
+       free(p);
+       free(q);
+       free(dP);
+       free(dQ);
+       free(qInv);
+       rsapem_destroy(rsapem);
+       return rsakey;
+}
+
+void
+rsakey_destroy(rsakey_t *rsakey)
+{
+       if (rsakey) {
+               bi_free_mod(rsakey->bi_ctx, BIGINT_M_OFFSET);
+               bi_depermanent(rsakey->e);
+               bi_depermanent(rsakey->d);
+               bi_free(rsakey->bi_ctx, rsakey->e);
+               bi_free(rsakey->bi_ctx, rsakey->d);
+
+               if (rsakey->use_crt) {
+                       bi_free_mod(rsakey->bi_ctx, BIGINT_P_OFFSET);
+                       bi_free_mod(rsakey->bi_ctx, BIGINT_Q_OFFSET);
+                       bi_depermanent(rsakey->dP);
+                       bi_depermanent(rsakey->dQ);
+                       bi_depermanent(rsakey->qInv);
+                       bi_free(rsakey->bi_ctx, rsakey->dP);
+                       bi_free(rsakey->bi_ctx, rsakey->dQ);
+                       bi_free(rsakey->bi_ctx, rsakey->qInv);
+               }
+               bi_terminate(rsakey->bi_ctx);
+
+               base64_destroy(rsakey->base64);
+               free(rsakey);
+       }
+}
+
+static bigint *
+rsakey_modpow(rsakey_t *rsakey, bigint *msg)
+{
+       if (rsakey->use_crt) {
+               return bi_crt(rsakey->bi_ctx, msg,
+                             rsakey->dP, rsakey->dQ,
+                             rsakey->p, rsakey->q, rsakey->qInv);
+       } else {
+               rsakey->bi_ctx->mod_offset = BIGINT_M_OFFSET;
+               return bi_mod_power(rsakey->bi_ctx, msg, rsakey->d);
+       }
+}
+
+int
+rsakey_sign(rsakey_t *rsakey, char *dst, int dstlen, const char *b64digest,
+            unsigned char *ipaddr, int ipaddrlen,
+            unsigned char *hwaddr, int hwaddrlen)
+{
+       unsigned char buffer[MAX_KEYLEN];
+       unsigned char *digest;
+       int digestlen;
+       int inputlen;
+       bigint *bi_in;
+       bigint *bi_out;
+       int idx;
+
+       assert(rsakey);
+
+       if (dstlen < base64_encoded_length(rsakey->base64, rsakey->keylen)) {
+               return -1;
+       }
+
+       /* Decode the base64 digest */
+       digestlen = base64_decode(rsakey->base64, &digest, b64digest, strlen(b64digest));
+       if (digestlen < 0) {
+               return -2;
+       }
+
+       /* Calculate the input data length */
+       inputlen = digestlen+ipaddrlen+hwaddrlen;
+       if (inputlen > rsakey->keylen-3-RSA_MIN_PADLEN) {
+               free(digest);
+               return -3;
+       }
+       if (inputlen < 32) {
+               /* Minimum size is 32 */
+               inputlen = 32;
+       }
+
+       /* Construct the input buffer with padding */
+       /* See RFC 3447 9.2 for more information */
+       idx = 0;
+       memset(buffer, 0, sizeof(buffer));
+       buffer[idx++] = 0x00;
+       buffer[idx++] = 0x01;
+       memset(buffer+idx, 0xff, rsakey->keylen-inputlen-3);
+       idx += rsakey->keylen-inputlen-3;
+       buffer[idx++] = 0x00;
+       memcpy(buffer+idx, digest, digestlen);
+       idx += digestlen;
+       memcpy(buffer+idx, ipaddr, ipaddrlen);
+       idx += ipaddrlen;
+       memcpy(buffer+idx, hwaddr, hwaddrlen);
+       idx += hwaddrlen;
+
+       /* Calculate the signature s = m^d (mod n) */
+       bi_in = bi_import(rsakey->bi_ctx, buffer, rsakey->keylen);
+       bi_out = rsakey_modpow(rsakey, bi_in);
+
+       /* Encode and save the signature into dst */
+       bi_export(rsakey->bi_ctx, bi_out, buffer, rsakey->keylen);
+       base64_encode(rsakey->base64, dst, buffer, rsakey->keylen);
+
+       free(digest);
+       return 0;
+}
+
+/* Mask generation function with SHA-1 hash */
+/* See RFC 3447 B.2.1 for more information */
+static int
+rsakey_mfg1(unsigned char *dst, int dstlen, const unsigned char *seed, int seedlen, int masklen)
+{
+       SHA1_CTX sha_ctx;
+       int iterations;
+       int dstpos;
+       int i;
+
+       iterations = (masklen+SHA1_SIZE-1)/SHA1_SIZE;
+       if (dstlen < iterations*SHA1_SIZE) {
+               return -1;
+       }
+
+       dstpos = 0;
+       for (i=0; i<iterations; i++) {
+               unsigned char counter[4];
+               counter[0] = (i>>24)&0xff;
+               counter[1] = (i>>16)&0xff;
+               counter[2] = (i>>8)&0xff;
+               counter[3] = i&0xff;
+
+               SHA1_Init(&sha_ctx);
+               SHA1_Update(&sha_ctx, seed, seedlen);
+               SHA1_Update(&sha_ctx, counter, sizeof(counter));
+               SHA1_Final(dst+dstpos, &sha_ctx);
+               dstpos += SHA1_SIZE;
+       }
+       return masklen;
+}
+
+/* OAEP decryption with SHA-1 hash */
+/* See RFC 3447 7.1.2 for more information */
+int
+rsakey_decrypt(rsakey_t *rsakey, unsigned char *dst, int dstlen, const char *b64input)
+{
+       unsigned char buffer[MAX_KEYLEN];
+       unsigned char maskbuf[MAX_KEYLEN];
+       unsigned char *input;
+       int inputlen;
+       bigint *bi_in;
+       bigint *bi_out;
+       int outlen;
+       int i, ret;
+
+       assert(rsakey);
+       if (!dst || !b64input) {
+               return -1;
+       }
+
+       memset(buffer, 0, sizeof(buffer));
+       inputlen = base64_decode(rsakey->base64, &input, b64input, strlen(b64input));
+       if (inputlen < 0 || inputlen > rsakey->keylen) {
+               return -2;
+       }
+       memcpy(buffer+rsakey->keylen-inputlen, input, inputlen);
+       free(input);
+       input = NULL;
+
+       /* Decrypt the input data m = c^d (mod n) */
+       bi_in = bi_import(rsakey->bi_ctx, buffer, rsakey->keylen);
+       bi_out = rsakey_modpow(rsakey, bi_in);
+
+       memset(buffer, 0, sizeof(buffer));
+       bi_export(rsakey->bi_ctx, bi_out, buffer, rsakey->keylen);
+
+       /* First unmask seed in the buffer */
+       ret = rsakey_mfg1(maskbuf, sizeof(maskbuf),
+                         buffer+1+SHA1_SIZE,
+                         rsakey->keylen-1-SHA1_SIZE,
+                         SHA1_SIZE);
+       if (ret < 0) {
+               return -3;
+       }
+       for (i=0; i<ret; i++) {
+               buffer[1+i] ^= maskbuf[i];
+       }
+
+       /* Then unmask the actual message */
+       ret = rsakey_mfg1(maskbuf, sizeof(maskbuf),
+                         buffer+1, SHA1_SIZE,
+                         rsakey->keylen-1-SHA1_SIZE);
+       if (ret < 0) {
+               return -4;
+       }
+       for (i=0; i<ret; i++) {
+               buffer[1+SHA1_SIZE+i] ^= maskbuf[i];
+       }
+
+       /* Finally find the first data byte */
+       for (i=1+2*SHA1_SIZE; i<rsakey->keylen && !buffer[i++];);
+
+       /* Calculate real output length and return */
+       outlen = rsakey->keylen-i;
+       if (outlen > dstlen) {
+               return -5;
+       }
+       memcpy(dst, buffer+i, outlen);
+       return outlen;
+}
+
+int
+rsakey_parseiv(rsakey_t *rsakey, unsigned char *dst, int dstlen, const char *b64input)
+{
+       unsigned char *tmpptr;
+       int length;
+
+       assert(rsakey);
+       if (!dst || !b64input) {
+               return -1;
+       }
+
+       length = base64_decode(rsakey->base64, &tmpptr, b64input, strlen(b64input));
+       if (length < 0) {
+               return -1;
+       } else if (length > dstlen) {
+               free(tmpptr);
+               return -2;
+       }
+
+       memcpy(dst, tmpptr, length);
+       free(tmpptr);
+       return length;
+}
diff --git a/src/rsakey.h b/src/rsakey.h
new file mode 100644 (file)
index 0000000..1bb69ef
--- /dev/null
@@ -0,0 +1,25 @@
+#ifndef RSAKEY_H
+#define RSAKEY_H
+
+typedef struct rsakey_s rsakey_t;
+
+rsakey_t *rsakey_init(const unsigned char *modulus, int mod_len,
+                      const unsigned char *pub_exp, int pub_len,
+                      const unsigned char *priv_exp, int priv_len,
+                      const unsigned char *p, int p_len,
+                      const unsigned char *q, int q_len,
+                      const unsigned char *dP, int dP_len,
+                      const unsigned char *dQ, int dQ_len,
+                      const unsigned char *qInv, int qInv_len);
+rsakey_t *rsakey_init_pem(const char *pemstr);
+
+int rsakey_sign(rsakey_t *rsakey, char *dst, int dstlen, const char *b64digest,
+                unsigned char *ipaddr, int ipaddrlen,
+                unsigned char *hwaddr, int hwaddrlen);
+
+int rsakey_decrypt(rsakey_t *rsakey, unsigned char *dst, int dstlen, const char *b64input);
+int rsakey_parseiv(rsakey_t *rsakey, unsigned char *dst, int dstlen, const char *b64input);
+
+void rsakey_destroy(rsakey_t *rsakey);
+
+#endif
diff --git a/src/rsapem.c b/src/rsapem.c
new file mode 100644 (file)
index 0000000..1090ffe
--- /dev/null
@@ -0,0 +1,148 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <ctype.h>
+
+#include "rsapem.h"
+#include "base64.h"
+
+#define RSAPRIVHEADER "-----BEGIN RSA PRIVATE KEY-----"
+#define RSAPRIVFOOTER "-----END RSA PRIVATE KEY-----"
+
+struct rsapem_s {
+       unsigned char *data;
+       unsigned int datalen;
+       unsigned int datapos;
+};
+
+rsapem_t *
+rsapem_init(const char *pemstr)
+{
+       rsapem_t *rsapem=NULL;
+       const char *header;
+       const char *footer;
+       base64_t *b64dec;
+       unsigned char *data;
+       int datalen;
+
+       header = strstr(pemstr, RSAPRIVHEADER);
+       footer = strstr(pemstr, RSAPRIVFOOTER);
+       if (!header || !footer) {
+               return NULL;
+       }
+
+
+       /* Base64 decode the whole input excluding header and footer */
+       b64dec = base64_init(NULL, 0, 1);
+       datalen = base64_decode(b64dec, &data, pemstr+sizeof(RSAPRIVHEADER),
+                               (footer-header)-sizeof(RSAPRIVHEADER));
+       base64_destroy(b64dec);
+       b64dec = NULL;
+       
+       if (datalen < 0) {
+               return NULL;
+       }
+
+#ifdef RSAPEM_DEBUG
+       {
+               int i;
+               printf("Decoded output:\n");
+               for (i=0; i<datalen; i++) {
+                       printf("%02x", data[i]);
+               }
+               printf("\n");
+       }
+#endif
+
+       /* Check that first 4 bytes are all valid */
+       if (datalen < 4 || data[0] != 0x30 || data[1] != 0x82) {
+               free(data);
+               return NULL;
+       } else if (((data[2] << 8) | data[3]) != datalen-4) {
+               free(data);
+               return NULL;
+       }
+       
+       rsapem = calloc(1, sizeof(rsapem_t));
+       if (!rsapem) {
+               free(data);
+               return NULL;
+       }
+
+       /* Initialize the data */
+       rsapem->data = data;
+       rsapem->datalen = datalen;
+       rsapem->datapos = 4;
+
+       data = NULL;
+       datalen = rsapem_read_vector(rsapem, &data);
+       if (datalen != 1 && data[0] != 0x00) {
+               free(data);
+               rsapem_destroy(rsapem);
+               return NULL;
+       }
+       free(data);
+       return rsapem;
+}
+
+void
+rsapem_destroy(rsapem_t *rsapem)
+{
+       if (rsapem) {
+               free(rsapem->data);
+               free(rsapem);
+       }
+}
+
+int
+rsapem_read_vector(rsapem_t *rsapem, unsigned char **data)
+{
+       unsigned int length;
+       unsigned char *ptr;
+
+       if (rsapem->datalen-rsapem->datapos < 2) {
+               return -1;
+       }
+       if (rsapem->data[rsapem->datapos] != 0x02) {
+               return -2;
+       }
+
+       /* Read vector length */
+       length = rsapem->data[rsapem->datapos+1];
+       if (length <= 0x80) {
+               rsapem->datapos += 2;
+       } else if (length == 0x81) {
+               if (rsapem->datalen-rsapem->datapos < 3) {
+                       return -3;
+               }
+               length = rsapem->data[rsapem->datapos+2];
+               rsapem->datapos += 3;
+       } else if (length == 0x82) {
+               if (rsapem->datalen-rsapem->datapos < 4) {
+                       return -3;
+               }
+               length = (rsapem->data[rsapem->datapos+2] << 8) |
+                         rsapem->data[rsapem->datapos+3];
+               rsapem->datapos += 4;
+       } else {
+               return -3;
+       }
+
+       /* Check that we have enough data available */
+       if (rsapem->datalen-rsapem->datapos < length) {
+               return -4;
+       }
+
+       /* Allocate data buffer and read bytes */
+       ptr = malloc(length);
+       if (!ptr) {
+               return -5;
+       }
+       memcpy(ptr, rsapem->data+rsapem->datapos, length);
+       rsapem->datapos += length;
+
+       /* Return buffer and length */
+       *data = ptr;
+       return length;
+}
+
diff --git a/src/rsapem.h b/src/rsapem.h
new file mode 100644 (file)
index 0000000..95ae5a8
--- /dev/null
@@ -0,0 +1,10 @@
+#ifndef RSAPEM_H
+#define RSAPEM_H
+
+typedef struct rsapem_s rsapem_t;
+
+rsapem_t *rsapem_init(const char *pemstr);
+int rsapem_read_vector(rsapem_t *rsapem, unsigned char **data);
+void rsapem_destroy(rsapem_t *rsapem);
+
+#endif
diff --git a/src/sdp.c b/src/sdp.c
new file mode 100644 (file)
index 0000000..369de1c
--- /dev/null
+++ b/src/sdp.c
@@ -0,0 +1,228 @@
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#include "sdp.h"
+
+struct sdp_s {
+       char *data;
+
+       /* Actual SDP records */
+       const char *version;
+       const char *origin;
+       const char *connection;
+       const char *session;
+       const char *time;
+       const char *media;
+
+       /* Additional SDP records */
+       const char *rtpmap;
+       const char *fmtp;
+       const char *rsaaeskey;
+       const char *aesiv;
+       const char *min_latency;
+};
+
+static void
+parse_sdp_line(sdp_t *sdp, char *line)
+{
+       int len = strlen(line);
+       if (len < 2 || line[1] != '=') {
+               return;
+       }
+
+       switch (line[0]) {
+       case 'v':
+               sdp->version = &line[2];
+               break;
+       case 'o':
+               sdp->origin = &line[2];
+               break;
+       case 's':
+               sdp->session = &line[2];
+               break;
+       case 'c':
+               sdp->connection = &line[2];
+               break;
+       case 't':
+               sdp->time = &line[2];
+               break;
+       case 'm':
+               sdp->media = &line[2];
+               break;
+       case 'a':
+               {
+                       char *key;
+                       char *value;
+
+                       /* Parse key and value */
+                       key = &line[2];
+                       value = strstr(line, ":");
+                       if (!value) break;
+                       *(value++) = '\0';
+
+                       if (!strcmp(key, "rtpmap")) {
+                               sdp->rtpmap = value;
+                       } else if (!strcmp(key, "fmtp")) {
+                               sdp->fmtp = value;
+                       } else if (!strcmp(key, "rsaaeskey")) {
+                               sdp->rsaaeskey = value;
+                       } else if (!strcmp(key, "aesiv")) {
+                               sdp->aesiv = value;
+                       } else if (!strcmp(key, "min-latency")) {
+                               sdp->min_latency = value;
+                       }
+                       break;
+               }
+       }
+}
+
+static void
+parse_sdp_data(sdp_t *sdp)
+{
+       int pos, len;
+
+       pos = 0;
+       len = strlen(sdp->data);
+       while (pos < len) {
+               int lfpos;
+
+               /* Find newline in string */
+               for (lfpos=pos; sdp->data[lfpos]; lfpos++) {
+                       if (sdp->data[lfpos] == '\n') {
+                               break;
+                       }
+               }
+               if (sdp->data[lfpos] != '\n') {
+                       break;
+               }
+
+               /* Replace newline with '\0' and parse line */
+               sdp->data[lfpos] = '\0';
+               if (lfpos > pos && sdp->data[lfpos-1] == '\r') {
+                       sdp->data[lfpos-1] = '\0';
+               }
+               parse_sdp_line(sdp, sdp->data+pos);
+               pos = lfpos+1;
+       }
+}
+
+sdp_t *
+sdp_init(const char *sdpdata, int sdpdatalen)
+{
+       sdp_t *sdp;
+
+       sdp = calloc(1, sizeof(sdp_t));
+       if (!sdp) {
+               return NULL;
+       }
+
+       /* Allocate data buffer */
+       sdp->data = malloc(sdpdatalen+1);
+       if (!sdp->data) {
+               free(sdp);
+               return NULL;
+       }
+       memcpy(sdp->data, sdpdata, sdpdatalen);
+       sdp->data[sdpdatalen] = '\0';
+       parse_sdp_data(sdp);
+       return sdp;
+}
+
+void
+sdp_destroy(sdp_t *sdp)
+{
+       if (sdp) {
+               free(sdp->data);
+               free(sdp);
+       }
+}
+
+const char *
+sdp_get_version(sdp_t *sdp)
+{
+       assert(sdp);
+
+       return sdp->version;
+}
+
+const char *
+sdp_get_origin(sdp_t *sdp)
+{
+       assert(sdp);
+
+       return sdp->origin;
+}
+
+const char *
+sdp_get_session(sdp_t *sdp)
+{
+       assert(sdp);
+
+       return sdp->session;
+}
+
+const char *
+sdp_get_connection(sdp_t *sdp)
+{
+       assert(sdp);
+
+       return sdp->connection;
+}
+
+const char *
+sdp_get_time(sdp_t *sdp)
+{
+       assert(sdp);
+
+       return sdp->time;
+}
+
+const char *
+sdp_get_media(sdp_t *sdp)
+{
+       assert(sdp);
+
+       return sdp->media;
+}
+
+const char *
+sdp_get_rtpmap(sdp_t *sdp)
+{
+       assert(sdp);
+
+       return sdp->rtpmap;
+}
+
+const char *
+sdp_get_fmtp(sdp_t *sdp)
+{
+       assert(sdp);
+
+       return sdp->fmtp;
+}
+
+const char *
+sdp_get_rsaaeskey(sdp_t *sdp)
+{
+       assert(sdp);
+
+       return sdp->rsaaeskey;
+}
+
+const char *
+sdp_get_aesiv(sdp_t *sdp)
+{
+       assert(sdp);
+
+       return sdp->aesiv;
+}
+
+const char *
+sdp_get_min_latency(sdp_t *sdp)
+{
+       assert(sdp);
+
+       return sdp->min_latency;
+}
+
diff --git a/src/sdp.h b/src/sdp.h
new file mode 100644 (file)
index 0000000..474fae0
--- /dev/null
+++ b/src/sdp.h
@@ -0,0 +1,22 @@
+#ifndef SDP_H
+#define SDP_H
+
+typedef struct sdp_s sdp_t;
+
+sdp_t *sdp_init(const char *sdpdata, int sdpdatalen);
+
+const char *sdp_get_version(sdp_t *sdp);
+const char *sdp_get_origin(sdp_t *sdp);
+const char *sdp_get_session(sdp_t *sdp);
+const char *sdp_get_connection(sdp_t *sdp);
+const char *sdp_get_time(sdp_t *sdp);
+const char *sdp_get_media(sdp_t *sdp);
+const char *sdp_get_rtpmap(sdp_t *sdp);
+const char *sdp_get_fmtp(sdp_t *sdp);
+const char *sdp_get_rsaaeskey(sdp_t *sdp);
+const char *sdp_get_aesiv(sdp_t *sdp);
+const char *sdp_get_min_latency(sdp_t *sdp);
+
+void sdp_destroy(sdp_t *sdp);
+
+#endif
diff --git a/src/sockets.h b/src/sockets.h
new file mode 100644 (file)
index 0000000..58ef250
--- /dev/null
@@ -0,0 +1,35 @@
+#ifndef SOCKETS_H
+#define SOCKETS_H
+
+#if defined(WIN32)
+typedef int socklen_t;
+
+#ifndef SHUT_RD
+#  define SHUT_RD SD_RECEIVE
+#endif
+#ifndef SHUT_WR
+#  define SHUT_WR SD_SEND
+#endif
+#ifndef SHUT_RDWR
+#  define SHUT_RDWR SD_BOTH
+#endif
+
+#define SOCKET_GET_ERROR()      WSAGetLastError()
+#define SOCKET_SET_ERROR(value) WSASetLastError(value)
+#define SOCKET_ERRORNAME(name)  WSA##name
+
+#define WSAEAGAIN WSAEWOULDBLOCK
+#define WSAENOMEM WSA_NOT_ENOUGH_MEMORY
+
+#else
+
+#define closesocket close
+#define ioctlsocket ioctl
+
+#define SOCKET_GET_ERROR()      (errno)
+#define SOCKET_SET_ERROR(value) (errno = (value))
+#define SOCKET_ERRORNAME(name)  name
+
+#endif
+
+#endif
diff --git a/src/threads.h b/src/threads.h
new file mode 100644 (file)
index 0000000..7f79e6d
--- /dev/null
@@ -0,0 +1,46 @@
+#ifndef THREADS_H
+#define THREADS_H
+
+#if defined(WIN32)
+#include <windows.h>
+
+#define sleepms(x) Sleep(x)
+
+typedef HANDLE thread_handle_t;
+
+#define THREAD_RETVAL DWORD WINAPI
+#define THREAD_CREATE(handle, func, arg) \
+       handle = CreateThread(NULL, 0, func, arg, 0, NULL)
+#define THREAD_JOIN(handle) do { WaitForSingleObject(handle, INFINITE); CloseHandle(handle); } while(0)
+
+typedef HANDLE mutex_handle_t;
+
+#define MUTEX_CREATE(handle) handle = CreateMutex(NULL, FALSE, NULL)
+#define MUTEX_LOCK(handle) WaitForSingleObject(handle, INFINITE)
+#define MUTEX_UNLOCK(handle) ReleaseMutex(handle)
+#define MUTEX_DESTROY(handle) CloseHandle(handle)
+
+#else /* Use pthread library */
+
+#include <pthread.h>
+#include <unistd.h>
+
+#define sleepms(x) usleep((x)*1000)
+
+typedef pthread_t thread_handle_t;
+
+#define THREAD_RETVAL void *
+#define THREAD_CREATE(handle, func, arg) \
+       if (pthread_create(&(handle), NULL, func, arg)) handle = 0
+#define THREAD_JOIN(handle) pthread_join(handle, NULL)
+
+typedef pthread_mutex_t mutex_handle_t;
+
+#define MUTEX_CREATE(handle) pthread_mutex_init(&(handle), NULL)
+#define MUTEX_LOCK(handle) pthread_mutex_lock(&(handle))
+#define MUTEX_UNLOCK(handle) pthread_mutex_unlock(&(handle))
+#define MUTEX_DESTROY(handle) pthread_mutex_destroy(&(handle))
+
+#endif
+
+#endif /* THREADS_H */
diff --git a/src/utils.c b/src/utils.c
new file mode 100644 (file)
index 0000000..8057eec
--- /dev/null
@@ -0,0 +1,130 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+char *
+utils_strsep(char **stringp, const char *delim)
+{
+       char *original;
+       char *strptr;
+
+       if (*stringp == NULL) {
+               return NULL;
+       }
+
+       original = *stringp;
+       strptr = strstr(*stringp, delim);
+       if (strptr == NULL) {
+               *stringp = NULL;
+               return original;
+       }
+       *strptr = '\0';
+       *stringp = strptr+strlen(delim);
+       return original;
+}
+
+int
+utils_read_file(char **dst, const char *filename)
+{
+       FILE *stream;
+       int filesize;
+       char *buffer;
+       int read_bytes;
+
+       /* Open stream for reading */
+       stream = fopen(filename, "rb");
+       if (!stream) {
+               return -1;
+       }
+
+       /* Find out file size */
+       fseek(stream, 0, SEEK_END);
+       filesize = ftell(stream);
+       fseek(stream, 0, SEEK_SET);
+
+       /* Allocate one extra byte for zero */
+       buffer = malloc(filesize+1);
+       if (!buffer) {
+               fclose(stream);
+               return -2;
+       }
+
+       /* Read data in a loop to buffer */
+       read_bytes = 0;
+       do {
+               int ret = fread(buffer+read_bytes, 1,
+                               filesize-read_bytes, stream);
+               if (ret == 0) {
+                       break;
+               }
+               read_bytes += ret;
+       } while (read_bytes < filesize);
+
+       /* Add final null byte and close stream */
+       buffer[read_bytes] = '\0';
+       fclose(stream);
+
+       /* If read didn't finish, return error */
+       if (read_bytes != filesize) {
+               free(buffer);
+               return -3;
+       }
+
+       /* Return buffer */
+       *dst = buffer;
+       return filesize;
+}
+
+int
+utils_hwaddr_raop(char *str, int strlen, const char *hwaddr, int hwaddrlen)
+{
+       int i,j;
+
+       /* Check that our string is long enough */
+       if (strlen == 0 || strlen < 2*hwaddrlen+1)
+               return -1;
+
+       /* Convert hardware address to hex string */
+       for (i=0,j=0; i<hwaddrlen; i++) {
+               int hi = (hwaddr[i]>>4) & 0x0f;
+               int lo = hwaddr[i] & 0x0f;
+
+               if (hi < 10) str[j++] = '0' + hi;
+               else         str[j++] = 'A' + hi-10;
+               if (lo < 10) str[j++] = '0' + lo;
+               else         str[j++] = 'A' + lo-10;
+       }
+
+       /* Add string terminator */
+       str[j++] = '\0';
+       return j;
+}
+
+int
+utils_hwaddr_airplay(char *str, int strlen, const char *hwaddr, int hwaddrlen)
+{
+       int i,j;
+
+       /* Check that our string is long enough */
+       if (strlen == 0 || strlen < 2*hwaddrlen+hwaddrlen)
+               return -1;
+
+       /* Convert hardware address to hex string */
+       for (i=0,j=0; i<hwaddrlen; i++) {
+               int hi = (hwaddr[i]>>4) & 0x0f;
+               int lo = hwaddr[i] & 0x0f;
+
+               if (hi < 10) str[j++] = '0' + hi;
+               else         str[j++] = 'a' + hi-10;
+               if (lo < 10) str[j++] = '0' + lo;
+               else         str[j++] = 'a' + lo-10;
+
+               str[j++] = ':';
+       }
+
+       /* Add string terminator */
+       if (j != 0) j--;
+       str[j++] = '\0';
+       return j;
+}
+
diff --git a/src/utils.h b/src/utils.h
new file mode 100644 (file)
index 0000000..f1b0b5a
--- /dev/null
@@ -0,0 +1,9 @@
+#ifndef UTILS_H
+#define UTILS_H
+
+char *utils_strsep(char **stringp, const char *delim);
+int utils_read_file(char **dst, const char *pemstr);
+int utils_hwaddr_raop(char *str, int strlen, const char *hwaddr, int hwaddrlen);
+int utils_hwaddr_airplay(char *str, int strlen, const char *hwaddr, int hwaddrlen);
+
+#endif
diff --git a/test/dnssd_test.c b/test/dnssd_test.c
new file mode 100644 (file)
index 0000000..7e329c4
--- /dev/null
@@ -0,0 +1,48 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <unistd.h>
+
+#include "dnssd.h"
+#include "compat.h"
+
+int
+main(int argc, char *argv[])
+{
+       const char hwaddr[] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB };
+       dnssd_t *dnssd;
+
+
+#ifdef WIN32
+       WORD wVersionRequested;
+       WSADATA wsaData;
+
+       wVersionRequested = MAKEWORD(2, 2);
+       if (WSAStartup(wVersionRequested, &wsaData) != 0) {
+               return -1;
+       }
+       if (LOBYTE(wsaData.wVersion) != 2 ||
+           HIBYTE(wsaData.wVersion) != 2) {
+               return -1;
+       }
+#endif
+
+       dnssd = dnssd_init(hwaddr, sizeof(hwaddr), NULL);
+       if (!dnssd) {
+               printf("Failed to init dnssd\n");
+               return -1;
+       }
+       dnssd_register_raop(dnssd, "Test", 5000);
+       dnssd_register_airplay(dnssd, "Test", 6000);
+
+       sleepms(60000);
+
+       dnssd_unregister_raop(dnssd);
+       dnssd_unregister_airplay(dnssd);
+       dnssd_destroy(dnssd);
+
+#ifdef WIN32
+       WSACleanup();
+#endif
+
+       return 0;
+}
diff --git a/test/dnssd_test.m b/test/dnssd_test.m
new file mode 100644 (file)
index 0000000..d4ccbe2
--- /dev/null
@@ -0,0 +1,32 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <Foundation/Foundation.h>
+
+#include "dnssd.h"
+#include "compat.h"
+
+int
+main(int argc, char *argv[])
+{
+       NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
+       const char hwaddr[] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB };
+       dnssd_t *dnssd;
+
+       dnssd = dnssd_init(hwaddr, sizeof(hwaddr), NULL);
+       if (!dnssd) {
+               printf("Failed to init dnssd\n");
+               return -1;
+       }
+       dnssd_register_raop(dnssd, "Test", 5000);
+       dnssd_register_airplay(dnssd, "Test", 6000);
+
+       sleepms(60000);
+
+       dnssd_unregister_raop(dnssd);
+       dnssd_unregister_airplay(dnssd);
+       dnssd_destroy(dnssd);
+       [pool release];
+
+       return 0;
+}
diff --git a/test/main.c b/test/main.c
new file mode 100644 (file)
index 0000000..e902dea
--- /dev/null
@@ -0,0 +1,213 @@
+#include <stdlib.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+
+#include <ao/ao.h>
+
+#include "dnssd.h"
+#include "airplay.h"
+#include "raop.h"
+#include "rsakey.h"
+#include "utils.h"
+
+#define CHALLENGE "LfBLs2pkGT4yYAJrxj2K9Q=="
+static unsigned char ipaddr[] = { 192, 168, 1, 10 };
+static unsigned char hwaddr[] = { 0x00, 0x5A, 0xDB, 0xE4, 0xE6, 0xFD };
+
+#define AESENC "B69yRGHoriZZeJNKghotJi6Pt7dEPEwKSoieM6dk8YE1D23/jyOsg0ZoJZmodHB4lR9Q9CmeoqgU0GX1KkYNafCrNUlXxJAZuMTISGmyeDegnH73ul1NQwIjfphGgwrx7dp7J+p4lyQi+Yt/daQyjE//Od0viD37GQtI9B7GukaiWrMl94wJmSLUL94VpKUxnD9E7T/LesX7bEMfUgSQUpIE+T2anp6eRqE/5R3kNYdEH9JcCEFu5DLqbbvMqgc0ewr81BNeVG5ck1iI2eF+OJVm9g082ZXqGAPFGwmcYiiLfjrQY5hnEUi7IeWqgX5Xd82DyW9BeDzT5MXVyI/GwQ=="
+
+static void
+test_rsa(const char *pemstr)
+{
+       char buffer[2048];
+       int ret;
+       rsakey_t *rsakey;
+
+       rsakey = rsakey_init_pem(pemstr);
+       if (!rsakey) {
+               printf("Initializing RSA failed\n");
+               return;
+       }
+
+       rsakey_sign(rsakey, buffer, sizeof(buffer), CHALLENGE,
+                   ipaddr, sizeof(ipaddr), hwaddr, sizeof(hwaddr));
+       printf("Signature:\n%s\n", buffer);
+
+       ret = rsakey_decrypt(rsakey, (unsigned char *)buffer, sizeof(buffer), AESENC);
+       printf("Decrypted length: %d\n", ret);
+
+       rsakey_destroy(rsakey);
+}
+
+static void
+photo_cb(char *data, int datalen)
+{
+       char template[512];
+       int written = 0;
+       int fd, ret;
+
+       printf("Got photo with data length: %d\n", datalen);
+
+       memset(template, 0, sizeof(template));
+       strcpy(template, "/tmp/tmpXXXXXX.JPG");
+       fd = mkstemps(template, 4);
+
+       while (written < datalen) {
+               ret = write(fd, data+written, datalen-written);
+               if (ret <= 0) break;
+               written += ret;
+       }
+       if (written == datalen) {
+               printf("Wrote to file %s\n", template);
+       }
+       close(fd);
+}
+
+static void
+play_cb()
+{
+}
+
+static void
+stop_cb()
+{
+}
+
+static void
+rate_set_cb()
+{
+}
+
+static void
+scrub_get_cb()
+{
+}
+
+static void
+scrub_set_cb()
+{
+}
+
+static void
+playback_info_cb()
+{
+}
+
+static void *
+audio_init(void *opaque, int bits, int channels, int samplerate)
+{
+       int driver;
+       ao_sample_format format;
+       ao_option *ao_opts = NULL;
+       ao_device *device;
+
+       printf("Opening audio device\n");
+       driver = ao_driver_id("pulse");
+
+       memset(&format, 0, sizeof(format));
+       format.bits = bits;
+       format.channels = channels;
+       format.rate = samplerate;
+       format.byte_format = AO_FMT_LITTLE;
+
+       ao_append_option(&ao_opts, "id", "0");
+       device = ao_open_live(driver, &format, ao_opts);
+       if (!device) {
+               fprintf(stderr, "Error opening audio device.\n");
+       } else {
+               printf("Opening device successful\n");
+       }
+       return device;
+}
+
+static void
+audio_process(void *ptr, const void *buffer, int buflen)
+{
+       ao_device *device = ptr;
+
+       assert(device);
+
+       printf("Got %d bytes of audio\n", buflen);
+       ao_play(device, (char *)buffer, buflen);
+}
+
+static void
+audio_flush(void *ptr)
+{
+}
+
+static void
+audio_destroy(void *ptr)
+{
+       ao_device *device = ptr;
+
+       printf("Closing audio device\n");
+       ao_close(device);
+}
+
+int
+main(int argc, char *argv[])
+{
+        const char *name = "AppleTV";
+        unsigned short raop_port = 5000;
+        unsigned short airplay_port = 7000;
+        const char hwaddr[] = { 0x48, 0x5d, 0x60, 0x7c, 0xee, 0x22 };
+       char *pemstr;
+
+       dnssd_t *dnssd;
+       airplay_t *airplay;
+       airplay_callbacks_t ap_cbs;
+       raop_t *raop;
+       raop_callbacks_t raop_cbs;
+
+       if (utils_read_file(&pemstr, "airport.key") < 0) {
+               return -1;
+       }
+       if (argc > 1) {
+               test_rsa(pemstr);
+       }
+
+       ao_initialize();
+
+       dnssd = dnssd_init(hwaddr, sizeof(hwaddr), NULL);
+       dnssd_register_raop(dnssd, name, raop_port);
+       dnssd_register_airplay(dnssd, name, airplay_port);
+
+       ap_cbs.photo_cb = &photo_cb;
+       ap_cbs.play_cb = &play_cb;
+       ap_cbs.stop_cb = &stop_cb;
+       ap_cbs.rate_set_cb = &rate_set_cb;
+       ap_cbs.scrub_get_cb = &scrub_get_cb;
+       ap_cbs.scrub_set_cb = &scrub_set_cb;
+       ap_cbs.playback_info_cb = &playback_info_cb;
+
+       raop_cbs.audio_init = audio_init;
+       raop_cbs.audio_process = audio_process;
+       raop_cbs.audio_flush = audio_flush;
+       raop_cbs.audio_destroy = audio_destroy;
+
+       airplay = airplay_init(&ap_cbs, hwaddr, sizeof(hwaddr));
+       airplay_start(airplay, airplay_port);
+
+       raop = raop_init(&raop_cbs, pemstr, hwaddr, sizeof(hwaddr));
+       raop_start(raop, &raop_port);
+
+       sleep(100);
+
+       raop_stop(raop);
+       raop_destroy(raop);
+
+       airplay_stop(airplay);
+       airplay_destroy(airplay);
+
+       dnssd_unregister_airplay(dnssd);
+       dnssd_unregister_raop(dnssd);
+       dnssd_destroy(dnssd);
+
+       ao_shutdown();
+
+       return 0;
+}
+
diff --git a/test/shairport.c b/test/shairport.c
new file mode 100644 (file)
index 0000000..15f91f6
--- /dev/null
@@ -0,0 +1,75 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <unistd.h>
+
+#include "dnssd.h"
+#include "raop.h"
+
+static void
+audio_init(void *cls, void **session, int bits, int channels, int samplerate)
+{
+       *session = fopen("audio.pcm", "wb");
+}
+
+static void
+audio_set_volume(void *cls, void *session, float volume)
+{
+       printf("Setting volume to %f\n", volume);
+}
+
+static void
+audio_process(void *cls, void *session, const void *buffer, int buflen)
+{
+       int orig = buflen;
+       while (buflen > 0) {
+               buflen -= fwrite(buffer+orig-buflen, 1, buflen, session);
+       }
+}
+
+static void
+audio_flush(void *cls, void *session)
+{
+       printf("Flushing audio\n");
+}
+
+static void
+audio_destroy(void *cls, void *session)
+{
+       fclose(session);
+}
+
+int
+main(int argc, char *argv[])
+{
+        const char *name = "AppleTV";
+        unsigned short raop_port = 5000;
+        const char hwaddr[] = { 0x48, 0x5d, 0x60, 0x7c, 0xee, 0x22 };
+
+       dnssd_t *dnssd;
+       raop_t *raop;
+       raop_callbacks_t raop_cbs;
+
+       raop_cbs.cls = NULL;
+       raop_cbs.audio_init = audio_init;
+       raop_cbs.audio_set_volume = audio_set_volume;
+       raop_cbs.audio_process = audio_process;
+       raop_cbs.audio_flush = audio_flush;
+       raop_cbs.audio_destroy = audio_destroy;
+
+       raop = raop_init_from_keyfile(&raop_cbs, "airport.key", hwaddr, sizeof(hwaddr));
+       raop_start(raop, &raop_port);
+
+       dnssd = dnssd_init(hwaddr, sizeof(hwaddr), NULL);
+       dnssd_register_raop(dnssd, name, raop_port);
+
+       sleep(100);
+
+       dnssd_unregister_raop(dnssd);
+       dnssd_destroy(dnssd);
+
+       raop_stop(raop);
+       raop_destroy(raop);
+
+       return 0;
+}
+