tags:

views:

179

answers:

4

I have an application that needs to behave differently if run directly from the linux console. So if a user connects with SSH to run FooBar, or the user walks over to the console and logs in directly to run FooBar, I want it to do something different.

What C API do I need to call to tell the difference between these two scenarios? I was thinking I'd have to look at the "tty/pts" information (such as what I see when I run "ps axf"), but I'm not certain if that is the best solution, nor what API to call to get that information.

Hints appreciated. :)

+3  A: 

Depending on how much you're worried about it being spoofed, an easy check would be for the presence/absence of the SSH_CLIENT and SSH_CONNECTION environment variables, in which case you'd want the getenv function.

developmentalinsanity
A: 

I'd look at environment variables as a reasonable sign of what's going on. I'm not sure what C API you'd want for that, but I'm sure one exists.

For example, both the SSH_CLIENT or SSH_CONNECTION environment variables are set on my machine regardless of the SSH client being used.

It may be worth checking how universal these are based on the SSH server running on the machine.

Darien
Damn, developmentalinsanity beat me to it ;) shouldn't have taken so long writing...
Darien
+2  A: 

Checking the return value of ttyname(3) against your stdin should give you the name of the terminal which is feeding the input of your process.

It will be /dev/console if the program is being run on the console (and doesn't have it's input redirected). You can also check stdout to see if it is connected to /dev/console - see which fits your usage scenario better.

ivans
It isn't /dev/console, but /dev/tty[0-9], while the ssh and gnome-terminal sessions show up with names like /dev/pts/[0-9]+. Combined with isatty(), your hint to use ttyname() works great for what I needed to do.
Stéphane
+2  A: 

ttyname will tell you the name of the terminal connected to a given file descriptor; for example, ttyname(0) will tell you stdin's terminal.

This will of course fail if input or output is redirected.

Barring that, you can check various environment variables (SSH_CONNECTION, SSH_CLIENT, REMOTEHOST, DISPLAY, SESSIONNAME). Wireshark has logic to detect if it's being run remotely so that it doesn't capture network traffic that it generates; you might be interested in the logic that its get_conn_cfilter function uses to implement this.

Josh Kelley
Nice catch in the wireshark sources!
ivans