Linux & C: Communicating with X server from outside of X? - c

I'm working on a small server program that takes data received from the network and performs various actions. One of these actions is to open a connection with the X server running on the system and simulate key presses. This is fine when my server is started from a terminal inside X, but I want my program to start as a system service with the system boots and then communicate with X when requested by the clients.
The basic problem I have is that a call to XOpenDisplay(NULL) in a process that was not started from inside X fails. As far as I understand, I can't get open an X display from outside of X so the best workaround I can think of is to write a separate program that is started when a user logs in to X that waits for a signal or message from the server and then performs the requested action. It is perfectly okay to assume that the server can send an error back to the client if this helper program isn't running or has failed for some reason.
So question: Is what I described above the best (albeit messy) solution, or is there a better way? Is there, in fact, a way to open an X display from outside of X? Thanks!

Being "inside of X" is just a matter of having the DISPLAY environment variable set. You can do this from anywhere.
If the X server in question is being run for a different user, you may need to also deal with authentication tokens such as Xauthority tickets.
However -- for the use case you describe, I'd strongly recommend running your own X server process, independent of the system's actual display hardware. This could be Xvnc if you want to connect to inspect interactively, or a simple headless implementation, or Xvfb if you need no display buffer at all. This approach will also prevent your software from needing to restart when users log in and out, which would otherwise be the case.

It is possible to connect to an X display from any process running on the machine - you need the DISPLAY variable set to indicate which X session you want to connect to, and may need the correct XAuthority token.
However, this would be considered the "messy" solution for your case, since you'd need to essentially guess the display number and work around the authorization issue. You'd also have to handle the case where the X server hasn't started yet when your daemon starts, or when the X server gets restarted while your daemon is running (the X client library isn't really designed to handle the case of the X server going away and coming back again).
The "clean" solution is actually the one you've suggested as a workaround - a client running within the X session that connects to your daemon over a UNIX domain socket or similar.

Related

VxWorks initiating connect() it fails at startup, but succeeds later

I'm using VxWorks 5.4 and attempting to connect to a server via TCP. A server which I'm going to be sending logs to, but for some reason at boot it fails or takes even up to 6 seconds - and is blocking the continuation of the task that the connection attempt was made in, which obviously is a big no no.
I have checked if the problem is one the server side by making a simple c program in windows that would connect to that server, and it takes no time at all (milliseconds).
I have "solved" the problem by making a task that would attempt "connectwithtineout" every 1-2 seconds and it does work (initiates the connection after around 2 fails in around 20ms), but I don't really like this approach and would have liked to initiate the actual connection when whatever I need that I'm missing is there and up instead of checking if I can connect every time.
After trying to investigate what the issue could have been, eventually the problem was about how a session is being closed between my system and the server.
You see, when you have a client running on some app on your windows/ or whatever other system, when you shut it down, it goes through some processes that close the session properly.
That is not the case in my system where to close it I essentially unplug the wire - thereby not having my system go through a shutdown process that involves properly closing the session.
After the system is up again, the connect function cannot be performed because my system tries to make the same session as the "dead one" which the server thinks is running.
Solving the problem was easy from the server side, just have a keepalive functionality - if your system doesn't respond for a while that you decide, close the session.

How to connect a program running on my computer to an external web server?

Let's say I want to code a very efficient program (in terms of execution time) in C and to display its output on a specific website; it will be executed everytime a client makes a specific request (i.e. clicking on a button). This program will run on my computer, but its output needs to be sent to the server that hosts this website (and the server is only running Apache).
I have read about CGIs, but they are supposed to be outdated and to have very slow time responses, so is there any specific protocol (or anything else) that I should learn for making my aim possible?

Chat server-client in C. Using threads or processes?

First of all, the environment I'm working on is Windows 7 and Visual Studio 2010.
I already wrote a server that uses the select method to retrieve data from more than one client.
Also I wrote a client that connected to the server above, by running (client.exe localhost 4444 Peter). "Peter" is the username that this user wants to use.
Now let's say we have two users connected on the server. Each of them has the ability to run the command /help. This returns some other commands that the user can use. One command of these is /listusr that returns all the users on the server.
One other command is the /talk2 and here is where my problem-question begins. I want to let the user choose to which of the other users want to talk. E.g if you want to talk to Peter, you give /talk2 Peter.
How am I going to start something like this? How will the server send the message from me to Peter (I have to add here that when a new user connects, the server saves his/her username and his/her socket number in a struct)?
Do I need to create new threads for each conversation or new processes? Can someone give me some hint or advice to continue my project? I'm little confused on how to manage at this point.
Neither. Your server should maintain some kind of data structure that matches a user id to a client socket handle. When a request comes in with the /talk2 command, the server should look up the corresponding socket handle for that userid and should simply relay that message using send().
A scalable way would be your sever is just responsible to tell both clients the IP address of the other side, and then Peter and you establish the connection so you can talk.
If you really want to have the sever transfer the conversation, you need to consider the following to gain a better scalability:
Use UDP instead of TCP
Use thread instead of process
Spawning a new process would be an ordeal for the server if the number of users interacting at a time are high. But on the other hand it will be simpler to code.
Threads do provide scalability, but then you must be extra careful in your code not to do anything silly. (For example, sending wrong chats to the wrong guys.)
Use select/poll techniques (I am not sure how they perform in the Windows environment, but it works cool with Linux.)
UDP will reduce transmission time, but I am not too sure if it's a good idea. Since you said you already have a code, it would be great pain to switch to UDP.
Just sending the address of required client is also a feasible idea. It reduces a lot of effort from the server, but now you will require dedicated clients.
Try each of them and check which one works best for you. It's a design problem, so there can't be a hard and fast solution. It will depend on the usage of your application. You may also want to use (may be you are already using) the sendto and recvfrom functions.

How do I detect the presence/absence of internet connection on a machine?

I need to detect the presence/absence of internet connection. More precisely, let us suppose that the application is broken up into 2 parts - A and B.
A is responsible for checking whether or not the system is connected to the internet. If it finds that there is no connection, it starts up part B. And as soon as it detects that there is a network connection, it kills B and continues its own work.
What would be the best way to do the A part of the application? Continual pings sounds hideous. There has to be a better way of doing this (preferably in C).
With sufficient privilege you can test the various network interfaces and examine their state. This would tell you if any of the interfaces was connected to a network and operating. However, this won't tell you if the connection is actually usable, i.e., connected to the internet (or your local net if that's all you need). I don't know of anyway to do that short of actually using it.
Using ICMP (ping) can be useful at a low level, but presumably what you need is a connection to an actual endpoint via TCP/IP to do real work. I would say that you should change the design of your application so that B is responsible for indicating when it is unable to continue due to the absence of resources that it relies on -- network or otherwise. A and B should communicate so that A is aware of the situation and is able to either kill B or respond to B terminating itself and thus continuing its work.
A lot of companies have measures in place to prevent outgoing ICMP requests, TCP connections to ports other than 80/443 for example, or even to prevent you from reaching the internet directly by (transparently) proxying your traffic.
Under an internet connection I would understand any way to contact the outside, be it UDP, TCP or ICMP. Depending on what your application needs to contact the internet for, I would suggest to check over the same protocol, as that is the only thing that matters to your app.
If your application uses HTTP to communicate to an external source, try to connect to a few sites you would suspect to not be blacklisted and that have a reliable uptime. Like google.com, microsoft.com, apple.com, and so on...
Edit:
I am unsure what the specifics are, so let me give you an example with a hypothetical situation.
Application A collects data on the system it is running on and forwards it to a Web Service listening on yourserverhost.yourcompany.com:80
Application B would basically take over the job of the Web Service when it is down and log everything so no data is lost.
When all is well, App A will be sending the data to your web service
Once this connection drops, you immediatly launch App B (the obvious remark here would be, why not keep App B running as a failsafe)
App A connects to App B and forwards what it had been buffering
App A continues to try to reestablish the connection to your Web Service and once it is back up will request App B to stop
If the problem you are facing is nothing like this, please provide a more concrete description of what App A and App B are supposed to be doing. I will be more than happy to help.
In your code, you have to check whether the internet connection exists by using a socket to open a connection to a website.
Firstrun: Ask user to input the network parameters, like proxy settings. Save this info.
Next runs: Use these settings to check for the Internet connection. You may simply do a DNS search.
If results are negative, ask user to check settings.
Check whether the cable is connected , if so ping your internet connection to any host as google.com.
ping google.com

Cleanest way to stop a process on Win32?

While implementing an applicative server and its client-side libraries in C++, I am having trouble finding a clean and reliable way to stop client processes on server shutdown on Windows.
Assuming the server and its clients run under the same user, the requirements are:
the solution should work in the following cases:
clients may each feature either a console or a gui.
user may be unprivileged.
clients may be or become unresponsive (infinite loop, deadlock).
clients may or may not be children of the server (direct or indirect).
unless prevented by a client-side defect, clients shall be allowed the opportunity to exit cleanly (free their ressources, sync some data to disk...) and some reasonable time to do so.
all client return codes shall be made available (if possible) to the server during the shutdown procedure.
server shall wait until all clients are gone.
As of this edit, the majority of the answers below advocate the use of a shared memory (or another IPC mechanism) between the server and its clients to convey shutdown orders and client status. These solutions would work, but require that clients successfully initialize the library.
What I did not say, is that the server is also used to start the clients and in some cases other programs/scripts which don't use the client library at all. A solution that did not rely on a graceful communication between server and clients would be nicer (if possible).
Some time ago, I stumbled upon a C snippet (in the MSDN I believe) that did the following:
start a thread via CreateRemoteThread in the process to shutdown.
had that thread directly call ExitProcess.
Unfortunately now that I'm looking for it, I'm unable to find it and the search results seem to imply that this trick does not work anymore on Vista. Any expert input on this ?
If you use thread, a simple solution is to use a named system event, the thread sleeps on the event waiting for it to be signaled, the control application can signal the event when it wants the client applications to quit.
For the UI application it (the thread) can post a message to the main window, WM_ CLOSE or QUIT I forget which, in the console application it can issue a CTRL-C or if the main console code loops it can check some exit condition set by the thread.
Either way rather than finding the client applications an telling them to quit, use the OS to signal they should quit. The sleeping thread will use virtually no CPU footprint provided it uses WaitForSingleObject to sleep on.
You want some sort of IPC between clients and servers. If all clients were children, I think pipes would have been easiest; since they're not, I guess a server-operated shared-memory segment can be used to register clients, issue the shutdown command, and collect return codes posted there by clients successfully shutting down.
In this shared-memory area, clients put their process IDs, so that the server can forcefully kill any unresponsive clients (modulo server privileges), using TerminateProcess().
If you are willing to go the IPC route, make the normal communication between client and server bi-directional to let the server ask the clients to shut down. Or, failing that, have the clients poll. Or as the last resort, the clients should be instructed to exit when the make a request to server. You can let the library user register an exit callback, but the best way I know of is to simply call "exit" in the client library when the client is told to shut down. If the client gets stuck in shutdown code, the server needs to be able to work around it by ignoring that client's data structures and connection.
Use PostMessage or a named event.
Re: PostMessage -- applications other than GUIs, as well as threads other than the GUI thread, can have message loops and it's very useful for stuff like this. (In fact COM uses message loops under the hood.) I've done it before with ATL but am a little rusty with that.
If you want to be robust to malicious attacks from "bad" processes, include a private key shared by client/server as one of the parameters in the message.
The named event approach is probably simpler; use CreateEvent with a name that is a secret shared by the client/server, and have the appropriate app check the status of the event (e.g. WaitForSingleObject with a timeout of 0) within its main loop to determine whether to shut down.
That's a very general question, and there are some inconsistencies.
While it is a not 100% rule, most console applications run to completion, whereas GUI applications run until the user terminates them (And services run until stopped via the SCM). Hence, it's easier to request a GUI to close. You send them the equivalent of Alt-F4. But for a console program, you have to send them the equivalent of Ctrl-C and hope they handle it. In both cases, you simply wait. If the process sticks around, you then shoot it down (TerminateProcess) and pray that the damage is limited. But your HDD can fill up with temporary files.
GUI application in general do not have exit codes - where would they go? And a console process that is forcefully terminated by definition does not exit, so it has no exit code. So, in a server shutdown scenario, don't expect exit codes.
If you've got a debugger attached, you generally can't shutdown the process from another application. That would make it impossible for debuggers to debug exit code!

Resources