How to execute net.exe from Windows Runtime in C? - c

To introduce my problem, I'm currently working on a project to remotely shut down stationary PCs via Siemens S7 PLC. Those PCs are used for an experimental manufactoring line for relays at my university. The principle is quiet simple, the PLC sends the IP of a computer via UDP to a special "always on" PC with monitoring functions on which a UDP server listens for packets (this PC starts up together with the manufactoring line; OS is Windows 10; the server is written in C). If it receives an UDP packet, it triggers a net use command followed by a shutdown command to that specific IP. This works just fine, if the server.exe is started manually. The goal is to get the server working when it's automatically started with e.g. the taskplaner. Exactly this is the main issue here, it's not working as background task. It receives the packets (I tested it) but then nothing happens, no computer shuts down. So I guessed it must be the net use or the shutdown command. At first I tried to set up the net use with a system()call:
char command[100] = { 0 };
snprintf(command, sizeof(command), "#NET USE \\\\%s\\IPC$ %s /USER:%s", ip, pw, usr);
system(command);
As this won't work I found following statement for system()on the Windows API reference page:
This API cannot be used in applications that execute in the Windows Runtime.
So I figured I had to find an alternative, which leads me to my next try with the ShellExecute() function. It seemed like there are no problems concerning the execution out of the runtime, cause I could't find any word about it at the reference page. I tried:
char programpath[100] = "C:\\Windows\\System32\\net.exe";
char cmdline[100] = { 0 };
snprintf(cmdline, sizeof(cmdline), "Use \\\\%s\\IPC$ %s /USER:%s", ip, pw, usr);
ShellExecute(NULL, "open", programpath, cmdline, NULL, SW_HIDE);
But nope, won't work either from the background. When I asked my prof about it, he said he is more into Linux, so he could only guess that there might be a problem with the permissions. He meant that my server has possibly no rights to open those two programs, when calling them as background process. But even after a long time of investigating through the internet, I can't find a proper solution which fits to my problem.

Related

Server broadcasts only to first client

I'm trying to broadcast a message from a server to all clients, but only one client receives the message.
I want to run this server and two or more instances of this client (taken from Donahoo, Calvert, "TCP/IP Sockets in C", 1e; I can paste the code into this question on request).
The programs work fine with a single client, but when running two clients only one (the first) ever receives a message, while the second instance just gets stuck (on bind).
I don't know what I'm doing wrong, I'm sure the program is correct so perhaps I'm running it wrong. I start the server as:
$ ./BroadcastSender localhost 1337 hey &
As for the clients, I have tried two variations, the first:
$ ./BroadcastReceiver 1337 & ./BroadcastReceiver 1337 &
In the second variation I have added while (1) {} after close(sock) and then run as:
$ ./BroadcastReceiver 1337 &
$ ./BroadcastReceiver 1337 &
Both variations give the same result, namely that the first client receives the message, the other one doesn't, but instead gets stuck trying to bind.
Am I running the server/clients the wrong way, or is there something missing in the code? I'm new to sockets so I don't really see if there's anything in, say, the server code saying "I'm gonna broadcast to one client only".
Could you give me some pointers in the right direction? There are other questions and answers about broadcasting but I haven't found one that addresses this particular issue. Thank you.
you can't have 2 processes bind on the same port. Not familiar with the broadcaster, but generally you have 2 options - either run the 2 processes on 2 machines on the same network or run the clients on separate ports and have the broadcaster broadcast on several ports
The command line when running 2 processes on 2 machines should be something like:
$ ./BroadcastSender 127.0.255.255 1337 hey &
when 127.0.255.255 is your subnet mask
--- edit(thanks #Jeremy) ---
you can also bind two sockets to the same UDP port using setsockopt
with SO_REUSEADDR/SO_REUSEPORT flags

Get signal level of the connected WiFi network

Using wpa_supplicant 2.4 on ARM Debian.
Is there a way to get signal level, in decibels or percents, of the wireless network I’m currently connected to?
STATUS command only returns the following set of values: bssid, freq, ssid, id, mode, pairwise_cipher, group_cipher, key_mgmt, wpa_state, ip_address, p2p_device_address, address, uuid
I can run SCAN afterwards, wait for results and search by SSID. But that’s slow and error-prone, I'd like to do better.
The driver should already know that information (because connected, and adjusting transmit levels for energy saving), is there a way to just query for that?
This question is not about general computing hardware and software. I'm using wpa_supplicant through a C API defined in wpa_ctrl.h header, interacting with the service through a pair of unix domain sockets (one for commands, another one for unsolicited events).
One reason I don’t like my current SCAN + SCAN_RESULT solution, it doesn’t work for hidden SSID networks. Scan doesn’t find the network, therefore I’m not getting signal level this way. Another issue is minor visual glitch at application startup. My app is launched by systemd, After=multi-user.target. Unless it’s the very first launch, Linux is already connected to Wi-Fi by then. In my app’s GUI (the product will feature a touch screen), I render a phone-like status bar, that includes WiFi signal strength icon. Currently, it initially shows minimal level (I know it's connected because STATUS command shows SSID), only after ~1 second I’m getting CTRL-EVENT-SCAN-RESULTS event from wpa_supplicant, run SCAN_RESULT command and update signal strength to the correct value.
On the API level my code is straightforward. I have two threads for that, both call wpa_ctrl_open, the command thread calls wpa_ctrl_request, the event thread has an endless loop that calls poll passing wpa_ctrl_get_fd() descriptor and POLLIN event mask, followed by wpa_ctrl_pending and wpa_ctrl_recv.
And here's the list of files in /sys/class/net/wlan0:
./mtu
./type
./phys_port_name
./netdev_group
./flags
./power/control
./power/async
./power/runtime_enabled
./power/runtime_active_kids
./power/runtime_active_time
./power/autosuspend_delay_ms
./power/runtime_status
./power/runtime_usage
./power/runtime_suspended_time
./speed
./dormant
./name_assign_type
./proto_down
./addr_assign_type
./phys_switch_id
./dev_id
./duplex
./gro_flush_timeout
./iflink
./phys_port_id
./addr_len
./address
./operstate
./carrier_changes
./broadcast
./queues/rx-0/rps_flow_cnt
./queues/rx-0/rps_cpus
./queues/rx-1/rps_flow_cnt
./queues/rx-1/rps_cpus
./queues/rx-2/rps_flow_cnt
./queues/rx-2/rps_cpus
./queues/rx-3/rps_flow_cnt
./queues/rx-3/rps_cpus
./queues/tx-0/xps_cpus
./queues/tx-0/tx_maxrate
./queues/tx-0/tx_timeout
./queues/tx-0/byte_queue_limits/limit
./queues/tx-0/byte_queue_limits/limit_max
./queues/tx-0/byte_queue_limits/limit_min
./queues/tx-0/byte_queue_limits/hold_time
./queues/tx-0/byte_queue_limits/inflight
./queues/tx-1/xps_cpus
./queues/tx-1/tx_maxrate
./queues/tx-1/tx_timeout
./queues/tx-1/byte_queue_limits/limit
./queues/tx-1/byte_queue_limits/limit_max
./queues/tx-1/byte_queue_limits/limit_min
./queues/tx-1/byte_queue_limits/hold_time
./queues/tx-1/byte_queue_limits/inflight
./queues/tx-2/xps_cpus
./queues/tx-2/tx_maxrate
./queues/tx-2/tx_timeout
./queues/tx-2/byte_queue_limits/limit
./queues/tx-2/byte_queue_limits/limit_max
./queues/tx-2/byte_queue_limits/limit_min
./queues/tx-2/byte_queue_limits/hold_time
./queues/tx-2/byte_queue_limits/inflight
./queues/tx-3/xps_cpus
./queues/tx-3/tx_maxrate
./queues/tx-3/tx_timeout
./queues/tx-3/byte_queue_limits/limit
./queues/tx-3/byte_queue_limits/limit_max
./queues/tx-3/byte_queue_limits/limit_min
./queues/tx-3/byte_queue_limits/hold_time
./queues/tx-3/byte_queue_limits/inflight
./tx_queue_len
./uevent
./statistics/rx_fifo_errors
./statistics/collisions
./statistics/rx_errors
./statistics/rx_compressed
./statistics/rx_dropped
./statistics/tx_packets
./statistics/tx_errors
./statistics/rx_missed_errors
./statistics/rx_over_errors
./statistics/tx_carrier_errors
./statistics/tx_heartbeat_errors
./statistics/rx_crc_errors
./statistics/multicast
./statistics/tx_fifo_errors
./statistics/tx_aborted_errors
./statistics/rx_bytes
./statistics/tx_compressed
./statistics/tx_dropped
./statistics/rx_packets
./statistics/tx_bytes
./statistics/tx_window_errors
./statistics/rx_frame_errors
./statistics/rx_length_errors
./dev_port
./ifalias
./ifindex
./link_mode
./carrier
You can get the signal level of the connected wifi by wpa_supplicant cmd SIGNAL_POLL
The wpa_supplicant would return:
RSSI=-60
LINKSPEED=867
NOISE=9999
FREQUENCY=5745
The value of the RSSI is the signal level.
You can get the signal level of the connected wifi by wpa_supplicant cmd BSS <bssid>.
About the bssid of the connected wifi, you can get from wpa_supplicant cmd STATUS.
https://android.googlesource.com/platform/external/wpa_supplicant_8/+/622b66d6efd0cccfeb8623184fadf2f76e7e8206/wpa_supplicant/ctrl_iface.c#1986
For iw compatible devices:
Following command gives the current station(aka AP) signal strength:
iw dev wlp2s0 station dump -v
If you need C API, just dig the source code of iw.
After a quick glance, the function you need is here
For broadcom devices, try search broadcom wl. It is close source, don't know if C API is provided.

Using DHCP libraries results infinite loop

I have a code that uses DHCP libararies(package : 4.2.6) to get the hardware address of the DHCP client connected to the system. During this process after DHCP objects got initialized, i tried dhcp_connect() as follows which results into an infinte loop.
dhcpctl_initialize ();
status=dhcpctl_connect (&connection, "127.0.0.1", 7911, 0);
When i tried to debug the issue, i found a function "omapi_wait_for_completion"(in ompai/dispatch.c), has a do-while check for waiter object and its status, the object should change its state to ready to come out of the this loop, but this is never happened which results into an infinite loop.
Here i am just copying the loop as a reference.
do {
status = omapi_one_dispatch ((omapi_object_t *)waiter, t);
if (status != ISC_R_SUCCESS)
return status;
} while (!waiter || !waiter -> ready);
NOTE:
There is no issue when i run the binary generated from the code in system command line, but when i trigger the same command through an application we have this issue.
The application that triggers my binary doesn't uses DHCP libraries or files.
Please note that same binary with the same application is working
fine with older DHCP package (3.0.5).
Thanks in advance for your help.

AppHangXProcB1 on our 32 bit application

We have a C program (a client that connects to our server). The program uses Win32 API:s to create controls etc. It is a single-threaded application. Lately the application has started to hang at random in Windows 7.
Thanks to Application Verifier, I could detect problematic APIs and rectified them.
Now there are still some customers reporting a "non-responsive" situation.
A crash dump from their side reveals the following API:
SendMessage(HWND_BROADCAST, WM_DDE_INITIATE, (WPARAM)hClient, MAKELONG(aAppl,aTopic));
Yes its sending a DDE command to WinWord.exe. Task Manager shows Winword in non-responsive state.
Evtx reveals the following:
Fault bucket , type 0
Event Name: AppHangXProcB1
Response: Not available
Cab Id: 0
Problem signature:
P1: OurApplication.exe
P2: 14.14.1.50
P3: 537337f4
P4: b6f1
P5: 32
P6: WINWORD.EXE
P7: 15.0.4615.1000
P8:
P9:
P10:
Attached files:
C:\Users\diane-do\AppData\Local\Temp\WER91C7.tmp.appcompat.txt
C:\Users\diane-do\AppData\Local\Temp\WER958F.tmp.WERInternalMetadata.xml
C:\Users\diane-do\AppData\Local\Temp\WER968B.tmp.xml
C:\Users\diane-do\AppData\Local\Temp\WER969C.tmp.hdmp
C:\Users\diane-do\AppData\Local\Temp\WER9777.tmp.mdmp
These files may be available here:
C:\Users\diane-do\AppData\Local\Microsoft\Windows\WER\ReportQueue\AppHang_OurApplication.exe_e9b582fc22d416b8787c1184f6fe7fa19d63_cab_0fde97a1
Analysis symbol:
Rechecking for solution: 0
Report Id: 9e84daa9-eff8-11e3-a2fb-90b11c841d1a
Report Status: 36
Any help would be appreciated.
Please note the above is Win 7 64-bit, while our application is 32 bit. Don't know what build their Office 2013 is (32 or 64 bit)
I am aware of the following:
- DDE is old technology, but changing it is out of question now.
- For the above case, I cant use SendMessageTimeout APIs as our client has to wait until commands complete.
ONCE AGAIN, The hang (non-responsive state) happens at random, not always at DDE but various instances. While computing something, even while doing a simple operation as below. Customers launch our CHM file from our menu, then Alt+Tab to another application and then Alt+Tab back to our application, our application becomes non-responsive.
P.S: I also didn't find any document online as to how to interpret those evtx application logs , what P1 P2 stand for. What signatures meant or what fault bucket type are, or any meaning of AppHangXProcB1 or AppHangB1 etc. Please pass the link if you have for the same.
sendmessage is a blocking call it will return only after the receiver application processes the message. Here, it got blocked & it as well blocked your application from dispatching the message. Since your application can't process any further window messages, it hanged the GUI.
Check again all the processing done on processing a window message for any blocking calls like waitforsingleobject, recv, connect in it.

libssh2 session cleanup without blocking?

My app uses libssh2 to communicate over SSH, and generally works fine. One problem I have is when the remote host dies unexpectedly -- the remote host in this case is an embedded device that can lose power at any time, so this isn't uncommon.
When that happens, my app detects that the remote computer has stopped responding to pings, and tears down the local end of the SSH connection like this:
void SSHSession :: CleanupSession()
{
if (_uploadFileChannel)
{
libssh2_channel_free(_uploadFileChannel);
_uploadFileChannel = NULL;
}
if (_sendCommandsChannel)
{
libssh2_channel_free(_sendCommandsChannel);
_sendCommandsChannel = NULL;
}
if (_session)
{
libssh2_session_disconnect(_session, "bye bye");
libssh2_session_free(_session);
_session = NULL;
}
}
Pretty straightforward, but the problem is that the libssh2_channel_free() calls can block for a long time waiting for the remote end to respond to the "I'm going away now" message, which it will never do because it's powered off... but in the meantime, my app is frozen (blocked in the cleanup-routine), which isn't good.
Is there any way (short of hacking libssh2) to avoid this? I'd like to just tear down the local SSH data structures, and never block during this tear-down. (I suppose I could simply leak the SSH session memory, or delegate it to a different thread, but those seem like ugly hacks rather than proper solutions)
I'm not experienced with libssh2, but perhaps we can get different behavior out of libssh2 by using libssh2_session_disconnect_ex and a different disconnect reason: SSH_DISCONNECT_CONNECTION_LOST.
libssh2_session_disconnect is equivalent to using libssh2_session_disconnect_ex with the reason SSH_DISCONNECT_BY_APPLICATION. If libssh2 knows that the connection is lost, maybe it won't try to talk to the other side.
http://libssh2.sourceforge.net/doc/#libssh2sessiondisconnectex
http://libssh2.sourceforge.net/doc/#sshdisconnectcodes
Set to non-blocking mode and take the control of reading data from the socket to your hand by setting callback function to read data from the soket using libssh2_session_callback_set with LIBSSH2_CALLBACK_RECV for cbtype
void *libssh2_session_callback_set(LIBSSH2_SESSION *session, int cbtype, void *callback);
If you can't read data from the socket due to error ENOTCONN that means remote end has closed the socket or connection failed, then return -ENOTCONN in your callback function

Resources