Ejemplo n.º 1
0
// Read API
int clSocketBase::Read(wxMemoryBuffer& content, long timeout) throw(clSocketException)
{
    content.Clear();

    char buffer[4096];
    timeout = (timeout * 1000); // convert to MS
    while(true && timeout) {
        int rc = SelectReadMS(10);
        timeout -= 10;
        if(rc == kSuccess) {
            memset(buffer, 0x0, sizeof(buffer));
            int bytesRead = recv(m_socket, buffer, sizeof(buffer), 0);
            if(bytesRead < 0) {
                // Error
                throw clSocketException("Read failed: " + error());

            } else if(bytesRead == 0) {
                // connection closed
                return kError;

            } else {
                content.AppendData(buffer, bytesRead);
                continue;
            }
        } else {
            if(content.IsEmpty())
                continue; // keep waiting until time ends
            else
                return kSuccess; // we already read our content
        }
    }
    return kTimeout;
}
Ejemplo n.º 2
0
bool wxRegKey::QueryValue(const wxString& szValue, wxMemoryBuffer& buffer) const
{
  if ( CONST_CAST Open(Read) ) {
    // first get the type and size of the data
    DWORD dwType, dwSize;
    m_dwLastError = RegQueryValueEx((HKEY) m_hKey, RegValueStr(szValue),
                                    RESERVED,
                                    &dwType, NULL, &dwSize);

    if ( m_dwLastError == ERROR_SUCCESS ) {
        if ( dwSize ) {
            const RegBinary pBuf = (RegBinary)buffer.GetWriteBuf(dwSize);
            m_dwLastError = RegQueryValueEx((HKEY) m_hKey,
                                            RegValueStr(szValue),
                                            RESERVED,
                                            &dwType,
                                            pBuf,
                                            &dwSize);
            buffer.UngetWriteBuf(dwSize);
        } else {
            buffer.SetDataLen(0);
        }
    }


    if ( m_dwLastError != ERROR_SUCCESS ) {
      wxLogSysError(m_dwLastError, _("Can't read value of key '%s'"),
                    GetName().c_str());
      return false;
    }
    return true;
  }
  return false;
}
Ejemplo n.º 3
0
void clSFTP::Write(const wxMemoryBuffer& fileContent, const wxString& remotePath) throw(clException)
{
    if(!m_sftp) {
        throw clException("SFTP is not initialized");
    }

    int access_type = O_WRONLY | O_CREAT | O_TRUNC;
    sftp_file file;
    wxString tmpRemoteFile = remotePath;
    tmpRemoteFile << ".codelitesftp";

    file = sftp_open(m_sftp, tmpRemoteFile.mb_str(wxConvUTF8).data(), access_type, 0644);
    if(file == NULL) {
        throw clException(wxString() << _("Can't open file: ") << tmpRemoteFile << ". "
                                     << ssh_get_error(m_ssh->GetSession()),
                          sftp_get_error(m_sftp));
    }

    char* p = (char*)fileContent.GetData();
    const int maxChunkSize = 65536;
    wxInt64 bytesLeft = fileContent.GetDataLen();

    while(bytesLeft > 0) {
        wxInt64 chunkSize = bytesLeft > maxChunkSize ? maxChunkSize : bytesLeft;
        wxInt64 bytesWritten = sftp_write(file, p, chunkSize);
        if(bytesWritten < 0) {
            sftp_close(file);
            throw clException(wxString() << _("Can't write data to file: ") << tmpRemoteFile << ". "
                                         << ssh_get_error(m_ssh->GetSession()),
                              sftp_get_error(m_sftp));
        }
        bytesLeft -= bytesWritten;
        p += bytesWritten;
    }
    sftp_close(file);

    // Unlink the original file if it exists
    bool needUnlink = false;
    {
        // Check if the file exists
        sftp_attributes attr = sftp_stat(m_sftp, remotePath.mb_str(wxConvISO8859_1).data());
        if(attr) {
            needUnlink = true;
            sftp_attributes_free(attr);
        }
    }

    if(needUnlink && sftp_unlink(m_sftp, remotePath.mb_str(wxConvUTF8).data()) < 0) {
        throw clException(wxString() << _("Failed to unlink file: ") << remotePath << ". "
                                     << ssh_get_error(m_ssh->GetSession()),
                          sftp_get_error(m_sftp));
    }

    // Rename the file
    if(sftp_rename(m_sftp, tmpRemoteFile.mb_str(wxConvUTF8).data(), remotePath.mb_str(wxConvUTF8).data()) < 0) {
        throw clException(wxString() << _("Failed to rename file: ") << tmpRemoteFile << " -> " << remotePath << ". "
                                     << ssh_get_error(m_ssh->GetSession()),
                          sftp_get_error(m_sftp));
    }
}
Ejemplo n.º 4
0
bool 
hoxChesscapePlayer::_ParseIncomingCommand( const wxMemoryBuffer& data,
										   wxString&       command,
										   wxString&       paramsStr ) const
{
    /* TODO: Force to convert the buffer to a string. */

    const wxString contentStr =
        wxString::FromUTF8( (const char*) data.GetData(), data.GetDataLen() );
    if ( data.GetDataLen() > 0 && contentStr.empty() ) // failed?
    {
        wxLogDebug("%s: *WARN* Fail to convert [%d] data to string.", 
            __FUNCTION__, data.GetDataLen());
        return false;
    }

	/* CHECK: The first character must be 0x10 */
	if ( contentStr.empty() || contentStr[0] != 0x10 )
	{
		wxLogDebug("%s: *WARN* Invalid command = [%s].", __FUNCTION__, contentStr.c_str());
		return false;
	}

	/* Chop off the 1st character */
	const wxString actualContent = contentStr.Mid(1);

	/* Extract the command and its parameters-string */
	command = actualContent.BeforeFirst( '=' );
	paramsStr = actualContent.AfterFirst('=');

	return true;  // success
}
Ejemplo n.º 5
0
void clSocketBase::Send(const wxMemoryBuffer& msg) throw(clSocketException)
{
    if(m_socket == INVALID_SOCKET) {
        throw clSocketException("Invalid socket!");
    }
    char* pdata = (char*)msg.GetData();
    int bytesLeft = msg.GetDataLen();
    while(bytesLeft) {
        if(SelectWriteMS(1000) == kTimeout) continue;
        int bytesSent = ::send(m_socket, (const char*)pdata, bytesLeft, 0);
        if(bytesSent <= 0) throw clSocketException("Send error: " + error());
        pdata += bytesSent;
        bytesLeft -= bytesSent;
    }
}
Ejemplo n.º 6
0
void clSFTP::Read(const wxString& remotePath, wxMemoryBuffer& buffer) throw(clException)
{
    if(!m_sftp) {
        throw clException("SFTP is not initialized");
    }

    sftp_file file = sftp_open(m_sftp, remotePath.mb_str(wxConvUTF8).data(), O_RDONLY, 0);
    if(file == NULL) {
        throw clException(wxString() << _("Failed to open remote file: ") << remotePath << ". "
                                     << ssh_get_error(m_ssh->GetSession()),
                          sftp_get_error(m_sftp));
    }

    SFTPAttribute::Ptr_t fileAttr = Stat(remotePath);
    if(!fileAttr) {
        throw clException(wxString() << _("Could not stat file:") << remotePath << ". "
                                     << ssh_get_error(m_ssh->GetSession()),
                          sftp_get_error(m_sftp));
    }
    wxInt64 fileSize = fileAttr->GetSize();
    if(fileSize == 0) return;

    // Allocate buffer for the file content
    char pBuffer[65536]; // buffer

    // Read the entire file content
    wxInt64 bytesLeft = fileSize;
    wxInt64 bytesRead = 0;
    while(bytesLeft > 0) {
        wxInt64 nbytes = sftp_read(file, pBuffer, sizeof(pBuffer));
        bytesRead += nbytes;
        bytesLeft -= nbytes;
        buffer.AppendData(pBuffer, nbytes);
    }

    if(bytesRead != fileSize) {
        sftp_close(file);
        buffer.Clear();
        throw clException(wxString() << _("Could not read file:") << remotePath << ". "
                                     << ssh_get_error(m_ssh->GetSession()),
                          sftp_get_error(m_sftp));
    }
    sftp_close(file);
}
Ejemplo n.º 7
0
bool wxRegKey::SetValue(const wxString& szValue, const wxMemoryBuffer& buffer)
{
#ifdef __TWIN32__
  wxFAIL_MSG("RegSetValueEx not implemented by TWIN32");
  return false;
#else
  if ( CONST_CAST Open() ) {
    m_dwLastError = RegSetValueEx((HKEY) m_hKey, RegValueStr(szValue),
                                  (DWORD) RESERVED, REG_BINARY,
                                  (RegBinary)buffer.GetData(),buffer.GetDataLen());
    if ( m_dwLastError == ERROR_SUCCESS )
      return true;
  }

  wxLogSysError(m_dwLastError, _("Can't set value of '%s'"),
                GetFullName(this, szValue));
  return false;
#endif
}
Ejemplo n.º 8
0
void Exword::ReadAdmini(wxMemoryBuffer& buffer)
{
    int rsp, length;
    char *data;
    exword_setpath(m_device, (uint8_t*)GetStoragePath().utf8_str().data(), 0);
    for (int i = 0; admini_list[i] != NULL; i++) {
        rsp = exword_get_file(m_device, (char*)admini_list[i], &data, &length);
        if (rsp == EXWORD_SUCCESS && length > 0) {
            buffer.AppendData(data, length);
            free(data);
            break;
        }
        free(data);
    }
}
Ejemplo n.º 9
0
bool Exword::Authenticate(wxString user, wxMemoryBuffer& key)
{
    bool success = false;
    int rsp;
    uint16_t count;
    exword_dirent_t *entries;
    exword_authchallenge_t c;
    exword_authinfo_t ai;
    exword_userid_t u;

    if (!IsConnected())
        return success;

    memcpy(c.challenge, key.GetData(), 20);
    memcpy(ai.blk1, "FFFFFFFFFFFFFFFF", 16);
    strncpy((char*)ai.blk2, user.utf8_str().data(), 24);
    strncpy(u.name, user.utf8_str().data(), 16);
    exword_setpath(m_device, (uint8_t*)"\\_INTERNAL_00", 0);
    rsp = exword_authchallenge(m_device, c);
    if (rsp == EXWORD_SUCCESS) {
        exword_setpath(m_device, (uint8_t*)"", 0);
        exword_list(m_device, &entries, &count);
        for (int i = 0; i < count; i++) {
            if (strcmp((const char*)entries[i].name, "_SD_00") == 0) {
                exword_setpath(m_device, (uint8_t*)"\\_SD_00", 0);
                rsp = exword_authchallenge(m_device, c);
                if (rsp != EXWORD_SUCCESS)
                    exword_authinfo(m_device, &ai);
             }
        }
        exword_free_list(entries);
        exword_userid(m_device, u);
        success = true;
    }
    return success;
}
Ejemplo n.º 10
0
/*!
 The type wxJSONTYPE_MEMORYBUFF is a \b wxJSON extension that is not correctly read by
 other JSON implementations.
 By default, the function writes such a type as an array of INTs as follows:
 \code
   [ 0,32,45,255,6,...]
 \endcode
 If the writer object was constructed using the \c wxJSONWRITER_MEMORYBUFF flag, then
 the output is much more compact and recognized by the \b wxJSON reader as a memory buffer
 type:
 \code
   '00203FFF06..'
 \endcode

*/
int
wxJSONWriter::WriteMemoryBuff( wxOutputStream& os, const wxMemoryBuffer& buff )
{
#define MAX_BYTES_PER_ROW	20
    char str[16];

    // if STYLED and SPLIT_STRING flags are set, the function writes 20 bytes on every row
    // the following is the counter of bytes written.
    // the string is splitted only for the special meory buffer type, not for array of INTs
    int bytesWritten = 0;
    bool splitString = false;
    if ( (m_style & wxJSONWRITER_STYLED) && 
               (m_style & wxJSONWRITER_SPLIT_STRING))   {
        splitString = true;
    }

    size_t buffLen = buff.GetDataLen();
    unsigned char* ptr = (unsigned char*) buff.GetData();
    wxASSERT( ptr );
    char openChar = '\'';
    char closeChar = '\'';
    bool asArray = false;

    if ( (m_style & wxJSONWRITER_MEMORYBUFF ) == 0 )  {
        // if the special flag is not specified, write as an array of INTs
        openChar = '[';
        closeChar = ']';
        asArray = true;
    }
    // write the open character
    os.PutC( openChar );

    for ( size_t i = 0; i < buffLen; i++ )  {
        unsigned char c = *ptr;
        ++ptr;

        if ( asArray )  {
            snprintf( str, 14, "%d", c );
            size_t len = strlen( str );
            wxASSERT( len <= 3 );
            wxASSERT( len >= 1 );
            str[len] = ',';
            // do not write the comma char for the last element
            if ( i < buffLen - 1 )    {
                ++len;
            }
            os.Write( str, len );
            if ( os.GetLastError() != wxSTREAM_NO_ERROR )    {
                return -1;
            }
        }
        else {
            // now convert the byte in two hex digits
            char c1 = c / 16;
            char c2 = c % 16;
            c1 += '0';
            c2 += '0';
            if ( c1 > '9' )  {
                c1 += 7;
            }
            if ( c2 > '9' )  {
                c2 += 7;
            }
            os.PutC( c1 );
            os.PutC( c2 );
            if ( os.GetLastError() != wxSTREAM_NO_ERROR )    {
                return -1;
            }
            if ( splitString )  {
                ++bytesWritten;
            }

            if (( bytesWritten >= MAX_BYTES_PER_ROW ) && ((buffLen - i ) >= 5 ))   {
                // split the string if we wrote 20 bytes, but only is we have to
                // write at least 5 bytes
                os.Write( "\'\n", 2 );
                int lastChar = WriteIndent( os, m_level + 2 );     // write indentation
                os.PutC( '\'' );               // reopen quotes
                if ( lastChar < 0 )  {
                    return lastChar;
                }
                bytesWritten = 0;
            }
        }
    }

    // write the close character
    os.PutC( closeChar );
    return closeChar;
}
Ejemplo n.º 11
0
void ODTExporter::ODTCreateContentFile(wxZipOutputStream &zout, const wxMemoryBuffer &styled_text, int lineCount, int tabWidth)
{
  const char *buffer = reinterpret_cast<char *>(styled_text.GetData());
  const size_t buffer_size = styled_text.GetDataLen();
  int lineno = 1;
  int width = calcWidth(lineCount);

  zout.PutNextEntry(_T("content.xml"));
  zout.Write(ODTContentFileBEG, strlen(ODTContentFileBEG));

  if (buffer_size)
  {
    char current_style = buffer[1];
    string content("<text:h text:style-name=\"Default\">");

    if (lineCount != -1)
    {
      int difWidth = width - calcWidth(lineno);

      if (difWidth > 0)
      {
        content += string("<text:s text:c=\"") + to_string(difWidth) + string("\"/>");
      }

      content += to_string(lineno);
      ++lineno;
      content += "<text:s text:c=\"2\"/>";
    }

    size_t first = 0;

    if (buffer_size > 0 && buffer[0] == ' ')
    {
      content += fix_spaces(buffer, &first, buffer_size, true);
    }

    if (current_style != 0)
    {
      content += string("<text:span text:style-name=\"style") + to_string(current_style) + string("\">");
    }

    int charLinePos = 0;

    for (size_t i = first; i < buffer_size; i += 2, ++charLinePos)
    {
      if (buffer[i + 1] != current_style)
      {
        if (!isspace(buffer[i]))
        {
          if (current_style != 0)
          {
            content += string("</text:span>");
          }

          current_style = buffer[i + 1];

          if (current_style != 0)
          {
            content += string("<text:span text:style-name=\"style") + to_string(current_style) + string("\">");
          }
        }
      }

      switch (buffer[i])
      {
        case '<':
          content += "&lt;";
          break;

        case '>':
          content += "&gt;";
          break;

        case '&':
          content += "&amp;";
          break;

        case '\'':
          content += "&apos;";
          break;

        case '"':
          content += "&quot;";
          break;

        case ' ':
          content += fix_spaces(buffer, &i, buffer_size);
          break;

        case '\t':
          {
            const int extraSpaces = tabWidth - charLinePos % tabWidth;
            size_t dummy = 0;
            const std::string extraSpacesStr(extraSpaces * 2, ' '); // imitates buffer (char + style)
            content += fix_spaces(extraSpacesStr.c_str(), &dummy, extraSpacesStr.size());
            charLinePos += extraSpaces - 1; // account for auto-increment
          }
          break;

        case '\r':
          --charLinePos; // account for auto-increment
          break;

        case '\n':
          if (current_style != 0)
          {
            content += string("</text:span>");
            current_style = 0;
          }

          content += "</text:h>\n";
          content += "<text:h text:style-name=\"Default\">";

          if (lineCount != -1)
          {
            int difWidth = width - calcWidth(lineno);

            if (difWidth > 0)
            {
              content += string("<text:s text:c=\"") + to_string(difWidth) + string("\"/>");
            }

            content += to_string(lineno);
            ++lineno;
            content += "<text:s text:c=\"2\"/>";
          }

          if (i + 2 < buffer_size && buffer[i + 2] == ' ')
          {
            i += 2;
            content += fix_spaces(buffer, &i, buffer_size, true);
          }

          charLinePos = -1; // account for auto-increment
          break;

        default:
          content += buffer[i];
          break;
      }
    }

    if (current_style != 0)
    {
      content += string("</text:span>");
    }

    content += "</text:h>\n";

    zout.Write(content.c_str(), content.size());
  }

  zout.Write(ODTContentFileEND, strlen(ODTContentFileEND));
}
Ejemplo n.º 12
0
bool wxZlibInputStream::SetDictionary(const wxMemoryBuffer &buf)
{
    return SetDictionary((char*)buf.GetData(), buf.GetDataLen());
}
Ejemplo n.º 13
0
Emfout::EMFDataObject::EMFDataObject(wxMemoryBuffer data) : wxCustomDataObject(m_emfFormat)
{
  SetData(data.GetBufSize(), data.GetData());
}
Ejemplo n.º 14
0
void PreparedStatement::SetParamBlob(int nPosition, const wxMemoryBuffer& buffer)
{
  SetParamBlob(nPosition, buffer.GetData(), buffer.GetBufSize());
}
Ejemplo n.º 15
0
WebSocketMessage::WebSocketMessage(const wxMemoryBuffer &buffer)
{
	_type = WebSocketMessage::Binary;

	_content.AppendData(buffer.GetData(), buffer.GetDataLen());
}