Exemplo n.º 1
0
String WebSocketHandshake::clientLocation() const
{
    StringBuilder builder;
    builder.append(m_secure ? "wss" : "ws");
    builder.append("://");
    builder.append(hostName(m_url, m_secure));
    builder.append(resourceName(m_url));
    return builder.toString();
}
Exemplo n.º 2
0
QT_BEGIN_NAMESPACE

static QByteArray localHostName() // from QHostInfo::localHostName(), modified to return a QByteArray
{
    QByteArray hostName(512, Qt::Uninitialized);
    if (gethostname(hostName.data(), hostName.size()) == -1)
        return QByteArray();
    hostName.truncate(strlen(hostName.data()));
    return hostName;
}
Exemplo n.º 3
0
CString WebSocketHandshake::clientHandshakeMessage() const
{
    // Keep the following consistent with clientHandshakeRequest().
    StringBuilder builder;

    builder.append("GET ");
    builder.append(resourceName(m_url));
    builder.append(" HTTP/1.1\r\n");

    Vector<String> fields;
    fields.append("Upgrade: websocket");
    fields.append("Connection: Upgrade");
    fields.append("Host: " + hostName(m_url, m_secure));
    fields.append("Origin: " + clientOrigin());
    if (!m_clientProtocol.isEmpty())
        fields.append("Sec-WebSocket-Protocol: " + m_clientProtocol);

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

    // Add no-cache headers to avoid compatibility issue.
    // There are some proxies that rewrite "Connection: upgrade"
    // to "Connection: close" in the response if a request doesn't contain
    // these headers.
    fields.append("Pragma: no-cache");
    fields.append("Cache-Control: no-cache");

    fields.append("Sec-WebSocket-Key: " + m_secWebSocketKey);
    fields.append("Sec-WebSocket-Version: 13");
    const String extensionValue = m_extensionDispatcher.createHeaderValue();
    if (extensionValue.length())
        fields.append("Sec-WebSocket-Extensions: " + extensionValue);

    // Add a User-Agent header.
    fields.append("User-Agent: " + m_context->userAgent(m_context->url()));

    // Fields in the handshake are sent by the client in a random order; the
    // order is not meaningful.  Thus, it's ok to send the order we constructed
    // the fields.

    for (size_t i = 0; i < fields.size(); i++) {
        builder.append(fields[i]);
        builder.append("\r\n");
    }

    builder.append("\r\n");

    return builder.toString().utf8();
}
Exemplo n.º 4
0
ConnectionInfo CWizardIrcConnection::connection() const
{
	ConnectionInfo connection;
	connection.nick = nickName();
	connection.real = realName();
	connection.host = hostName();
	connection.port = port();
	connection.secure = isSecure();
	connection.user = userName();
	connection.pass = password();
	connection.name = connectionName();
	return connection;
}
Exemplo n.º 5
0
QString Smb4KCustomOptions::unc() const
{
  QString unc;
  
  switch (d->type)
  {
    case Host:
    {
      if (!hostName().isEmpty())
      {
        unc = QString("//%1").arg(hostName());
      }
      else
      {
        // Do nothing
      }
      break;
    }
    case Share:
    {
      if (!hostName().isEmpty() && !shareName().isEmpty())
      {
        unc = QString("//%1/%2").arg(hostName()).arg(shareName());
      }
      else
      {
        // Do nothing
      }
      break;
    }
    default:
    {
      break;
    }
  }

  return unc;
}
CString WebSocketHandshake::clientHandshakeMessage() const
{
    // Keep the following consistent with clientHandshakeRequest().
    StringBuilder builder;

    builder.append("GET ");
    builder.append(resourceName(m_url));
    builder.append(" HTTP/1.1\r\n");

    Vector<String> fields;
    fields.append("Upgrade: WebSocket");
    fields.append("Connection: Upgrade");
    fields.append("Host: " + hostName(m_url, m_secure));
    fields.append("Origin: " + clientOrigin());
    if (!m_clientProtocol.isEmpty())
        fields.append("Sec-WebSocket-Protocol: " + m_clientProtocol);

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

    fields.append("Sec-WebSocket-Key1: " + m_secWebSocketKey1);
    fields.append("Sec-WebSocket-Key2: " + m_secWebSocketKey2);

    // Fields in the handshake are sent by the client in a random order; the
    // order is not meaningful.  Thus, it's ok to send the order we constructed
    // the fields.

    for (size_t i = 0; i < fields.size(); i++) {
        builder.append(fields[i]);
        builder.append("\r\n");
    }

    builder.append("\r\n");

    CString handshakeHeader = builder.toString().utf8();
    char* characterBuffer = 0;
    CString msg = CString::newUninitialized(handshakeHeader.length() + sizeof(m_key3), characterBuffer);
    memcpy(characterBuffer, handshakeHeader.data(), handshakeHeader.length());
    memcpy(characterBuffer + handshakeHeader.length(), m_key3, sizeof(m_key3));
    return msg;
}
Exemplo n.º 7
0
int CUIManager::NetGameMenu()
{
   CBox box(100, 100, 440, 280, 200, 50, 170);
   CTextBox playerName(180, 120, 20, cfg.Get("GAME", "PlayerName", "Player"));
   gpGeneral->DrawText(msg("menu_playername"), 110, 120, 255, 250, 50);
   CTextBox pwd(180, 150, 20, cfg.Get("GAME", "ServerPwd", ""));
   gpGeneral->DrawText(msg("menu_password"), 110, 150, 255, 250, 50);
   CTextBox hostName(180, 180, 20, cfg.Get("GAME", "HostName", ""));
   gpGeneral->DrawText(msg("menu_hostaddr"), 110, 180, 255, 250, 50);

   CButton btnServer(1, 110, 350, 100, 20, 50, 220, 200);
   gpGeneral->DrawText(msg("menu_server"), 160 - strlen(msg("menu_server")) * 4, 352, 255, 250, 50);
   CButton btnClient(2, 220, 350, 100, 20, 50, 220, 200);
   gpGeneral->DrawText(msg("menu_client"), 270 - strlen(msg("menu_client")) * 4, 352, 255, 250, 50);
   CButton btnCancel(3, 330, 350, 100, 20, 50, 220, 200);
   gpGeneral->DrawText(msg("menu_cancel"), 380 - strlen(msg("menu_cancel")) * 4, 352, 255, 250, 50);

   while (1) {
      int key = gpGeneral->ReadKey() - SDLK_LAST;
      if (key == 1) {
         // SERVER button pressed
         if (strlen(playerName.Text()) > 0) {
            cfg.Set("GAME", "PlayerName", playerName.Text());
         }
         cfg.Set("GAME", "ServerPwd", pwd.Text());
         gpGeneral->DrawText(msg("connecting"), 0, 440, 255, 255, 0);
         return 1;
      } else if (key == 2) {
         // CLIENT button pressed
         if (strlen(hostName.Text()) <= 0) {
            continue;
         }
         if (strlen(playerName.Text()) > 0) {
            cfg.Set("GAME", "PlayerName", playerName.Text());
         }
         cfg.Set("GAME", "HostName", hostName.Text());
         cfg.Set("GAME", "ServerPwd", pwd.Text());
         gpGeneral->DrawText(msg("connecting"), 0, 440, 255, 255, 0);
         return 2;
      } else if (key == 3) {
         // Cancel button pressed
         return 0; // do nothing
      }
   }
   return 0;
}
Exemplo n.º 8
0
CString WebSocketHandshake::clientHandshakeMessage() const
{
    // Keep the following consistent with clientHandshakeRequest().
    StringBuilder builder;

    builder.append("GET ");
    builder.append(resourceName(m_url));
    builder.append(" HTTP/1.1\r\n");

    Vector<String> fields;
    fields.append("Upgrade: websocket");
    fields.append("Connection: Upgrade");
    fields.append("Host: " + hostName(m_url, m_secure));
    fields.append("Origin: " + clientOrigin());
    if (!m_clientProtocol.isEmpty())
        fields.append("Sec-WebSocket-Protocol: " + m_clientProtocol);

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

    fields.append("Sec-WebSocket-Key: " + m_secWebSocketKey);
    fields.append("Sec-WebSocket-Version: 13");
    const String extensionValue = m_extensionDispatcher.createHeaderValue();
    if (extensionValue.length())
        fields.append("Sec-WebSocket-Extensions: " + extensionValue);

    // Fields in the handshake are sent by the client in a random order; the
    // order is not meaningful.  Thus, it's ok to send the order we constructed
    // the fields.

    for (size_t i = 0; i < fields.size(); i++) {
        builder.append(fields[i]);
        builder.append("\r\n");
    }

    builder.append("\r\n");

    return builder.toString().utf8();
}
Exemplo n.º 9
0
// Null constructor
Foam::JobInfo::JobInfo()
:
    runningJobPath_(),
    finishedJobPath_(),
    cpuTime_()
{
    name() = "JobInfo";

    if (writeJobInfo && Pstream::master())
    {
        string baseDir = getEnv("FOAM_JOB_DIR");
        string jobFile = hostName() + '.' + Foam::name(pid());

        fileName runningDir(baseDir/"runningJobs");
        fileName finishedDir(baseDir/"finishedJobs");

        runningJobPath_  = runningDir/jobFile;
        finishedJobPath_ = finishedDir/jobFile;

        if (baseDir.empty())
        {
            FatalErrorIn("JobInfo::JobInfo()")
                << "Cannot get JobInfo directory $FOAM_JOB_DIR"
                << Foam::exit(FatalError);
        }

        if (!isDir(runningDir) && !mkDir(runningDir))
        {
            FatalErrorIn("JobInfo::JobInfo()")
                << "Cannot make JobInfo directory " << runningDir
                << Foam::exit(FatalError);
        }

        if (!isDir(finishedDir) && !mkDir(finishedDir))
        {
            FatalErrorIn("JobInfo::JobInfo()")
                << "Cannot make JobInfo directory " << finishedDir
                << Foam::exit(FatalError);
        }
    }

    constructed = true;
}
Exemplo n.º 10
0
WebSocketHandshakeRequest WebSocketHandshake::clientHandshakeRequest() const
{
    // Keep the following consistent with clientHandshakeMessage().
    // FIXME: do we need to store m_secWebSocketKey1, m_secWebSocketKey2 and
    // m_key3 in WebSocketHandshakeRequest?
    WebSocketHandshakeRequest request("GET", m_url);
    if (m_useHixie76Protocol)
        request.addHeaderField("Upgrade", "WebSocket");
    else
        request.addHeaderField("Upgrade", "websocket");
    request.addHeaderField("Connection", "Upgrade");
    request.addHeaderField("Host", hostName(m_url, m_secure));
    request.addHeaderField("Origin", clientOrigin());
    if (!m_clientProtocol.isEmpty())
        request.addHeaderField("Sec-WebSocket-Protocol:", m_clientProtocol);

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

    if (m_useHixie76Protocol) {
        request.addHeaderField("Sec-WebSocket-Key1", m_hixie76SecWebSocketKey1);
        request.addHeaderField("Sec-WebSocket-Key2", m_hixie76SecWebSocketKey2);
        request.setKey3(m_hixie76Key3);
    } else {
        request.addHeaderField("Sec-WebSocket-Key", m_secWebSocketKey);
        request.addHeaderField("Sec-WebSocket-Version", "13");
        const String extensionValue = m_extensionDispatcher.createHeaderValue();
        if (extensionValue.length())
            request.addHeaderField("Sec-WebSocket-Extensions", extensionValue);
    }

    return request;
}
Exemplo n.º 11
0
QVariantMap CoreAccount::toVariantMap(bool forcePassword) const
{
    QVariantMap v;
    v["AccountId"] = accountId().toInt(); // can't use AccountId because then comparison fails
    v["AccountName"] = accountName();
    v["Uuid"] = uuid().toString();
    v["Internal"] = isInternal();
    v["User"] = user();
    if (_storePassword || forcePassword)
        v["Password"] = password();
    else
        v["Password"] = QString();
    v["StorePassword"] = storePassword();
    v["HostName"] = hostName();
    v["Port"] = port();
    v["UseSSL"] = useSsl();
    v["ProxyType"] = proxyType();
    v["ProxyUser"] = proxyUser();
    v["ProxyPassword"] = proxyPassword();
    v["ProxyHostName"] = proxyHostName();
    v["ProxyPort"] = proxyPort();
    return v;
}
Exemplo n.º 12
0
ResourceRequest WebSocketHandshake::clientHandshakeRequest() const
{
    // Keep the following consistent with clientHandshakeMessage().
    // FIXME: do we need to store m_secWebSocketKey1, m_secWebSocketKey2 and
    // m_key3 in the request?
    ResourceRequest request(m_url);
    request.setHTTPMethod("GET");

    request.addHTTPHeaderField("Connection", "Upgrade");
    request.addHTTPHeaderField("Host", hostName(m_url, m_secure));
    request.addHTTPHeaderField("Origin", clientOrigin());
    if (!m_clientProtocol.isEmpty())
        request.addHTTPHeaderField("Sec-WebSocket-Protocol", m_clientProtocol);

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

    request.addHTTPHeaderField("Pragma", "no-cache");
    request.addHTTPHeaderField("Cache-Control", "no-cache");

    request.addHTTPHeaderField("Sec-WebSocket-Key", m_secWebSocketKey);
    request.addHTTPHeaderField("Sec-WebSocket-Version", "13");
    const String extensionValue = m_extensionDispatcher.createHeaderValue();
    if (extensionValue.length())
        request.addHTTPHeaderField("Sec-WebSocket-Extensions", extensionValue);

    // Add a User-Agent header.
    request.addHTTPHeaderField("User-Agent", m_context->userAgent(m_context->url()));

    return request;
}
Exemplo n.º 13
0
//------------------------------------------------------------------------------
// FUNCTION:   getDNSName
//
// REMARKS:    returns the Name Property
//
// PARAMETERS: [OUT]  name -> string that will receive the NTP Name property
//
// RETURN:     true, if there's a DNS Name
//------------------------------------------------------------------------------
Boolean DNSService::getDNSName(String & name)
{
#ifdef DNSPROVIDER_DEBUG
    cout << "DNSService::getDNSName()" << endl;
#endif

    if (dnsName.size() != 0)
    {
#ifdef DNSPROVIDER_DEBUG
        cout << "DNSService::getDNSName() - dnsName = '" << dnsName <<
             "'" << endl;
#endif
        name.assign(dnsName);
    }
    else 
    {
        // initialize dnsName to root domain(" ")
        dnsName.assign(" ");

        char host[PEGASUS_MAXHOSTNAMELEN + 1];

        if (gethostname(host,sizeof(host)) == 0)
        {
                host[sizeof(host)-1] = 0;
                String hostName(host);
                Uint32 domainIndex =0;

                if( (domainIndex=hostName.find('.')) != PEG_NOT_FOUND)
                {
                    dnsName=hostName.subString(domainIndex+1,PEG_NOT_FOUND);
                }
        }
        name.assign(dnsName);
    }
    return true;
}
Exemplo n.º 14
0
PEGASUS_NAMESPACE_BEGIN

String Guid::getGuid(const String &prefix)
{
  Uint32 seconds(0), milliSeconds(0);
  System::getCurrentTime(seconds, milliSeconds);
  CIMValue secondsValue(seconds);
  CIMValue milliSecondsValue(milliSeconds);
  String ipAddress;
  String hostName(System::getHostName());
  if ((ipAddress = System::getHostIP(hostName)) == String::EMPTY)
  {
      // set default address if everything else failed
      ipAddress = String("127.0.0.1");
  }
  // change the dots to dashes
  for (Uint32 i=0; i<ipAddress.size(); i++)
    {
      if (ipAddress[i] == Char16('.'))
        ipAddress[i] = Char16('-');
    }

  return (secondsValue.toString() + milliSecondsValue.toString() + "-" + ipAddress);
}
Exemplo n.º 15
0
/*!
 * Returns \c true is this endpoint is valid; \c false otherwise.
 *
 * The endpoint is considered valid if the host specified during construction is
 * a known AWS host, and thus we know what region and service(s) it supports.
 *
 * For example:
 * \code
 * AwsEndpoint good(QLatin1String("cloudformation.us-east-1.amazonaws.com"));
 * AwsEndpoint bad(QLatin1String("example.com"));
 * Q_ASSERT(good.isValid()); // good is valid.
 * Q_ASSERT(!bad.isValid()); // bad is not.
 * \endcode
 */
bool AwsEndpoint::isValid() const
{
    return ((!hostName().isEmpty()) && (!regionName().isEmpty()) && (!serviceName().isEmpty()));
}
Exemplo n.º 16
0
int TcDatabase::open()
{
    int ret = 0;
    close();
    switch(dbType())
    {
    case SQLSERVER:
        //QSqlDatabase::removeDatabase("FriendSafe");
        m_handle = QSqlDatabase::addDatabase("QODBC");
        {
            QString dsn = QString("DRIVER={SQL SERVER};SERVER=%1;DATABASE=%2;").arg(hostName()).arg(dbName());
            m_handle.setDatabaseName(dsn);
            m_handle.setUserName(m_username);
            m_handle.setPassword(m_password);
        }
        ret = m_handle.open() ? 1 : 0;
        break;

    case MYSQL:
        //QSqlDatabase::removeDatabase("qt_sql_default_connection");
        m_handle = QSqlDatabase::addDatabase("QMYSQL");//, "qt_sql_default_connection");//, "allowMultiQueries=true");
        m_handle.setHostName(hostName());
        m_handle.setDatabaseName(dbName());
        m_handle.setUserName(m_username);
        m_handle.setPassword(m_password);
        //m_handle.setConnectOptions("allowMultiQueries=true");
        //m_handle.cloneDatabase()
        ret = m_handle.open() ? 1 : 0;
//DEBUG_OUT(m_handle.connectionName())
//DEBUG_OUT(m_handle.connectionNames().join("\n"))
        break;

    case POSTGRESQL:
        //QSqlDatabase::removeDatabase("");
        m_handle = QSqlDatabase::addDatabase("QPSQL");
        m_handle.setHostName(hostName());
        m_handle.setDatabaseName(dbName());
        m_handle.setUserName(m_username);
        m_handle.setPassword(m_password);
        //m_handle.setConnectOptions("allowMultiQueries=true");
        //m_handle.cloneDatabase()
        ret = m_handle.open() ? 1 : 0;
//DEBUG_OUT(m_handle.connectionName())
//DEBUG_OUT(m_handle.connectionNames().join("\n"))
        break;

    case SQLTIE:
        //QSqlDatabase::removeDatabase("FriendSafe");
        m_handle = QSqlDatabase::addDatabase("QSQLITE");

        QFileInfo dbFile(m_dbName);
        QDir dir(dbFile.absoluteDir());
        dir.mkpath(dbFile.absolutePath());
        m_handle.setDatabaseName(m_dbName);
        m_handle.setUserName(m_username);
        m_handle.setPassword(m_password);

        if ( m_handle.open() )
        {
            m_hostName = "localhost";
            m_hostPort = 0;
            QStringList tables = m_handle.tables();
            if ( tables.count() <= 0 )
            {
                // 没有任何表,这个库是新建的。
                QFile f(CreateDDL);
                if ( f.open(QFile::Text | QFile::ReadOnly) )
                {
                    QTextStream in(&f);
                    QString fileText = in.readAll();
                    f.close();

                    ret = 1;
                    QSqlQuery query = QSqlQuery(m_handle);
                    int pos;
                    while((pos=fileText.indexOf(";")) >-1)
                    {
                        QString sqlText = fileText.mid(0, pos).trimmed();
                        fileText.remove(0, pos+1);
                        fileText = fileText.trimmed();

                        QStringList sqlLines = sqlText.split("\n", QString::SkipEmptyParts);
                        QString sql;
                        for( int i=0;i<sqlLines.count();i++ )
                        {
                            QString s = sqlLines.at(i);
                            if ( ! s.startsWith("--") )
                            {
                                sql += s + "\n";
                            }
                        }
                        if ( ! sql.isEmpty() && ! query.exec(sql) )
                        {
                            ret = -1;
                        }
                    }
                    query.finish();
                }
            }else
            {
                ret = 1;
            }
        }
        break;
    }
    m_accepted = ret >0;
    return ret;
}
Exemplo n.º 17
0
void SyslogParser::parseBSD(const std::string& msg, RemoteSyslogChannel::Severity severity, RemoteSyslogChannel::Facility fac, std::size_t& pos)
{
	Poco::Message::Priority prio = convert(severity);
	// rest of the unparsed header is:
	// "%b %f %H:%M:%S" SP hostname|ipaddress
	// detect three spaces
	int spaceCnt = 0;
	std::size_t start = pos;
	while (spaceCnt < 3 && pos < msg.size())
	{
		if (msg[pos] == ' ')
		{
			spaceCnt++;
			if (spaceCnt == 1)
			{
				// size must be 3 chars for month
				if (pos - start != 3)
				{
					// probably a shortened time value, or the hostname
					// assume hostName
					Poco::Message logEntry(msg.substr(start, pos-start), msg.substr(pos+1), prio);
					_pListener->log(logEntry);
					return;
				}
			}
			else if (spaceCnt == 2)
			{
				// a day value!
				if (!(std::isdigit(msg[pos-1]) && (std::isdigit(msg[pos-2]) || std::isspace(msg[pos-2]))))
				{
					// assume the next field is a hostname
					spaceCnt = 3;
				}
			}
			if (pos + 1 < msg.size() && msg[pos+1] == ' ')
			{
				// we have two spaces when the day value is smaller than 10!
				++pos; // skip one
			}
		}
		++pos;
	}
	std::string timeStr(msg.substr(start, pos-start-1));
	int tzd(0);
	Poco::DateTime date;
	int year = date.year(); // year is not included, use the current one
	bool hasDate = Poco::DateTimeParser::tryParse(RemoteSyslogChannel::BSD_TIMEFORMAT, timeStr, date, tzd);
	if (hasDate)
	{
		int m = date.month();
		int d = date.day();
		int h = date.hour();
		int min = date.minute();
		int sec = date.second();
		date = Poco::DateTime(year, m, d, h, min, sec);
	}
	// next entry is host SP
	std::string hostName(parseUntilSpace(msg, pos));

	// TAG: at most 32 alphanumeric chars, ANY non alphannumeric indicates start of message content
	// ignore: treat everything as content
	std::string message(msg.substr(pos));
	pos = msg.size();
	Poco::Message logEntry(hostName, message, prio);
	logEntry.setTime(date.timestamp());
	_pListener->log(logEntry);
}
Exemplo n.º 18
0
int main()
{

#ifdef WINDOWS_XP

	// Initialize the winsock library
	WSADATA wsaData;
    winLog << "system started ..." << endl;
	winLog << endl << "initialize the winsock library ... ";

	try 
	{
		if (WSAStartup(0x101, &wsaData))
		{
			myException* initializationException = new myException(0,"Error: calling WSAStartup()");
			throw initializationException;
        }
	}
	catch(myException* excp)
	{
		excp->response();
		delete excp;
		exit(1);
	}
	winLog << "successful" << endl;

#endif
        
    // Retrieve the host name and host address given the host name

	string hName = "www.yuchen.net";
	winLog << endl;
	winLog << "Retrieve the host name and host address given the host name:" << endl;
	winLog << "		==> the given domain name is " << hName << endl;
	
    myHostInfo hostName(hName, NAME);
	string givenHostName = hostName.getHostName();
	string givenHostAddr = hostName.getHostIPAddress();
    cout << "Server name: "  << givenHostName << endl;
    cout << "Server IP address: "  << givenHostAddr << endl;
	winLog << "		==> Name: " << givenHostName << endl;
	winLog << "		==> Address: " << givenHostAddr << endl;

    // Retrieve the host name and host address given the host address
/*
	string IPaddress = "209.86.128.254";
	winLog << endl;
	winLog << "Retrieve the host name and host address given the host address:" << endl;
	winLog << "		==> the given address is " << IPaddress << endl;

    myHostInfo hostAddress(IPaddress, ADDRESS);
	givenHostName = hostAddress.getHostName();
	givenHostAddr = hostAddress.getHostIPAddress();
    cout << "Name: " << givenHostName << endl;
    cout << "Address: " << givenHostAddr << endl;
	winLog << "		==> Name: " << givenHostName << endl;
	winLog << "		==> Address: " << givenHostAddr << endl;
    
	// get local information if neither the name or the address is given

	winLog << endl;
	winLog << "Retrieve the local host name and address with no information:" << endl;
	
    myHostInfo uHostAddress;
	string localHostName = uHostAddress.getHostName();
    string localHostAddr = uHostAddress.getHostIPAddress();
    cout << "Name: " << localHostName << endl;
    cout << "Address: " << localHostAddr << endl;
	winLog << "		==> Name: " << localHostName << endl;
	winLog << "		==> Address: " << localHostAddr << endl;
*/
#ifdef UNIX

    // Retrieve all entries from the host name database
    myHostInfo AllHosts;
    while(AllHosts.cGetNextHost())
    {
        cout << "Name: " << AllHosts.sGetHostName() << endl;
        cout << "Address: " << AllHosts.sGetHostAddress() << endl;
    }

#endif

#ifdef WINDOWS_XP

    // Close the winsock library
	winLog << endl << "system shut down ...";		
	
	try 
	{
		if (WSACleanup())
		{
			myException* cleanupException = new myException(0,"Error: calling WSACleanup()");
			throw cleanupException;
        }
	}
	catch(myException* excp)
	{
		excp->response();
		delete excp;
		exit(1);
	}
	winLog << "successful" << endl;

#endif

    return 1;
}
Exemplo n.º 19
0
void BinHTTPInputStreamCommon::createHTTPRequest(const XMLURL &urlSource, const XMLNetHTTPInfo *httpInfo, CharBuffer &buffer)
{
    static const char *GET = "GET ";
    static const char *PUT = "PUT ";
    static const char *POST = "POST ";
    static const char *HTTP10 = " HTTP/1.0\r\n";
    static const char *HOST = "Host: ";
    static const char *AUTHORIZATION = "Authorization: Basic ";
    static const char *COLON = ":";

    XMLTransService::Codes failReason;
    const XMLSize_t blockSize = 2048;

    XMLTranscoder* trans = XMLPlatformUtils::fgTransService->makeNewTranscoderFor("ISO8859-1", failReason, blockSize, fMemoryManager);
    Janitor<XMLTranscoder> janTrans(trans);

    TranscodeToStr hostName(urlSource.getHost(), trans, fMemoryManager);
    TranscodeToStr path(urlSource.getPath(), trans, fMemoryManager);
    TranscodeToStr fragment(urlSource.getFragment(), trans, fMemoryManager);
    TranscodeToStr query(urlSource.getQuery(), trans, fMemoryManager);

    // Build up the http GET command to send to the server.
    // To do:  We should really support http 1.1.  This implementation
    //         is weak.
    if(httpInfo) {
        switch(httpInfo->fHTTPMethod) {
        case XMLNetHTTPInfo::GET:   buffer.append(GET); break;
        case XMLNetHTTPInfo::PUT:   buffer.append(PUT); break;
        case XMLNetHTTPInfo::POST:  buffer.append(POST); break;
        }
    }
    else {
        buffer.append(GET);
    }

    if(path.str() != 0) {
        buffer.append((char*)path.str());
    }
    else {
        buffer.append("/");
    }

    if(query.str() != 0) {
        buffer.append("?");
        buffer.append((char*)query.str());
    }

    if(fragment.str() != 0) {
        buffer.append((char*)fragment.str());
    }
    buffer.append(HTTP10);

    buffer.append(HOST);
    buffer.append((char*)hostName.str());
    if(urlSource.getPortNum() != 80)
    {
        buffer.append(COLON);
        buffer.appendDecimalNumber(urlSource.getPortNum());
    }
    buffer.append(CRLF);

    const XMLCh *username = urlSource.getUser();
    const XMLCh *password = urlSource.getPassword();
    if(username && password) {
        XMLBuffer userPassBuf(256, fMemoryManager);
        userPassBuf.append(username);
        userPassBuf.append(chColon);
        userPassBuf.append(password);

        TranscodeToStr userPass(userPassBuf.getRawBuffer(), trans, fMemoryManager);

        XMLSize_t len;
        XMLByte* encodedData = Base64::encode(userPass.str(), userPass.length(), &len, fMemoryManager);
        ArrayJanitor<XMLByte> janBuf2(encodedData, fMemoryManager);

        if(encodedData) {
            // HTTP doesn't want the 0x0A separating the data in chunks of 76 chars per line
            XMLByte* authData = (XMLByte*)fMemoryManager->allocate((len+1)*sizeof(XMLByte));
            ArrayJanitor<XMLByte> janBuf(authData, fMemoryManager);
            XMLByte *cursor = authData;
            for(XMLSize_t i = 0; i < len; ++i)
                if(encodedData[i] != chLF)
                    *cursor++ = encodedData[i];
            *cursor++ = 0;
            buffer.append(AUTHORIZATION);
            buffer.append((char*)authData);
            buffer.append(CRLF);
        }
    }

    if(httpInfo && httpInfo->fHeaders)
        buffer.append(httpInfo->fHeaders, httpInfo->fHeadersLen);

    buffer.append(CRLF);
}
Exemplo n.º 20
0
void Foam::argList::parse
(
    bool checkArgs,
    bool checkOpts,
    bool initialise
)
{
    // Help/documentation options:
    //   -help    print the usage
    //   -doc     display application documentation in browser
    //   -srcDoc  display source code in browser
    if
    (
        options_.found("help")
     || options_.found("doc")
     || options_.found("srcDoc")
    )
    {
        if (options_.found("help"))
        {
            printUsage();
        }

        // Only display one or the other
        if (options_.found("srcDoc"))
        {
            displayDoc(true);
        }
        else if (options_.found("doc"))
        {
            displayDoc(false);
        }

        ::exit(0);
    }

    // Print the usage message and exit if the number of arguments is incorrect
    if (!check(checkArgs, checkOpts))
    {
        FatalError.exit();
    }


    if (initialise)
    {
        string dateString = clock::date();
        string timeString = clock::clockTime();

        // Print the banner once only for parallel runs
        if (Pstream::master() && bannerEnabled)
        {
            IOobject::writeBanner(Info, true)
                << "Build  : " << Foam::FOAMbuild << nl
                << "Exec   : " << argListStr_.c_str() << nl
                << "Date   : " << dateString.c_str() << nl
                << "Time   : " << timeString.c_str() << nl
                << "Host   : " << hostName() << nl
                << "PID    : " << pid() << endl;
        }

        jobInfo.add("startDate", dateString);
        jobInfo.add("startTime", timeString);
        jobInfo.add("userName", userName());
        jobInfo.add("foamVersion", word(FOAMversion));
        jobInfo.add("code", executable_);
        jobInfo.add("argList", argListStr_);
        jobInfo.add("currentDir", cwd());
        jobInfo.add("PPID", ppid());
        jobInfo.add("PGID", pgid());

        // Add build information - only use the first word
        {
            std::string build(Foam::FOAMbuild);
            std::string::size_type found = build.find(' ');
            if (found != std::string::npos)
            {
                build.resize(found);
            }
            jobInfo.add("foamBuild", build);
        }
    }

    // Case is a single processor run unless it is running parallel
    int nProcs = 1;

    // Roots if running distributed
    fileNameList roots;


    // If this actually is a parallel run
    if (parRunControl_.parRun())
    {
        // For the master
        if (Pstream::master())
        {
            // Establish rootPath_/globalCase_/case_ for master
            getRootCase();

            // See if running distributed (different roots for different procs)
            label dictNProcs = -1;
            fileName source;

            if (options_.found("roots"))
            {
                source = "-roots";
                IStringStream is(options_["roots"]);
                roots = readList<fileName>(is);

                if (roots.size() != 1)
                {
                    dictNProcs = roots.size()+1;
                }
            }
            else
            {
                source = rootPath_/globalCase_/"system/decomposeParDict";
                IFstream decompDictStream(source);

                if (!decompDictStream.good())
                {
                    FatalError
                        << "Cannot read "
                        << decompDictStream.name()
                        << exit(FatalError);
                }

                dictionary decompDict(decompDictStream);

                dictNProcs = readLabel
                (
                    decompDict.lookup("numberOfSubdomains")
                );

                if (decompDict.lookupOrDefault("distributed", false))
                {
                    decompDict.lookup("roots") >> roots;
                }
            }

            // Convenience:
            // when a single root is specified, use it for all processes
            if (roots.size() == 1)
            {
                const fileName rootName(roots[0]);
                roots.setSize(Pstream::nProcs()-1, rootName);

                // adjust dictNProcs for command-line '-roots' option
                if (dictNProcs < 0)
                {
                    dictNProcs = roots.size()+1;
                }
            }


            // Check number of processors.
            // nProcs     => number of actual procs
            // dictNProcs => number of procs specified in decompositionDict
            // nProcDirs  => number of processor directories
            //               (n/a when running distributed)
            //
            // - normal running : nProcs = dictNProcs = nProcDirs
            // - decomposition to more  processors : nProcs = dictNProcs
            // - decomposition to fewer processors : nProcs = nProcDirs
            if (dictNProcs > Pstream::nProcs())
            {
                FatalError
                    << source
                    << " specifies " << dictNProcs
                    << " processors but job was started with "
                    << Pstream::nProcs() << " processors."
                    << exit(FatalError);
            }


            // Distributed data
            if (roots.size())
            {
                if (roots.size() != Pstream::nProcs()-1)
                {
                    FatalError
                        << "number of entries in roots "
                        << roots.size()
                        << " is not equal to the number of slaves "
                        << Pstream::nProcs()-1
                        << exit(FatalError);
                }

                forAll(roots, i)
                {
                    roots[i].expand();
                }

                // Distribute the master's argument list (with new root)
                bool hadCaseOpt = options_.found("case");
                for
                (
                    int slave = Pstream::firstSlave();
                    slave <= Pstream::lastSlave();
                    slave++
                )
                {
                    options_.set("case", roots[slave-1]/globalCase_);

                    OPstream toSlave(Pstream::scheduled, slave);
                    toSlave << args_ << options_;
                }
                options_.erase("case");

                // Restore [-case dir]
                if (hadCaseOpt)
                {
                    options_.set("case", rootPath_/globalCase_);
                }
            }
            else
            {
                // Possibly going to fewer processors.
                // Check if all procDirs are there.
                if (dictNProcs < Pstream::nProcs())
                {
                    label nProcDirs = 0;
                    while
                    (
                        isDir
                        (
                            rootPath_/globalCase_/"processor"
                          + name(++nProcDirs)
                        )
                    )
                    {}

                    if (nProcDirs != Pstream::nProcs())
                    {
                        FatalError
                            << "number of processor directories = "
                            << nProcDirs
                            << " is not equal to the number of processors = "
                            << Pstream::nProcs()
                            << exit(FatalError);
                    }
                }

                // Distribute the master's argument list (unaltered)
                for
                (
                    int slave = Pstream::firstSlave();
                    slave <= Pstream::lastSlave();
                    slave++
                )
                {
                    OPstream toSlave(Pstream::scheduled, slave);
                    toSlave << args_ << options_;
                }
            }
        }
Exemplo n.º 21
0
Nequeo::Net::Sockets::HostEntry Nequeo::Net::Sockets::DNS::thisHost()
{
	return hostByName(hostName());
}
bool GenericLinuxDeviceConfigurationWizardSetupPage::isComplete() const
{
    return !configurationName().isEmpty() && !hostName().isEmpty() && !userName().isEmpty()
            && (authenticationType() == SshConnectionParameters::AuthenticationByPassword
                || d->ui.privateKeyPathChooser->isValid());
}
Exemplo n.º 23
0
bool TKvsDatabase::open()
{
    return (driver()) ? driver()->open(databaseName(), userName(), password(), hostName(), port(), connectOptions()) : false;
}
Exemplo n.º 24
0
const HostEntry& DNS::thisHost()
{
	return hostByName(hostName());
}
Exemplo n.º 25
0
/**
 * PHP has "EGPCS" processing order of these global variables, and this
 * order is important in preparing $_REQUEST that needs to know which to
 * overwrite what when name happens to be the same.
 */
void HttpProtocol::PrepareSystemVariables(Transport *transport,
                                          const RequestURI &r,
                                          const SourceRootInfo &sri) {
  SystemGlobals *g = (SystemGlobals*)get_global_variables();
  const VirtualHost *vhost = VirtualHost::GetCurrent();

  // reset global symbols to nulls or empty arrays
  pm_php$globals$symbols_php();

  Variant &server = g->GV(_SERVER);
  server.set("REQUEST_START_TIME", time(NULL));

  // $_ENV
  process_env_variables(g->GV(_ENV));
  g->GV(_ENV).set("HPHP", 1);
  g->GV(_ENV).set("HPHP_SERVER", 1);
#ifdef HOTPROFILER
  g->GV(_ENV).set("HPHP_HOTPROFILER", 1);
#endif

  Variant &request = g->GV(_REQUEST);

  // $_GET and $_REQUEST
  if (!r.queryString().empty()) {
    DecodeParameters(g->GV(_GET), r.queryString().data(),
                     r.queryString().size());
    CopyParams(request, g->GV(_GET));
  }

  string contentType = transport->getHeader("Content-Type");
  string contentLength = transport->getHeader("Content-Length");
  // $_POST and $_REQUEST
  if (transport->getMethod() == Transport::POST) {
    bool needDelete = false;
    int size = 0;
    const void *data = transport->getPostData(size);
    if (data && size) {
      ASSERT(((char*)data)[size] == 0); // we need a NULL terminated string
      string boundary;
      int content_length = atoi(contentLength.c_str());
      bool rfc1867Post = IsRfc1867(contentType, boundary);
      string files;
      if (rfc1867Post) {
        if (content_length > VirtualHost::GetMaxPostSize()) {
          // $_POST and $_FILES are empty
          Logger::Warning("POST Content-Length of %d bytes exceeds "
                          "the limit of %lld bytes",
                          content_length, VirtualHost::GetMaxPostSize());
          needDelete = read_all_post_data(transport, data, size);
        } else {
          if (transport->hasMorePostData()) {
            needDelete = true;
            data = Util::buffer_duplicate(data, size);
          }
          DecodeRfc1867(transport, g->GV(_POST), g->GV(_FILES),
                        content_length, data, size, boundary);
        }
        ASSERT(!transport->getFiles(files));
      } else {
        needDelete = read_all_post_data(transport, data, size);

        bool decodeData = strncasecmp(contentType.c_str(),
                                       DEFAULT_POST_CONTENT_TYPE,
                                       sizeof(DEFAULT_POST_CONTENT_TYPE)-1) == 0;
        // Always decode data for now. (macvicar)
        decodeData = true;

        if (decodeData) {
          DecodeParameters(g->GV(_POST), (const char*)data, size, true);
        }

        bool ret = transport->getFiles(files);
        if (ret) {
          g->GV(_FILES) = f_unserialize(files);
        }
      }
      CopyParams(request, g->GV(_POST));
      if (needDelete) {
        if (RuntimeOption::AlwaysPopulateRawPostData) {
          g->GV(HTTP_RAW_POST_DATA) = String((char*)data, size, AttachString);
        } else {
          free((void *)data);
        }
      } else {
        // For literal we disregard RuntimeOption::AlwaysPopulateRawPostData
        g->GV(HTTP_RAW_POST_DATA) = String((char*)data, size, AttachLiteral);
      }
    }
  }

  // $_COOKIE
  string cookie_data = transport->getHeader("Cookie");
  if (!cookie_data.empty()) {
    StringBuffer sb;
    sb.append(cookie_data);
    DecodeCookies(g->GV(_COOKIE), (char*)sb.data());
    CopyParams(request, g->GV(_COOKIE));
  }

  // $_SERVER

  // HTTP_ headers -- we don't exclude headers we handle elsewhere (e.g.,
  // Content-Type, Authorization), since the CGI "spec" merely says the server
  // "may" exclude them; this is not what APE does, but it's harmless.
  HeaderMap headers;
  transport->getHeaders(headers);
  for (HeaderMap::const_iterator iter = headers.begin();
       iter != headers.end(); ++iter) {
    const vector<string> &values = iter->second;
    for (unsigned int i = 0; i < values.size(); i++) {
      String key = "HTTP_";
      key += StringUtil::ToUpper(iter->first).replace("-", "_");
      server.set(key, String(values[i]));
    }
  }
  string host = transport->getHeader("Host");
  String hostName(VirtualHost::GetCurrent()->serverName(host));
  string hostHeader(host);
  if (hostHeader.empty()) {
    server.set("HTTP_HOST", hostName);
    StackTraceNoHeap::AddExtraLogging("Server", hostName.data());
  } else {
    StackTraceNoHeap::AddExtraLogging("Server", hostHeader.c_str());
  }
  if (hostName.empty() || RuntimeOption::ForceServerNameToHeader) {
    hostName = hostHeader;
    // _SERVER['SERVER_NAME'] shouldn't contain the port number
    int colonPos = hostName.find(':');
    if (colonPos != String::npos) {
      hostName = hostName.substr(0, colonPos);
    }
  }

  // APE sets CONTENT_TYPE and CONTENT_LENGTH without HTTP_
  if (!contentType.empty()) {
    server.set("CONTENT_TYPE", String(contentType));
  }
  if (!contentLength.empty()) {
    server.set("CONTENT_LENGTH", String(contentLength));
  }

  // APE processes Authorization: Basic into PHP_AUTH_USER and PHP_AUTH_PW
  string authorization = transport->getHeader("Authorization");
  if (!authorization.empty()) {
    if (strncmp(authorization.c_str(), "Basic ", 6) == 0) {
      // it's safe to pass this as a string literal since authorization
      // outlives decodedAuth; this saves us a superfluous copy.
      String decodedAuth =
        StringUtil::Base64Decode(String(authorization.c_str() + 6));
      int colonPos = decodedAuth.find(':');
      if (colonPos != String::npos) {
        server.set("PHP_AUTH_USER", decodedAuth.substr(0, colonPos));
        server.set("PHP_AUTH_PW", decodedAuth.substr(colonPos + 1));
      }
    }
  }

  server.set("REQUEST_URI", String(transport->getUrl(), CopyString));
  server.set("SCRIPT_URL", r.originalURL());
  String prefix(transport->isSSL() ? "https://" : "http://");
  String port_suffix("");

  // Need to append port
  if (!transport->isSSL() && RuntimeOption::ServerPort != 80) {
    port_suffix = ":" + RuntimeOption::ServerPort;
  }
  server.set("SCRIPT_URI", String(prefix +
                                  (hostHeader.empty() ?
                                    hostName + port_suffix : hostHeader)
                                  + r.originalURL()));

  if (r.rewritten()) {
    // when URL is rewritten, PHP decided to put original URL as SCRIPT_NAME
    String name = r.originalURL();
    if (!r.pathInfo().empty()) {
      int pos = name.find(r.pathInfo());
      if (pos >= 0) {
        name = name.substr(0, pos);
      }
    }
    if (r.defaultDoc()) {
      if (!name.empty() && name[name.length() - 1] != '/') {
        name += "/";
      }
      name += String(RuntimeOption::DefaultDocument);
    }
    server.set("SCRIPT_NAME", name);
  } else {
    server.set("SCRIPT_NAME", r.resolvedURL());
  }
  if (!r.rewritten() && r.pathInfo().empty()) {
    server.set("PHP_SELF", r.resolvedURL());
  } else {
    // when URL is rewritten, or pathinfo is not empty, use original URL
    server.set("PHP_SELF", r.originalURL());
  }

  server.set("SCRIPT_FILENAME", r.absolutePath());
  if (r.pathInfo().empty()) {
    server.set("PATH_TRANSLATED", r.absolutePath());
  } else {
    server.set("PATH_TRANSLATED",
               String(vhost->getDocumentRoot() + r.pathInfo().data()));
    server.set("PATH_INFO", r.pathInfo());
  }

  server.set("argv", r.queryString());
  server.set("argc", 0);
  server.set("GATEWAY_INTERFACE", "CGI/1.1");
  server.set("SERVER_ADDR", String(RuntimeOption::ServerPrimaryIP));
  server.set("SERVER_NAME", hostName);
  server.set("SERVER_PORT", RuntimeOption::ServerPort);
  server.set("SERVER_SOFTWARE", "HPHP");
  server.set("SERVER_PROTOCOL", "HTTP/" + transport->getHTTPVersion());
  server.set("SERVER_ADMIN", "");
  server.set("SERVER_SIGNATURE", "");
  switch (transport->getMethod()) {
  case Transport::GET:  server.set("REQUEST_METHOD", "GET");  break;
  case Transport::HEAD: server.set("REQUEST_METHOD", "HEAD"); break;
  case Transport::POST:
    if (transport->getExtendedMethod() == NULL) {
      server.set("REQUEST_METHOD", "POST");
    } else {
      server.set("REQUEST_METHOD", transport->getExtendedMethod());
    }
    break;
  default:              server.set("REQUEST_METHOD", "");     break;
  }
  server.set("HTTPS", transport->isSSL() ? "1" : "");
  server.set("REQUEST_TIME", time(NULL));
  server.set("QUERY_STRING", r.queryString());

  server.set("REMOTE_ADDR", String(transport->getRemoteHost(), CopyString));
  server.set("REMOTE_HOST", ""); // I don't think we need to nslookup
  server.set("REMOTE_PORT", 0);  // TODO: quite useless

  server.set("DOCUMENT_ROOT", String(vhost->getDocumentRoot()));

  for (map<string, string>::const_iterator iter =
         RuntimeOption::ServerVariables.begin();
       iter != RuntimeOption::ServerVariables.end(); ++iter) {
      server.set(String(iter->first), String(iter->second));
  }
  const map<string, string> &vServerVars = vhost->getServerVars();
  for (map<string, string>::const_iterator iter =
         vServerVars.begin();
       iter != vServerVars.end(); ++iter) {
    server.set(String(iter->first), String(iter->second));
  }
  sri.setServerVariables(server);

  const char *threadType = transport->getThreadTypeName();
  server.set("THREAD_TYPE", threadType);
  StackTraceNoHeap::AddExtraLogging("ThreadType", threadType);

#ifdef TAINTED
  taint_array_variant(g->GV(_GET), "$_GET");
  taint_array_variant(g->GV(_POST), "$_POST");
  taint_array_variant(g->GV(_SERVER), "$_SERVER");
  taint_array_variant(g->GV(_COOKIE), "$_COOKIE");
#endif
}
Exemplo n.º 26
0
CString WebSocketHandshake::clientHandshakeMessage() const
{
    // Keep the following consistent with clientHandshakeRequest().
    StringBuilder builder;

    builder.append("GET ");
    builder.append(resourceName(m_url));
    builder.append(" HTTP/1.1\r\n");

    Vector<String> fields;
    if (m_useHixie76Protocol)
        fields.append("Upgrade: WebSocket");
    else
        fields.append("Upgrade: websocket");
    fields.append("Connection: Upgrade");
    fields.append("Host: " + hostName(m_url, m_secure));
    fields.append("Origin: " + clientOrigin());
    if (!m_clientProtocol.isEmpty())
        fields.append("Sec-WebSocket-Protocol: " + m_clientProtocol);

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

    if (m_useHixie76Protocol) {
        fields.append("Sec-WebSocket-Key1: " + m_hixie76SecWebSocketKey1);
        fields.append("Sec-WebSocket-Key2: " + m_hixie76SecWebSocketKey2);
    } else {
        fields.append("Sec-WebSocket-Key: " + m_secWebSocketKey);
        fields.append("Sec-WebSocket-Version: 13");
        const String extensionValue = m_extensionDispatcher.createHeaderValue();
        if (extensionValue.length())
            fields.append("Sec-WebSocket-Extensions: " + extensionValue);
    }

    // Fields in the handshake are sent by the client in a random order; the
    // order is not meaningful.  Thus, it's ok to send the order we constructed
    // the fields.

    for (size_t i = 0; i < fields.size(); i++) {
        builder.append(fields[i]);
        builder.append("\r\n");
    }

    builder.append("\r\n");

    CString handshakeHeader = builder.toString().utf8();
    // Hybi-10 handshake is complete at this point.
    if (!m_useHixie76Protocol)
        return handshakeHeader;
    // Hixie-76 protocol requires sending eight-byte data (so-called "key3") after the request header fields.
    char* characterBuffer = 0;
    CString msg = CString::newUninitialized(handshakeHeader.length() + sizeof(m_hixie76Key3), characterBuffer);
    memcpy(characterBuffer, handshakeHeader.data(), handshakeHeader.length());
    memcpy(characterBuffer + handshakeHeader.length(), m_hixie76Key3, sizeof(m_hixie76Key3));
    return msg;
}