Flash policy request C++ - json

I am writing a socket server which has a Flash client. However, I can't get past the flash policy request.
My code:
if (buf[0] == 60) {
printf("Policy request spotted");
const auto& policy = Server::policy();
send(client, &policy, policy.size() + 1, 0);
close(client);
break;
}
std::string Server::policy(){
char c = 0;
return "<?xml version=\"1.0\"?>\r\n<!DOCTYPE cross-domain-policy SYSTEM \"/xml/dtds/cross-domain-policy.dtd\">\r\n<cross-domain-policy>\r\n<allow-access-from domain=\"*\" to-ports=\"1-31111\" />\r\n</cross-domain-policy>" + c;
}
Doensn't seems to work. What do I need to do to fix it?
Thanks.

I got it fixed by using this:
char policy[] = "<?xml version=\"1.0\"?>\r\n<!DOCTYPE cross-domain-policy SYSTEM \"/xml/dtds/cross-domain-policy.dtd\">\r\n<cross-domain-policy>\r\n<allow-access-from domain=\"*\" to-ports=\"1-31111\" />\r\n</cross-domain-policy>\0";
send(client, &policy, sizeof(policy), 0);
in the if (buf[0] == 60) { statement.

Related

[Qt][QMYSQL] Deployed app - Driver not loaded

First of all, many thanks for those who will take time to help me on this topic. I've searched a lot on many different forums before posting here but it seems I'm missing something.
Well, I'm working on Windows 7 (64 bits) with Qt5.5 / MySQL Server 5.6.
And I use MinGW 5.5.0 32 bits on Qt Creator (auto detected).
It's not a matter of building the drivers, it's done and it works perfectly for the dev.! :-)
I can reach my BD, do any query that I want and retrieve/insert all the data.
I'm facing to a matter of deploying my application on other computers.
I know that I have to put qsqlmysql.dll in a folder "sqldrivers" placed in my app. directory. Such as placing libmysql.dll in this directory too.
So I have something like the following
App directory
App.exe
libmysql.dll
Qt5Core.dll
Qt5Gui
Qt5Sql
Qt5Widget
libwinpthread-1.dll
libstdc++-6.dll
libgcc_s_dw2-1.dll
platforms
qwindow.dll
sqldrivers
qsqlmysql.dll
BUT when I release the application and I try to run it from another computer which I used to develop, I have a "Driver not loaded" error...
As far now, I have really no idea what I've missed...
So please, if anyone could give me some, it would be really really appreciated!
I let you the part of the code which is really useful, just in case...
main.cpp
QApplication a(argc, argv);
Maintenance w;
w.show();
return a.exec();
Maintenance.cpp
void Maintenance::login(){
int db_select = 1;
this->maint_db = Database(db_select);
/* All that follow is linked to the login of user... */
}
Database.cpp
Database::Database(int default_db)
{
this->db = QSqlDatabase::addDatabase("QMYSQL");
switch(default_db){
case 0:
this->db.setHostName("XXX.XX.XXX.XX");
this->db.setDatabaseName("maintenance_db");
this->db.setUserName("USERNAME");
this->db.setPassword("PASSWORD");
this->db.setPort(3306);
break;
// Only to make some trials in local
case 1:
this->db.setHostName("127.0.0.1");
this->db.setDatabaseName("maintenance_db");
this->db.setUserName("USERNAME");
this->db.setPassword("PASSWORD");
break;
}
/* I've added the following code to try to solve the problem
I retrieve that the available drivers are: QMYSQL / QMYSQL3
But all the information about the DB are empty (due to the unloaded driver I assume.)
And the error from *lastError()* is "Driver not loaded"
*/
QString my_drivers;
for(int i = 0; i < QSqlDatabase::drivers().length(); i++){
my_drivers = my_drivers + " / " + QSqlDatabase::drivers().at(i);
}
QString lib_path;
for(int i = 0; i < QApplication::libraryPaths().length(); i++){
lib_path = lib_path + " / " + QApplication::libraryPaths().at(i);
}
QString start = QString::number(QCoreApplication::startingUp());
QMessageBox::information(0, "BDD init",
"Drivers available: " + my_drivers
+ " \nHostname: " + this->db.hostName()
+ "\nDB name: " + this->db.databaseName()
+ "\nUsername: " + this->db.userName()
+ "\nPW: " + this->db.password()
+ "\n\n" + lib_path + "\n" + start
);
if(this->db.isOpen()){
QMessageBox::information(0, "BDD init", "Already open.");
}
else{
if(this->db.open()){
QMessageBox::information(0, "BDD init", "Opened.");
}
else{
QMessageBox::critical(0, "BDD init", "Not opened.\n" + this->db.lastError().text());
}
}
}
There are at least 3 possible solutions:
Find all .dll paths are correct with your favourite process monitor
Make sure all .dll is in the same arch as your .exe, which is x86 (32bit)
Debug with QPluginLoader
Simplest way to create "deploy" folder for you windows Qt5 aplication is using windeployqt tool
Create empty directory, copy your app.exe file and than run windeployqt app.exe
Check out the docs http://doc.qt.io/qt-5/windows-deployment.html#the-windows-deployment-tool

How to send html files with http protocol over tcp in c language?

I 'm writing a HTTP web server that can respond to PUT, GET , ... requests
when GET request is sent from a browser , the browser should receives the related HTML file
I have analyzed the GET request in the Wireshark it sends the whole HTML file of the website
and then the browser requests the rest of the files that are used in the HTML file
My problem is that when I use the send() function and send and HTTP respond to the GET requests the body part of the HTTP message that contains the HTML file is not displayed correctly in the browser when it is read from a HTML file but when I type the HTML file into a string variable and give it to the send() function it works.
here is my code:
char send_buffer[1000];
FILE *sendFile = fopen("foo.txt", "r");
while( !feof(sendFile) )
{
int numread = fread(send_buffer, sizeof(unsigned char), 1000, sendFile);
if( numread < 1 ) break; // EOF or error
char *send_buffer_ptr = send_buffer;
do
{
int numsent = send(connected, send_buffer_ptr, numread, 0);
if( numsent < 1 ) // 0 if disconnected, otherwise error
{
if( numsent < 0 )
{
if( WSAGetLastError() == WSAEWOULDBLOCK )
{
fd_set wfd;
FD_ZERO(&wfd);
FD_SET(connected, &wfd);
timeval tm;
tm.tv_sec = 10;
tm.tv_usec = 0;
if( select(0, NULL, &wfd, NULL, &tm) > 0 )
continue;
}
}
break; // timeout or error
}
send_buffer_ptr += numsent;
numread -= numsent;
}
while( numread > 0 );
}
I have tested the code with the foo file containing the HTTP header and some HTML code as below:
HTTP/1.1 200 OK
Content-length: 60
Content-Type: text/html
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
I have also tries sending the header with a separate send function and the HTML file with another send function right after it.
The Content-Length header in your response is incorrect. The body of your response is over 100 bytes long, not 60 bytes like the header says. (If your file uses CR+LF line endings, it's actually even longer.)
In general, the Content-Length header should be generated by the web server, as it must exactly match the size of the response body. Storing it in the response is far too prone to errors.

Speech API (SAPI) floating point division by zero in C++ Builder on Windows 7

I use the following code for Text-To-Speech application controls for blind persons in C++ Builder (most likely similar example can be used in Delphi). Main form has KeyPreview property checked to enable key F11 preview to start speaking active (focused) control. The code as it is works but there are some problems. This example is in C++ Builder code but from what I've found, Delphi suffers from same problem and the solution I found is the same. If you have Delphi solution, feel free to post it, it is similar anyway.
#include <sapi.h>
#include <WTypes.h>
//---------------------------------------------------------------------------
// Speak text string (synchronous function)
//---------------------------------------------------------------------------
bool SpeakText(UnicodeString Text)
{
ISpVoice* pVoice = NULL;
if (FAILED(::CoInitialize(NULL))) return false;
Word Saved8087CW = Default8087CW; // Disable floating point division by zero exception caused by Speak
Set8087CW(0x133f);
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
if (SUCCEEDED(hr))
{
//pVoice->SpeakCompleteEvent()
//pVoice->SetSyncSpeakTimeout(1000);
hr = pVoice->Speak(WideString(Text).c_bstr(), SPF_DEFAULT, NULL);
pVoice->Release();
pVoice = NULL;
}
Set8087CW(Saved8087CW);
::CoUninitialize();
return true;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormKeyUp(TObject *Sender, WORD &Key, TShiftState Shift)
{
UnicodeString Speaker;
if (Key == VK_F11)
{
if (Screen->ActiveControl->InheritsFrom(__classid(TButton))) { Speaker += "Button, " + static_cast<TButton*>(Screen->ActiveControl)->Caption + "."; }
else if (Screen->ActiveControl->InheritsFrom(__classid(TEdit))) { Speaker += "Edit box, " + static_cast<TEdit*>(Screen->ActiveControl)->Text + "."; }
}
if (Speaker != "") SpeakText(Speaker);
}
//---------------------------------------------------------------------------
Problems:
pVoice->Speak causes Floating point division by zero if I don't override the exception using the Set8087CW function. This happens only on Windows 7 (possibly Vista and Windows 8 too) but not on Windows XP in the same program (compiled exe). Is there a solution without using Set8087CW? Removing these lines will cause the problem and exception. I have BCB2010.
Function is synchronous and won't shut up or return control to program until it finishes reading text. This is a problem for longer text. It also blocks program events. Is there a way to make it asynchronous or introduce an event to periodically check for F11 key status and if F11 is pressed again it stops reading and uninitializes object? For example poll every 300 ms (or after each word etc.) for key-press F11 and if pressed, stop speaking? Or run it threaded?
Does SAPI has memory leaks as some write on various sites?
Can above code use OleCheck instead of CoCreateInstance and CoUninitialize?
UPDATE for those looking for solution as suggested by Remy Lebeau:
SavedCW = Get8087CW();
Set8087CW(SavedCW | 0x4);
hr = pVoice->Speak(WideString(Text).c_bstr(), SPF_DEFAULT | SPF_ASYNC, NULL);
pVoice->WaitUntilDone(-1); // Waits until text is done... if F11 is pressed simply go out of scope and speech will stop
Set8087CW(SavedCW);
Also found detailed example in CodeRage 4 session: http://cc.embarcadero.com/item/27264
The error does occur in Vista as well. Masking floating point exceptions is the only solution.
To make Speak() run asynchronously, you need to include the SPF_ASYNC flag when calling it. If you need to detect when asynchronous speaking is finished, you can use ISpVoice::WaitUntilDone(), or call ISpVoice::SpeakCompleteEvent() and pass the returned HANDLE to one of the WaitFor...() family of functions, like WaitForSingleObject().
What kind of leaks do other sites talk about?
Not instead of, no. OleCheck() merely checks the value of an HRESULT value and throws an exception if it is an error value. You still have to call COM functions that return the actual HRESULT values in the first place. If anything, OleCheck() would be a replacement for SUCCEEDED() instead.
For what you are attempting, I would suggest the following approach instead:
struct s8087CW
{
Word Saved8087CW;
s8087CW(Word NewCW)
{
Saved8087CW = Default8087CW;
Set8087CW(NewCW);
// alternatively, the VCL documentation says to use SetExceptionMask() instead of Set8087CW() directly...
}
~s8087CW()
{
Set8087CW(Saved8087CW);
}
};
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent *Owner)
: TForm(Owner)
{
::CoInitialize(NULL);
}
//---------------------------------------------------------------------------
__fastcall TForm1::~TForm1()
{
if (pVoice) pVoice->Release();
::CoUninitialize();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormKeyUp(TObject *Sender, WORD &Key, TShiftState Shift)
{
if (Key == VK_F11)
{
TWinControl *Ctrl = Screen->ActiveControl;
if (Ctrl)
{
TButton *btn;
TEdit *edit;
if ((btn = dynamic_cast<TButton*>(Ctrl)) != NULL)
SpeakText("Button, " + btn->Caption);
else if ((edit = dynamic_cast<TEdit*>(Ctrl)) != NULL)
SpeakText("Edit box, " + edit->Text);
}
}
}
//---------------------------------------------------------------------------
ISpVoice* pVoice = NULL;
bool __fastcall TForm1::SpeakText(const String &Text)
{
s8087CW cw(0x133f);
if (!pVoice)
{
if (FAILED(CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice)))
return false;
}
SPVOICESTATUS stat;
pVoice->GetStatus(&stat, NULL);
while (stat.dwRunningState == SPRS_IS_SPEAKING)
{
ULONG skipped;
pVoice->Skip(L"SENTENCE", 1000, &skipped);
pVoice->GetStatus(&stat, NULL);
}
return SUCCEEDED(pVoice->Speak(WideString(Text).c_bstr(), SPF_ASYNC, NULL));
}

create cuda context manager failed

I'm implementing fluid simulator using PhysiX. Unfortunately sth is wrong with cuda context manager and I have a problem with recognizing what it is. I have an init method which looks like this:
void InitializePhysX() {
bool recordMemoryAllocations = true;
const bool useCustomTrackingAllocator = true;
PxAllocatorCallback* allocator = &gDefaultAllocatorCallback;
PxErrorCallback* error = &gDefaultErrorCallback;
PxFoundation* mFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, *allocator, *error);
if(!mFoundation)
printf("PxCreateFoundation failed!\n");
PxProfileZoneManager* mProfileZoneManager = &PxProfileZoneManager::createProfileZoneManager(mFoundation);
if(!mProfileZoneManager)
printf("PxProfileZoneManager::createProfileZoneManager failed!\n");
#ifdef PX_WINDOWS
pxtask::CudaContextManagerDesc cudaContextManagerDesc;
pxtask::CudaContextManager* mCudaContextManager = pxtask::createCudaContextManager(*mFoundation, cudaContextManagerDesc, mProfileZoneManager);
if( mCudaContextManager ){
if( !mCudaContextManager->contextIsValid() ){
mCudaContextManager->release();
mCudaContextManager = NULL;
printf("invalid context\n");
}
} else {
printf("create cuda context manager failed\n");
}
#endif
mPhysX = PxCreatePhysics(PX_PHYSICS_VERSION, *mFoundation, PxTolerancesScale(), recordMemoryAllocations, mProfileZoneManager);
if(!mPhysX)
printf("PxCreatePhysics failed!\n");
...
}
When I try to run my application it occures that mCudaContextManger is never created properly. "create cuda context manager failed" is being wrote on the console and:
"....\LowLevel\software\src\PxsContext.cpp (1122) : warning : GPU operation faied. No px::CudaContextManager available.
....\SimulationController\src\particles\ScParticleSystemSim.cpp (73) : warning : GPU particle system creation failed. Falling back to CPU implementation."
I have GeForce560Ti with newest driver (error also shows up on GeForce460 on my friend's laptop). Physix is set to use GPU in NVidia Control Panel.
Does anybody know what we made wrong and how to make GPU work? Thanks in advance!
File PhysX3Gpu_x86.dll was missing. I added it and now everything is fine.

How to encode a JSON object before using it by borswe URL testing

http://localhost/catalog/{"request": "catalog","user_id": "test#gmail.com","purchased": "2"}
here goes my request URL. I need to test my service with a sample URL typed in browser. But it seems that many of the JSON items do not accepted by the server side. if i enter plane text string server works fine. I tried to encode the URL using http://www.albionresearch.com/misc/urlencode.php, but still the errors are there.
May be this is a problem which belongs to tapestry. Else i would like to get some help.
following request works.
http://localhost/catalog/helloworld
tapestry performs its own encoding of parameters within urls, which there is no replica for on the client side.
see org.apache.tapestry5.internal.services.URLEncoderImpl.encode(String)
the reason 'helloworld' works as expected is that there are no 'special characters' so the escaped value would equal 'helloworld' anyway.
So you will either need to encode your json via java using tapestry's URLEncoder or write a client side replica.
that is, if i understand your question properly.
EDIT i was bored so I wrote the client side replica:
/**
* see org.apache.tapestry5.internal.services.URLEncoderImpl.encode(String)
* correct as at tapestry 5.3.5
*/
function tapestryUrlEncodeParameter(input)
{
var safe = "abcdefghijklmnopqrstuvwxyz"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "01234567890-_.:";
if (input === null)
return "$N";
input = input.toString();
if (input === "")
return "$B";
var output = "";
for (var i = 0; i < input.length; i++)
{
var ch = input.charAt(i);
if (ch === '$')
{
output += "$$";
continue;
}
if (safe.indexOf(ch) != -1)
{
output += ch;
continue;
}
var chHex = ch.charCodeAt(0).toString(16);
while (chHex.length < 4)
chHex = "0" + chHex;
output += "$" + chHex;
}
return output;
}
What do you have server side? Either way you will have to decode your encoded json string on the server side if you want to do it this way.
A better solution might be to use a testing tool of some kind. This could be as simple as a jquery $.get request in a webpage or perhaps you might want to think about a more versatile HTTP client as suggested in this post