spawn async process not working with pkexec - process

My current gksudo command works with Process.spawn_async_with_pipes. however if I switch gksudo with pkexec it does not show the pkexec window and directly completes the command without the prompt and returns nothing.
When I use Process.spawn_command_line_sync with the same pkexec command it brings up the prompt to ask for the password and the commands executes fine and returns result.
My key reason to use pkexec is to use polkit and not prompt the user for subsequent uses of command which requires root permissions.
My method for Process.spawn_async_with_pipes code is shown below.
I need help in how I can make pkexec work as a background process i.e. the prompt should block the gui but once the user provides the password it should return control back to the gui and continue execution in the background. This is exactly what happens with gksudo.
Thanks in advance
This is the async method
public int execute_sync_multiarg_command_pipes(string[] spawn_args) {
debug("Starting to execute async command: "+string.joinv(" ", spawn_args));
spawn_async_with_pipes_output.erase(0, -1); //clear the output buffer
MainLoop loop = new MainLoop ();
try {
string[] spawn_env = Environ.get();
Pid child_pid;
int standard_input;
int standard_output;
int standard_error;
Process.spawn_async_with_pipes ("/",
spawn_args,
spawn_env,
SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
null,
out child_pid,
out standard_input,
out standard_output,
out standard_error);
// capture stdout:
IOChannel output = new IOChannel.unix_new (standard_output);
output.add_watch (IOCondition.IN | IOCondition.HUP, (channel, condition) => {
return process_line (channel, condition, "stdout");
});
// capture stderr:
IOChannel error = new IOChannel.unix_new (standard_error);
error.add_watch (IOCondition.IN | IOCondition.HUP, (channel, condition) => {
return process_line (channel, condition, "stderr");
});
ChildWatch.add (child_pid, (pid, status) => {
// Triggered when the child indicated by child_pid exits
Process.close_pid (pid);
loop.quit ();
});
loop.run ();
} catch(SpawnError e) {
warning("Failure in executing async command ["+string.joinv(" ", spawn_args)+"] : "+e.message);
spawn_async_with_pipes_output.append(e.message);
}
debug("Completed executing async command["+string.joinv(" ", spawn_args)+"]...");
return 0;
}`
This is how it is being called:
execute_sync_multiarg_command_pipes({"pkexec", COMMAND_USING_SUDO[6]});

Spawning an async pkexec command works:
public static int main (string[] args) {
MainLoop loop = new MainLoop ();
try {
string[] spawn_args = {"pkexec", "ls", "-l", "-h"};
string[] spawn_env = Environ.get ();
Pid child_pid;
Process.spawn_async ("/",
spawn_args,
spawn_env,
SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
null,
out child_pid);
ChildWatch.add (child_pid, (pid, status) => {
// Triggered when the child indicated by child_pid exits
Process.close_pid (pid);
loop.quit ();
});
loop.run ();
} catch (SpawnError e) {
stdout.printf ("Error: %s\n", e.message);
}
return 0;
}
The prompt comes up and the resulting file listing is from my "/root" directory like expected.
So the problem must be somewhere else.
It also works with pipes:
private static bool process_line (IOChannel channel, IOCondition condition, string stream_name) {
if (condition == IOCondition.HUP) {
stdout.printf ("%s: The fd has been closed.\n", stream_name);
return false;
}
try {
string line;
channel.read_line (out line, null, null);
stdout.printf ("%s: %s", stream_name, line);
} catch (IOChannelError e) {
stdout.printf ("%s: IOChannelError: %s\n", stream_name, e.message);
return false;
} catch (ConvertError e) {
stdout.printf ("%s: ConvertError: %s\n", stream_name, e.message);
return false;
}
return true;
}
public static int main (string[] args) {
MainLoop loop = new MainLoop ();
try {
string[] spawn_args = {"pkexec", "ls", "-l", "-h"};
string[] spawn_env = Environ.get ();
Pid child_pid;
int standard_input;
int standard_output;
int standard_error;
Process.spawn_async_with_pipes ("/",
spawn_args,
spawn_env,
SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
null,
out child_pid,
out standard_input,
out standard_output,
out standard_error);
// stdout:
IOChannel output = new IOChannel.unix_new (standard_output);
output.add_watch (IOCondition.IN | IOCondition.HUP, (channel, condition) => {
return process_line (channel, condition, "stdout");
});
// stderr:
IOChannel error = new IOChannel.unix_new (standard_error);
error.add_watch (IOCondition.IN | IOCondition.HUP, (channel, condition) => {
return process_line (channel, condition, "stderr");
});
ChildWatch.add (child_pid, (pid, status) => {
// Triggered when the child indicated by child_pid exits
Process.close_pid (pid);
loop.quit ();
});
loop.run ();
} catch (SpawnError e) {
stdout.printf ("Error: %s\n", e.message);
}
return 0;
}
Even this (which now includes your example code fragment) works:
StringBuilder spawn_async_with_pipes_output;
private static bool process_line (IOChannel channel, IOCondition condition, string stream_name) {
if (condition == IOCondition.HUP) {
stdout.printf ("%s: The fd has been closed.\n", stream_name);
return false;
}
try {
string line;
channel.read_line (out line, null, null);
stdout.printf ("%s: %s", stream_name, line);
} catch (IOChannelError e) {
stdout.printf ("%s: IOChannelError: %s\n", stream_name, e.message);
return false;
} catch (ConvertError e) {
stdout.printf ("%s: ConvertError: %s\n", stream_name, e.message);
return false;
}
return true;
}
public int execute_sync_multiarg_command_pipes(string[] spawn_args) {
debug("Starting to execute async command: "+string.joinv(" ", spawn_args));
spawn_async_with_pipes_output.erase(0, -1); //clear the output buffer
MainLoop loop = new MainLoop ();
try {
string[] spawn_env = Environ.get();
Pid child_pid;
int standard_input;
int standard_output;
int standard_error;
Process.spawn_async_with_pipes ("/",
spawn_args,
spawn_env,
SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
null,
out child_pid,
out standard_input,
out standard_output,
out standard_error);
// capture stdout:
IOChannel output = new IOChannel.unix_new (standard_output);
output.add_watch (IOCondition.IN | IOCondition.HUP, (channel, condition) => {
return process_line (channel, condition, "stdout");
});
// capture stderr:
IOChannel error = new IOChannel.unix_new (standard_error);
error.add_watch (IOCondition.IN | IOCondition.HUP, (channel, condition) => {
return process_line (channel, condition, "stderr");
});
ChildWatch.add (child_pid, (pid, status) => {
// Triggered when the child indicated by child_pid exits
Process.close_pid (pid);
loop.quit ();
});
loop.run ();
} catch(SpawnError e) {
warning("Failure in executing async command ["+string.joinv(" ", spawn_args)+"] : "+e.message);
spawn_async_with_pipes_output.append(e.message);
}
debug("Completed executing async command["+string.joinv(" ", spawn_args)+"]...");
return 0;
}
public static int main (string[] args) {
spawn_async_with_pipes_output = new StringBuilder ();
execute_sync_multiarg_command_pipes ({"pkexec", "ls", "-l", "-h"});
return 0;
}

Related

Asio SSL full-duplex socket synchronization problem

My MVCE for SSL relay server:
#pragma once
#include <stdint.h>
#include <iostream>
#include <asio.hpp>
#include <asio/ssl.hpp>
namespace test
{
namespace setup
{
const uint32_t maxMessageSize = 1024 * 1024;
const uint32_t maxSessionsNum = 10;
}
enum class MessageType
{
LOG_ON = 0,
TEXT_MESSAGE = 1
};
class MessageHeader
{
public:
uint32_t messageType;
uint32_t messageLength;
MessageHeader(uint32_t messageType, uint32_t messageLength) : messageType(messageType), messageLength(messageLength) {}
};
class LogOn
{
public:
MessageHeader header;
uint32_t sessionId;
uint32_t isClient0;
LogOn() : header((uint32_t)MessageType::LOG_ON, sizeof(LogOn)) {}
};
class TextMessage
{
public:
MessageHeader header;
uint8_t data[];
TextMessage() : header((uint32_t)MessageType::TEXT_MESSAGE, sizeof(TextMessage)){}
};
class ClientSocket;
class Session
{
public:
ClientSocket* pClient0;
ClientSocket* pClient1;
};
Session* getSession(uint32_t sessionId);
class ClientSocket
{
public:
bool useTLS;
std::shared_ptr<asio::ip::tcp::socket> socket;
std::shared_ptr<asio::ssl::stream<asio::ip::tcp::socket>> socketSSL;
Session* pSession;
bool isClient0;
std::recursive_mutex writeBufferLock;
std::vector<char> readBuffer;
uint32_t readPos;
ClientSocket(asio::ip::tcp::socket& socket) : useTLS(false)
{
this->socket = std::make_shared<asio::ip::tcp::socket>(std::move(socket));
this->readBuffer.resize(setup::maxMessageSize + sizeof(MessageHeader));
this->readPos = 0;
}
ClientSocket(asio::ssl::stream<asio::ip::tcp::socket>& socket) : useTLS(true)
{
this->socketSSL = std::make_shared<asio::ssl::stream<asio::ip::tcp::socket>>(std::move(socket));
this->readBuffer.resize(setup::maxMessageSize + sizeof(MessageHeader));
this->readPos = 0;
}
bool writeSocket(uint8_t* pBuffer, uint32_t bufferSize)
{
try
{
std::unique_lock<std::recursive_mutex>
lock(this->writeBufferLock);
size_t writtenBytes = 0;
if (true == this->useTLS)
{
writtenBytes = asio::write(*this->socketSSL,
asio::buffer(pBuffer, bufferSize));
}
else
{
writtenBytes = asio::write(*this->socket,
asio::buffer(pBuffer, bufferSize));
}
return (writtenBytes == bufferSize);
}
catch (asio::system_error e)
{
std::cout << e.what() << std::endl;
}
catch (std::exception e)
{
std::cout << e.what() << std::endl;
}
catch (...)
{
std::cout << "Some other exception" << std::endl;
}
return false;
}
void asyncReadNextMessage(uint32_t messageSize)
{
auto readMessageLambda = [&](const asio::error_code errorCode, std::size_t length)
{
this->readPos += (uint32_t)length;
if (0 != errorCode.value())
{
//send socket to remove
printf("errorCode= %u, message=%s\n", errorCode.value(), errorCode.message().c_str());
//sendRemoveMeSignal();
return;
}
if ((this->readPos < sizeof(MessageHeader)))
{
asyncReadNextMessage(sizeof(MessageHeader) - this->readPos);
return;
}
MessageHeader* pMessageHeader = (MessageHeader*)this->readBuffer.data();
if (pMessageHeader->messageLength > setup::maxMessageSize)
{
//Message to big - should disconnect ?
this->readPos = 0;
asyncReadNextMessage(sizeof(MessageHeader));
return;
}
if (this->readPos < pMessageHeader->messageLength)
{
asyncReadNextMessage(pMessageHeader->messageLength - this->readPos);
return;
}
MessageType messageType = (MessageType)pMessageHeader->messageType;
switch(messageType)
{
case MessageType::LOG_ON:
{
LogOn* pLogOn = (LogOn*)pMessageHeader;
printf("LOG_ON message sessionId=%u, isClient0=%u\n", pLogOn->sessionId, pLogOn->isClient0);
this->isClient0 = pLogOn->isClient0;
this->pSession = getSession(pLogOn->sessionId);
if (this->isClient0)
this->pSession->pClient0 = this;
else
this->pSession->pClient1 = this;
}
break;
case MessageType::TEXT_MESSAGE:
{
TextMessage* pTextMessage = (TextMessage*)pMessageHeader;
if (nullptr != pSession)
{
if (this->isClient0)
{
if (nullptr != pSession->pClient1)
{
pSession->pClient1->writeSocket((uint8_t*)pTextMessage, pTextMessage->header.messageLength);
}
}
else
{
if (nullptr != pSession->pClient0)
{
pSession->pClient0->writeSocket((uint8_t*)pTextMessage, pTextMessage->header.messageLength);
}
}
}
}
break;
}
this->readPos = 0;
asyncReadNextMessage(sizeof(MessageHeader));
};
if (true == this->useTLS)
{
this->socketSSL->async_read_some(asio::buffer(this->readBuffer.data() + this->readPos, messageSize), readMessageLambda);
}
else
{
this->socket->async_read_some(asio::buffer(this->readBuffer.data() + this->readPos, messageSize), readMessageLambda);
}
}
};
class SSLRelayServer
{
public:
static SSLRelayServer* pSingleton;
asio::io_context ioContext;
asio::ssl::context sslContext;
std::vector<std::thread> workerThreads;
asio::ip::tcp::acceptor* pAcceptor;
asio::ip::tcp::endpoint* pEndpoint;
bool useTLS;
Session* sessions[setup::maxSessionsNum];
SSLRelayServer() : pAcceptor(nullptr), pEndpoint(nullptr), sslContext(asio::ssl::context::tlsv13_server)//sslContext(asio::ssl::context::sslv23)
{
this->useTLS = false;
this->pSingleton = this;
//this->sslContext.set_options(asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2);
this->sslContext.set_password_callback(std::bind(&SSLRelayServer::getPrivateKeyPEMFilePassword, this));
this->sslContext.use_certificate_chain_file("server_cert.pem");
this->sslContext.use_private_key_file("server_private_key.pem",
asio::ssl::context::pem);
}
static SSLRelayServer* getSingleton()
{
return pSingleton;
}
std::string getPrivateKeyPEMFilePassword() const
{
return "";
}
void addClientSocket(asio::ip::tcp::socket& socket)
{
ClientSocket* pClientSocket = new ClientSocket(socket); // use smart pointers
pClientSocket->asyncReadNextMessage(sizeof(MessageHeader));
}
void addSSLClientToken(asio::ssl::stream<asio::ip::tcp::socket>&sslSocket)
{
ClientSocket* pClientSocket = new ClientSocket(sslSocket); // use smart pointers
pClientSocket->asyncReadNextMessage(sizeof(MessageHeader));
}
void handleAccept(asio::ip::tcp::socket& socket, const asio::error_code& errorCode)
{
if (!errorCode)
{
printf("accepted\n");
if (true == socket.is_open())
{
asio::ip::tcp::no_delay no_delay_option(true);
socket.set_option(no_delay_option);
addClientSocket(socket);
}
}
}
void handleAcceptTLS(asio::ip::tcp::socket& socket, const asio::error_code& errorCode)
{
if (!errorCode)
{
printf("accepted\n");
if (true == socket.is_open())
{
asio::ip::tcp::no_delay no_delay_option(true);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(std::move(socket), this->sslContext);
try
{
sslStream.handshake(asio::ssl::stream_base::server);
sslStream.lowest_layer().set_option(no_delay_option);
addSSLClientToken(sslStream);
}
catch (asio::system_error e)
{
std::cout << e.what() << std::endl;
return;
}
catch (std::exception e)
{
std::cout << e.what() << std::endl;
return;
}
catch (...)
{
std::cout << "Other exception" << std::endl;
return;
}
}
}
}
void startAccept()
{
auto acceptHandler = [this](const asio::error_code& errorCode, asio::ip::tcp::socket socket)
{
printf("acceptHandler\n");
handleAccept(socket, errorCode);
this->startAccept();
};
auto tlsAcceptHandler = [this](const asio::error_code& errorCode, asio::ip::tcp::socket socket)
{
printf("tlsAcceptHandler\n");
handleAcceptTLS(socket, errorCode);
this->startAccept();
};
if (true == this->useTLS)
{
this->pAcceptor->async_accept(tlsAcceptHandler);
}
else
{
this->pAcceptor->async_accept(acceptHandler);
}
}
bool run(uint32_t servicePort, uint32_t threadsNum, bool useTLS)
{
this->useTLS = useTLS;
this->pEndpoint = new asio::ip::tcp::endpoint(asio::ip::tcp::v4(), servicePort);
this->pAcceptor = new asio::ip::tcp::acceptor(ioContext, *pEndpoint);
this->pAcceptor->listen();
this->startAccept();
for (uint32_t threadIt = 0; threadIt < threadsNum; ++threadIt)
{
this->workerThreads.emplace_back([&]() {
#ifdef WINDOWS
SetThreadDescription(GetCurrentThread(), L"SSLRelayServer worker thread");
#endif
this->ioContext.run(); }
);
}
return true;
}
Session* getSession(uint32_t sessionId)
{
if (nullptr == this->sessions[sessionId])
{
this->sessions[sessionId] = new Session();
}
return this->sessions[sessionId];
}
};
SSLRelayServer* SSLRelayServer::pSingleton = nullptr;
Session* getSession(uint32_t sessionId)
{
SSLRelayServer* pServer = SSLRelayServer::getSingleton();
Session* pSession = pServer->getSession(sessionId);
return pSession;
}
class Client
{
public:
asio::ssl::context sslContext;
std::shared_ptr<asio::ip::tcp::socket> socket;
std::shared_ptr<asio::ssl::stream<asio::ip::tcp::socket>> socketSSL;
asio::io_context ioContext;
bool useTLS;
bool isClient0;
uint32_t readDataIt;
std::vector<uint8_t> readBuffer;
std::thread listenerThread;
Client() : sslContext(asio::ssl::context::tlsv13_client)//sslContext(asio::ssl::context::sslv23)
{
sslContext.load_verify_file("server_cert.pem");
//sslContext.set_verify_mode(asio::ssl::verify_peer);
using asio::ip::tcp;
using std::placeholders::_1;
using std::placeholders::_2;
sslContext.set_verify_callback(std::bind(&Client::verifyCertificate, this, _1, _2));
this->readBuffer.resize(setup::maxMessageSize);
this->readDataIt = 0;
}
bool verifyCertificate(bool preverified, asio::ssl::verify_context& verifyCtx)
{
return true;
}
void listenerRunner()
{
#ifdef WINDOWS
if (this->isClient0)
{
SetThreadDescription(GetCurrentThread(), L"listenerRunner client0");
}
else
{
SetThreadDescription(GetCurrentThread(), L"listenerRunner client1");
}
#endif
while (1==1)
{
asio::error_code errorCode;
size_t transferred = 0;
if (true == this->useTLS)
{
transferred = this->socketSSL->read_some(asio::buffer(this->readBuffer.data() + this->readDataIt, sizeof(MessageHeader) - this->readDataIt), errorCode);
}
else
{
transferred = this->socket->read_some(asio::buffer(this->readBuffer.data() + this->readDataIt, sizeof(MessageHeader) - this->readDataIt), errorCode);
}
this->readDataIt += transferred;
if (0 != errorCode.value())
{
this->readDataIt = 0;
continue;
}
if (this->readDataIt < sizeof(MessageHeader))
continue;
MessageHeader* pMessageHeader = (MessageHeader*)this->readBuffer.data();
if (pMessageHeader->messageLength > setup::maxMessageSize)
{
exit(1);
}
bool resetSocket = false;
while (pMessageHeader->messageLength > this->readDataIt)
{
printf("readDataIt=%u, threadId=%u\n", this->readDataIt, GetCurrentThreadId());
{
//message not complete
if (true == this->useTLS)
{
transferred = this->socketSSL->read_some(asio::buffer(this->readBuffer.data() + this->readDataIt, pMessageHeader->messageLength - this->readDataIt), errorCode);
}
else
{
transferred = this->socket->read_some(asio::buffer(this->readBuffer.data() + this->readDataIt, pMessageHeader->messageLength - this->readDataIt), errorCode);
}
this->readDataIt += transferred;
}
if (0 != errorCode.value())
{
exit(1);
}
}
MessageType messageType = (MessageType)pMessageHeader->messageType;
switch (messageType)
{
case MessageType::TEXT_MESSAGE:
{
TextMessage* pTextMessage = (TextMessage*)pMessageHeader;
printf("TEXT_MESSAGE: %s\n", pTextMessage->data);
}
break;
}
this->readDataIt = 0;
}
}
void run(uint32_t sessionId, bool isClient0, bool useTLS, uint32_t servicePort)
{
this->useTLS = useTLS;
this->isClient0 = isClient0;
if (useTLS)
{
socketSSL = std::make_shared<asio::ssl::stream<asio::ip::tcp::socket>>(ioContext, sslContext);
}
else
{
socket = std::make_shared<asio::ip::tcp::socket>(ioContext);
}
asio::ip::tcp::resolver resolver(ioContext);
asio::ip::tcp::resolver::results_type endpoints = resolver.resolve(asio::ip::tcp::v4(), "127.0.0.1", std::to_string(servicePort));
asio::ip::tcp::no_delay no_delay_option(true);
if (true == useTLS)
{
asio::ip::tcp::endpoint sslEndpoint = asio::connect(socketSSL->lowest_layer(), endpoints);
socketSSL->handshake(asio::ssl::stream_base::client);
socketSSL->lowest_layer().set_option(no_delay_option);
}
else
{
asio::ip::tcp::endpoint endpoint = asio::connect(*socket, endpoints);
socket->set_option(no_delay_option);
}
this->listenerThread = std::thread(&Client::listenerRunner, this);
LogOn logOn;
logOn.isClient0 = isClient0;
logOn.sessionId = sessionId;
const uint32_t logOnSize = sizeof(logOn);
if (true == useTLS)
{
size_t transferred = asio::write(*socketSSL, asio::buffer(&logOn, sizeof(LogOn)));
}
else
{
size_t transferred = asio::write(*socket, asio::buffer(&logOn, sizeof(LogOn)));
}
uint32_t counter = 0;
while (1 == 1)
{
std::string number = std::to_string(counter);
std::string message;
if (this->isClient0)
{
message = "Client0: " + number;
}
else
{
message = "Client1: " + number;
}
TextMessage textMessage;
textMessage.header.messageLength += message.size() + 1;
if (this->useTLS)
{
size_t transferred = asio::write(*socketSSL, asio::buffer(&textMessage, sizeof(TextMessage)));
transferred = asio::write(*socketSSL, asio::buffer(message.c_str(), message.length() + 1));
}
else
{
size_t transferred = asio::write(*socket, asio::buffer(&textMessage, sizeof(TextMessage)));
transferred = asio::write(*socket, asio::buffer(message.c_str(), message.length() + 1));
}
++counter;
//Sleep(1000);
}
}
};
void clientTest(uint32_t sessionId, bool isClient0, bool useTLS,
uint32_t servicePort)
{
#ifdef WINDOWS
if (isClient0)
{
SetThreadDescription(GetCurrentThread(), L"Client0");
}
else
{
SetThreadDescription(GetCurrentThread(), L"Client1");
}
#endif
Client client;
client.run(sessionId, isClient0, useTLS, servicePort);
while (1 == 1)
{
Sleep(1000);
}
}
void SSLRelayTest()
{
SSLRelayServer relayServer;
const uint32_t threadsNum = 1;
const bool useTLS = true;
const uint32_t servicePort = 777;
relayServer.run(servicePort, threadsNum, useTLS);
Sleep(5000);
std::vector<std::thread> threads;
const uint32_t sessionId = 0;
threads.emplace_back(clientTest, sessionId, true, useTLS, servicePort);
threads.emplace_back(clientTest, sessionId, false, useTLS,servicePort);
for (std::thread& threadIt : threads)
{
threadIt.join();
}
}
}
What this sample does ?
It runs SSL relay server on localhost port 777 which connects two clients and allows exchanging
of text messages between them.
Promblem:
When I run that sample server returns error "errorCode= 167772441, message=decryption failed or bad record mac (SSL routines)" in void "asyncReadNextMessage(uint32_t messageSize)"
I found out this is caused by client which reads and writes to client SSL socket from separate threads (changing variable useTLS to 0 runs it on normal socket which proves that it is SSL socket problem).
Apparently TLS is not full-duplex protocol (I did not know about that). I can't synchronize access to read and write with mutex because when socket enters read state and there is no
incoming message writing to socked will be blocked forever. At this thread Boost ASIO, SSL: How do strands help the implementation?
someone recommended using strands but someone else wrote that asio only synchronizes not concurrent execution of read and write handles which does not fix the problem.
I expect that somehow there is a way to synchronize read and write to SSL socket. I'm 100% sure that problem lies in synchronizing read and writes to socket because when I wrote example with read and write to socket done by one thread it worked. However then client always expects that there is message to read which can block all write if there is not. Can it be solved without using separate sockets for reads and writes ?
Okay I figured it out by writting many diffrent samples of code including SSL sockets.
When asio::io_context is already running you can't simply schedule asio::async_write or asio::async_read from thread which is not
associated with strand connected to that socket.
So when there is:
asio::async_write(*this->socketSSL, asio::buffer(pBuffer, bufferSize), asio::bind_executor(readWriteStrand,writeMessageLambda));
but thread which is executing is not running from readWriteStrand strand then it should be written as:
asio::post(ioContext, asio::bind_executor(readWriteStrand, [&]() {asio::async_read(*this->socketSSL, asio::buffer(readBuffer.data() + this->readDataIt, messageSize), asio::bind_executor(readWriteStrand, readMessageLambda)); }));

jvm condition and locksupport which is faster?

An experimental example of synchronous call is made. Each thread task waits for a task callback with its own value of + 1. The performance difference between condition and locksupport is compared. The result is unexpected. The two times are the same, but the difference on the flame diagram is very big. Does it mean that the JVM has not optimized locksupport
enter image description here
public class LockerTest {
static int max = 100000;
static boolean usePark = true;
static Map<Long, Long> msg = new ConcurrentHashMap<>();
static ExecutorService producer = Executors.newFixedThreadPool(4);
static ExecutorService consumer = Executors.newFixedThreadPool(16);
static AtomicLong record = new AtomicLong(0);
static CountDownLatch latch = new CountDownLatch(max);
static ReentrantLock lock = new ReentrantLock();
static Condition cond = lock.newCondition();
static Map<Long, Thread> parkMap = new ConcurrentHashMap<>();
static AtomicLong cN = new AtomicLong(0);
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
for (int num = 0; num < max; num++) {
consumer.execute(() -> {
long id = record.incrementAndGet();
msg.put(id, -1L);
call(id);
if (usePark) {
Thread thread = Thread.currentThread();
parkMap.put(id, thread);
while (msg.get(id) == -1) {
cN.incrementAndGet();
LockSupport.park(thread);
}
} else {
lock.lock();
try {
while (msg.get(id) == -1) {
cN.incrementAndGet();
cond.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
latch.countDown();
});
}
latch.await();
consumer.shutdown();
producer.shutdown();
System.out.printf("park %s suc %s cost %s cn %s"
, usePark
, msg.entrySet().stream().noneMatch(entry -> entry.getKey() + 1 != entry.getValue())
, System.currentTimeMillis() - start
, cN.get()
);
}
private static void call(long id) {
producer.execute(() -> {
try {
Thread.sleep((id * 13) % 100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (usePark) {
msg.put(id, id + 1);
LockSupport.unpark(parkMap.remove(id));
} else {
lock.lock();
try {
msg.put(id, id + 1);
cond.signalAll();
} finally {
lock.unlock();
}
}
});
}
}

How to save IP camera snapshot in Content folder using EmguCV c#

I'm using EmguCV 3.4. I need to store snapshots from IP camera periodically(5 mins). I try to stored snapshots in the Content folder (ASP.NET MVC). I got access violation exception. Help me.
My Code,
private VideoCapture _capture = null;
private Mat _frame;
public void GetSnapshot(CameraDTO cameraDTO)
{
CvInvoke.UseOpenCL = false;
try
{
_capture = new VideoCapture(cameraDTO.CameraAccessURL);
_capture.ImageGrabbed += ProcessFrame;
if (StartCapture())
{
while (_frame == null)
{
//wait untill camera ready
}
if (_frame != null && _capture != null)
{
Image<Bgr, Byte> imgeOrigenal = _frame.ToImage<Bgr, Byte>();
imgeOrigenal.Save(#ImageSavepath + #"\ImageFromCamera" + cameraDTO.camID + ".jpg");
}
}
}
catch (Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
private bool StartCapture()
{
if (_capture != null)
{
_capture.Start();
return true;
}
return false;
}
private void ProcessFrame(object sender, EventArgs e)
{
try
{
if (_capture != null && _capture.IsOpened && _capture.Ptr != IntPtr.Zero && _frame != null)
{
_frame = new Mat();
_capture.Retrieve(_frame, 0);
}
}
catch (AccessViolationException exv)
{
Console.WriteLine("ERROR: {0}", exv.Message);
return;
}
catch (Exception ex)
{
Console.WriteLine("ERROR: {0}", ex.Message);
return;
}
}
#ImageSavepath = Content folder, randomly generate the issue
The problem is that you use _frame in another thread (cross-thread manipulating). You should save the image inside FrameProcess().
private void FrameProcess(object sender, EventArgs e)
{
try
{
if (_capture != null && _capture.IsOpened && _capture.Ptr != IntPtr.Zero && _frame != null)
{
_frame = new Mat();
_capture.Retrieve(_frame, 0);
Image<Bgr, Byte> imgeOrigenal = _frame.ToImage<Bgr, Byte>();
imgeOrigenal.Save(#ImageSavepath + #"\ImageFromCamera" + cameraDTO.camID + ".jpg");
}
}
catch (AccessViolationException exv)
{
Console.WriteLine("ERROR: {0}", exv.Message);
return;
}
catch (Exception ex)
{
Console.WriteLine("ERROR: {0}", ex.Message);
return;
}
}

GCM IntentService

i used this code for GCM , but when i got pushnotification , i got error like this :
> 08-24 09:28:31.670 25605-5683/icon.apkt E/AndroidRuntime﹕ FATAL
> EXCEPTION: IntentService[GCMIntentService-43597399078-11]
> android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
> at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:5503)
> at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:1099)
> at android.view.ViewGroup.invalidateChildFast(ViewGroup.java:4417)
> at android.view.View.invalidateViewProperty(View.java:11201)
> at android.view.ViewPropertyAnimator$AnimatorEventListener.onAnimationUpdate(ViewPropertyAnimator.java:1047)
> at android.animation.ValueAnimator.animateValue(ValueAnimator.java:1166)
> at android.animation.ValueAnimator.animationFrame(ValueAnimator.java:1102)
> at android.animation.ValueAnimator.doAnimationFrame(ValueAnimator.java:1131)
> at android.animation.ValueAnimator$AnimationHandler.doAnimationFrame(ValueAnimator.java:616)
> at android.animation.ValueAnimator$AnimationHandler.run(ValueAnimator.java:639)
> at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
> at android.view.Choreographer.doCallbacks(Choreographer.java:591)
> at android.view.Choreographer.doFrame(Choreographer.java:560)
> at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
> at android.os.Handler.handleCallback(Handler.java:725)
> at android.os.Handler.dispatchMessage(Handler.java:92)
> at android.os.Looper.loop(Looper.java:137)
> at android.os.HandlerThread.run(HandlerThread.java:60)
Here is my code :
/**
* Method called on device un registred
*/
#Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "GCM Device unregistered");
generateNotification(context, "Device Unregistered", new Intent());
ServerUtilities.unregister(context, registrationId);
}
/**
* Method called on Receiving a new message
*/
#Override
protected void onMessage(final Context context, Intent intent) {
Log.i(TAG, "GCM Received message");
if (intent == null) {
} else {
String message = intent.getExtras().getString("message");
String namaPelanggan = "", alamat = "", telepon = "", noGangguan = "";
// {
// "reportNumber" : "G5313111100001"
// "status" : "Dalam Perjalanan",
// "poskoId" : "538711",
// "poskoName" : "POSKO DEPOK KOTA",
// "reguId" : "6683",
// "reguName" : "rdpk55",
// "idPel" : "525060659230",
// "namaPelanggan" : "SUPRIYADI" ,
// "createBy" : "11387",
// "createName" : "POSKODEPOK",
// "namaPelapor" : ""SAMINAH,
// "alamat" : "KP PANCORAN MAS",
// "telepon" : "021234234",
// "hp" : "081234234234",
// "longitude" : "0",
// "latitude" : "0"
// }
try {
JSONObject json = new JSONObject(message);
namaPelanggan = json.getString("namaPelanggan");
alamat = json.getString("alamat");
telepon = json.getString("telepon");
noGangguan = json.getString("reportNumber");
String total = "Gangguan baru diterima, NoGangguan = " + noGangguan
+ " Pelapor = " + namaPelanggan + ", Lokasi = " + alamat
+ ", Telepon = " + telepon;
// final String nogang = noGangguan;
try {
// GenericMethods.ShowToast(context, total);
User user = new User();
if (user.fromLocal(context)) {
GenericMethods.getGangguanOnline(context, user,
new onFinish() {
#Override
public void complete() {
// DO NOTHING
// Intent intent = null;
//
// Gangguan tugas = GenericMethods
// .getGangguan(nogang);
//
// if (tugas == null) {
// Log.i("RETURN", "NULL");
// return;
// }
//
// Log.i("SELECT", tugas.LASTSTATUS);
// if (tugas.LASTSTATUS
// .equalsIgnoreCase(WSDLConfig.status.status0))
// {
// intent = new Intent(context,
// BerangkatActivity.class);
// Log.d("GCM Open", tugas.LASTSTATUS);
// } else if (tugas.LASTSTATUS
// .equalsIgnoreCase(WSDLConfig.status.status1))
// {
// intent = new Intent(context,
// SebelumActivity.class);
// Log.d("GCM Open", tugas.LASTSTATUS);
// } else if (tugas.LASTSTATUS
// .equalsIgnoreCase(WSDLConfig.status.status2))
// {
// intent = new Intent(context,
// SesudahActivity.class);
// Log.d("GCM Open", tugas.LASTSTATUS);
// } else if (tugas.LASTSTATUS
// .equalsIgnoreCase(WSDLConfig.status.status3))
// {
// intent = new Intent(context,
// SesudahActivity.class);
// Log.d("GCM Open", tugas.LASTSTATUS);
// } else if (tugas.LASTSTATUS
// .equalsIgnoreCase(WSDLConfig.status.status4))
// {
// intent = new Intent(context,
// SelesaiActivity.class);
// Log.d("GCM Open", tugas.LASTSTATUS);
// }
//
// if (intent != null) {
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.putExtra(
// Configuration.put_runworkflowID,
// tugas.REPORTNUMBER);
// startActivity(intent);
// }
// if (GenericMethods.activeActivity != null)
// ((MainActivity) GenericMethods.activeActivity)
// .getDaftarGangguanOffline();
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
DBHelper db = new DBHelper(context);
db.insertGCMList(noGangguan, total);
db.close();
Log.i("GCM","GCM Notif");
generateNotification(getApplicationContext(), total, new Intent(
getApplicationContext(), MainActivity.class));
} catch (JSONException e) {
e.printStackTrace();
}
}
The exception is not about GCM, it is because you try to update your UI in intent service, intent service actually run in a separate thread. Android does not allow update UI in non-main thread.
Try to move your update UI code into main thread, here just an example:
new Handler(getMainLooper()).post(new Runnable() {
#Override
public void run() {
// put your update UI code here.
}
});

TinyOS periodic Bcast AMSend not received

I want to send messages periodically through this program, the messages are broadcasted fine and I get a sendDone message. The problem is that these messages are not received well. I would really appreciate any help to find out where the problem is?
Here is the code(please ignore unused variables as I have cut a lot of the code):
includes lqer;
module lqer_M{
provides {
interface SplitControl;
interface AMSend[am_id_t id];
interface Receive[uint8_t id];
};
uses {
interface SplitControl as AMControl;
interface Timer<TMilli> as LQERTimer;
interface Random;
interface AMPacket;
interface AMSend as SendPacket;
interface Receive as ReceivePacket;
interface PacketAcknowledgements;
interface Packet;
}
}
implementation{
message_t lqer_msg_;
message_t* p_lqer_msg_;
lqer_table l_table[LQER_FT_SIZE];
node_info info;
uint8_t max=0, Pos=0;
message_t* newADV;
bool busy = FALSE;
command error_t SplitControl.start() {
int i,j;
p_lqer_msg_ = &lqer_msg_;
info.hop=1000;
for(i=0; i<16; i++){
info.m[i]=1;
}
for(i = 0; i< LQER_FT_SIZE; i++) {
l_table[i].nid = INVALID_NODE_ID;
l_table[i].hop = 1000;
for (j=0; j<16; j++)
{
l_table[i].m[j]=1;
}
}
call AMControl.start();
return SUCCESS;
}
command error_t SplitControl.stop() {
call AMControl.stop();
return SUCCESS;
}
event void AMControl.startDone( error_t e ) {
if ( e == SUCCESS ) {
call LQERTimer.startPeriodic( LQER_DEFAULT_PERIOD );
signal SplitControl.startDone(e);
} else {
call AMControl.start();
}
}
event void AMControl.stopDone(error_t e){
call LQERTimer.stop();
signal SplitControl.stopDone(e);
}
event void LQERTimer.fired() {
message_t* lqer_adv_msg;
lqer_adv_hdr* new_ADV=(lqer_adv_hdr*)(lqer_adv_msg->data);
am_addr_t me = call AMPacket.address();
if (me==0001){
new_ADV->src = me;
new_ADV->hop = 0;
newADV= (message_t*)(&new_ADV);
dbg("GRAPE_DBG", "%s\t LQER: Sink address: %d\n", sim_time_string(), me);
call PacketAcknowledgements.requestAck(newADV);
call SendPacket.send( AM_BROADCAST_ADDR, newADV, call Packet.payloadLength(newADV) );
}
}
event message_t* ReceivePacket.receive( message_t* p_msg, void* payload, uint8_t len ) {
lqer_adv_hdr* lqer_hdr = (lqer_adv_hdr*)(p_msg->data);
lqer_adv_hdr* msg_lqer_hdr =(lqer_adv_hdr*)(p_lqer_msg_->data);
uint8_t i;
lqer_adv_hdr* new_ADV =(lqer_adv_hdr*)(p_lqer_msg_->data);
dbg("GRAPE_DBG", "%s\t ADV: RecievedADV dst: \n", sim_time_string());
msg_lqer_hdr->src = lqer_hdr->src;
msg_lqer_hdr->hop = lqer_hdr->hop;
new_ADV->src = msg_lqer_hdr->src;
new_ADV->hop = msg_lqer_hdr->hop;
newADV= (message_t*)(&new_ADV);
call PacketAcknowledgements.requestAck( newADV );
call SendPacket.send( AM_BROADCAST_ADDR, newADV, call Packet.payloadLength(newADV) );
return p_msg;
}
command error_t AMSend.cancel[am_id_t id](message_t* msg) {
return call SendPacket.cancel(msg);
}
command uint8_t AMSend.maxPayloadLength[am_id_t id]() {
return call Packet.maxPayloadLength();
}
command void* AMSend.getPayload[am_id_t id](message_t* m, uint8_t len) {
return call Packet.getPayload(m, 0);
}
default event void AMSend.sendDone[uint8_t id](message_t* msg, error_t err) {
return;
}
default event message_t* Receive.receive[am_id_t id](message_t* msg, void* payload, uint8_t len) {
return msg;
}
command error_t AMSend.send[am_id_t id](am_addr_t addr, message_t* msg, uint8_t len)
{
call SendPacket.send( TOS_BCAST_ADDR , msg, call Packet.payloadLength(msg) );
return SUCCESS;
}
event void SendPacket.sendDone(message_t* p_msg, error_t e) {
dbg("GRAPE_DBG", "%s\t ADV: SendDone\n", sim_time_string());
if( p_msg== newADV)
busy=FALSE;
}
}
You should look at what is the error value in the sendDone event. It is possible that send returns success, but the sending fail after that, and the error code is returned in the sendDone. These error includes ENOACK, ENOMEM, etc.
Also, check your destination address and the AM address of the receiver.