Connecting windows from unix

AF_UNIX comes to Windows

December 19th, 2017

Introduction:

Beginning in Insider Build 17063 , you’ll be able to use the unix socket ( AF_UNIX ) address family on Windows to communicate between W in32 processes . Unix sockets allow inter-process communication (IPC) between process es on the same machine.

Overview :

Support for the unix socket has existed both in BSD and Linux for the longest time, but, not on Windows. On Windows, there were some alternatives for local IPC, such as named pipes . But, calling conventions are different between the named pipes and sockets , making writing low-maintenance cross-platform applications difficult. For example, one such place where these two constructs differ (other than the API) is terminating the connection. BSD Socket API provides a bidirectional close semantics using shutdown . There is no direct equivalent of that in named pipes. Such differences make it difficult to port unix socket applications from Linux to Windows and vice versa; up until now!

Build 17063 brings native support for the unix socket to Windows. Starting this build, two Win 32 process es can use the AF_UNIX address family over Winsock API (which is very similar to the BSD socket API) to communicate with each other. Currently, the support only exists for the stream ( SOCK_STREAM ) socket type , which is a connection-oriented protocol for one-to-one communication. Support for the datagram (SOCK_DGRAM) can be considered in future depending on the adoption, feedback and scenario s .

Addressing scheme – sockaddr_un :

The ‘ sockaddr_un ’ structure is used for defining the address of a unix socket. In the Windows implementation of the unix socket, we have kept the name, definition and semantics of the unix socket address the same as that in Linux , to make cross-platform development easier .

There are three different addressing formats for unix sockets. ‘pathname’, ‘abstract’ and ‘unnamed’ sockets. ‘pathname’ sockets are bound to the filesystem , where in the ‘ sun_path ’ member of the struct is used to specify a null-terminated UTF-8 file system path. You can expect the same from the Windows implementation , where ‘ sun_path ’ specifies a Win32 UTF-8 file system path.

The second category is the ‘abstract’ socket address where the first character in ‘ sun_path ’ is a null byte. Windows implementation of AF_UNIX socket can also accept abstract addresses. The one difference noteworthy here is that the Windows unix socket implementation currently does not support the auto bind feature whereby an abstract address is auto-generated by the implementation on behalf of the user.

Lastly, ‘unnamed’ sockets, where the socket is bound to a pathname with no name. This is also supported on Windows unix socket implementation . Although, one of the socket API’s socketpair that generates unnamed sockets, itself is not supported in Winsock 2.0 .

Security:

Unix sockets provide a mechanism for secure communication. C ommunication over unix sockets can be secured by controlling the file (or directory) permissions on the pathname sockets ( or the parent directory ) . For example, the bind socket API creates a ‘socket’ file with the given pathname . The creation of the new socket file will fail if the calling process does not has write permission on the directory where the file is being created. Similarly, for connecting to a stream socket, the connecting process should have write permission on the socket. The same level of security is available and enforced on the Windows unix socket implementation . See the man page on AF_UNIX for more details on the security .

Implementation:

Majority of the functionality for the Windows AF_UNIX is implemented in the Windows kernel in a driver : afunix.sys . The Windows kernel networking stack provides a very pluggable and extensible model, that makes it easy to support new network providers. The socket file itself that is created as part of the bind call is a custom NTFS reparse point .

Unsupported \unavailable :

Summarizing from the above, the following Linux unix socket features are either currently unavailable or unsupported in the Windows unix socket implementation.

  • AF_UNIX datagram (SOCK_DGRAM) or sequence packet (SOCK_SEQPACKET) socket type.
  • Ancillary data: Linux ‘s unix socket implementation supports passing ancillary data such as passing file descriptors ( `SCM_RIGHTS` ) or credentials (‘ SCM_CREDENTIALS` ) over the socket . There is no support for ancillary data in the Windows unix socket implementation .
  • Autobind feature (see the section on ‘ sockaddr_un ’ for details).
  • socketpair : socketpair socket API is not supported in Winsock 2.0.
Читайте также:  Alsa для linux mint

How can I write a Windows AF_UNIX app ?

  1. Download the Windows Insiders SDK f or the Windows build 17061 — available here .
  2. Check whether your Windows build has support for unix socket by running “ scqueryafunix ” from a Windows admin command prompt.
  3. #include afunix.h > in your Windows application and w rite a Windows unix socket winsock application as you would write any other unix socket application, but, using Winsock API ’s .

Note: As mentioned above in the ‘ security’ section , when a socket binds a socket to a valid pathname address, a socket file is created within the filesystem. On Linux, the application is expected to unlink (see the notes section in the man page for AF_UNIX ) before any other socket can be bound to the same address. The same applies to Windows unix sockets , except that, DeleteFile (or any other file delete API) should be used to delete the socket file prior to calling bind with the same path.

What’s next?

We are listening. Please try out the Windows unix socket provider and let us know what works, what doesn’t work, what you like, what you don’t like or what improvements would you like . For now, the best way to provide feedback is either via Feedback Hub under apps -> Hyper-V, the WSL GitHub issue tracker, or as a comment on this blog.

And, if you are wondering, there is already support for unix socket within Windows Subsystem for Linux (WSL), how does that work with the Windows un ix s ocket implementation? Well, currently, it doesn’t, but stay tuned!

Sftp from Unix to Windows [closed]

Is anyone aware of a way of sftp’ing from Unix to Windows

7 Answers 7

You setup a server with, for instance freeSSHd. Then you can use the regular unix client that comes with OpenSSH, which is a bit on the no feature side of the spectrum, or choose among many of the other SFTP supporting unix clients.

If you just want a Windows client, I’d recommend WinSCP.

From a similar question just asked, I saw this mentioned: http://www.freesshd.com. That could allow you to sftp from *nix to Windows.

PSFTP from the PuTTY team works ok for grabbing files while on Windows.

You can install OpenSSH for windows. It is a cygwin thing and is a little bit tricky to set up on windows box, but it worked for me.

Take a look at CompleteFTP, which is an fast, compact SFTP server for all Windows platforms.

You can use OpenSSH on Unix to SFTP to CompleteFTP running on Windows.

Disclosure: I’m one of the developers of CompleteFTP.

Wikipedia has a large list of sftp servers many can run on windows. Some are more difficult to setup and some are non free. I have used openssh under cygwin and freesshd.

If you are looking for a GUI sftp client that works on Linux you probably are looking for FileZilla or gftp-gtk.

Are you looking for a ready SSH server on windows or you are going to create one? If you need to create a server, then take a look at SSHBlackbox package of SecureBlackbox (our product). It provides powerful components to build a full-scale SSH and SFTP server.

UNIX for Advanced & Expert Users

connecting to windows from unix

What do you mean by connect. If you just want the file system of windows to be accessible, you can use the mount, offcourse for that you must have the windows system mounted. You can configure this by fsconf. ( I am assuming you are probably using the linux flavor of unix)

hope this tip helps

btw, I am also Hemant here

hi.
well. i need to trigger some application which resides on a windows machine through unix.

thanx for the reply.

Oh, I remeber seeing such a thread before, where I had written that you can have a server socket listening on windows and the client socket on your unix system. So if your job on unix gets ovre the client socket on unix will notify the server socket on the windows system.
Let me find that thread and post it as a link (doing this for the first time)

Originally posted by linuxpenguin
Oh, I remeber seeing such a thread before, where I had written that you can have a server socket listening on windows and the client socket on your unix system. So if your job on unix gets ovre the client socket on unix will notify the server socket on the windows system.
Let me find that thread and post it as a link (doing this for the first time)

Читайте также:  Геймпад defender scorpion x7 драйвер для windows 10

really greatful to u. for the help.
but it’s just that i hv never been into socket programmin. so if u could throw some more light on it. wud be of great help.
thanx once again.

I dont know how socket programming is done on windows side. On Unix side I can tell you some things, you will have to carry on. You will have to go thru some books for more info

socket is a system call in unix, by which you can open a file descriptor at the system level for reading from it or writing to it. Using this file descriptor, you can communicate to other file descriptors ( as in windows . )
This is all about inter process communications. A process on unix can talk to a process on windows, thru the IPC tools like socket. For unix sockets I can suggest you to have a look at stevens unix programming. Also on the net you can get a lot of sample socket program

Connecting windows from unix

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Asked by:

Question

Our requirement is to export list of local users (username, lastlogon, group memberships) from a list of windows servers.

The powershell script for above is expected to be triggered from unix machine. This is because we are already doing the same for unix servers via a custom application hosted on unix server and this powershell script to export windows local users will be called from the same application.

As of now we have installed Open SSH, Powershell core on unix and jumphost windows machines which will run invoke-command on series of windows servers and export the data to jumphost.

So flow is Unix (powershell core) -> Windows Jumphost (OpenSSH + Powershell core) -> Target windows server

To solve double hop issue we are using ‘runAsCredential’ approach as in https://blogs.msdn.microsoft.com/sergey_babkins_blog/2015/03/18/another-solution-to-multi-hop-powershell-remoting/

Other approaches to double hop does not seem to work if source machine is running powershell core on unix.

So, Is there a better way to implement the requirement?

Порт сокетных приложений из Unix в Windows

Как известно, концепция сокетов была разработана в Беркли, и затем реализована сначала в BSD, затем в Linux и, наконец, с некоторыми изменениями, и в Windows. Таким образом, это делает сетевое программирование на обеих платформах очень сильно похожим и перенос Unix приложения на Win-платформу становится не очень сложным делом.

Эта статья — попытка помочь тем, кто впервые решил осуществить порт сокетного приложения из Unix (Linux, BSD) в Windows. Зачем? Кто-то решает поднять свой уровень кодинга на новую высоту, кому-то это просто интересно, а кто-то ищет новые задачи для решения. Совет: не пытайтесь сразу портировать что-нибудь достаточно большое и сложное, начните с простых утилит вроде traceroute, nslookup и с прочтения этой статьи :-). Базовых знаний приемов сетевого программирования на C++ будет вполне достаточно. Все примеры из статьи компилировались на VC++ 6.0 под Win2k prof. и WinXP prof.

UNIX и Windows по разному обращаются с сокетами: в UNIX сокеты обрабатываются системой точно так же, как дескрипторы файлов integer типа, в то время как Windows это хэндл unsigned типа — SOCKET. В Unix все I/O действия выполняются чтением или записью в соответствующий дескриптор — число (integer) ассоциированное с открытым файлом, сетевым соединением, терминалом и т.п.

В Unix коды ошибок доступны через переменную errno, в Windows нужно использовать функцию WSAGetLastError().

И в Unix и в Windows порт определяется параметром, переданном функции htons(), но в Windows некоторые, наиболее часто используемые порты предопределены в
winsock.h:

IPPORT_ECHO — 7
IPPORT_DISCARD — 9
IPPORT_SYSTAT — 11
IPPORT_DAYTIME — 13
IPPORT_NETSTAT — 15
IPPORT_FTP — 21
IPPORT_TELNET — 23
IPPORT_SMTP — 25
IPPORT_TIMESERVER — 37
IPPORT_NAMESERVER — 42
IPPORT_WHOIS — 43
IPPORT_MTP — 57

Заголовочные файлы
Вот список функций Unix и соответствующих им .h-файлов

socket()
[ #include ]
[ #include ]

bind()
[ #include ]
[ #include ]

connect()
[ #include ]
[ #include ]

listen()
[ #include ]
[ #include ]

Эти два файла к сокетам не относятся, но обычно присутствуют в Unix программах:

Т.е. типичное начало сетевой UNIX программы выглядит так:

#include
#include
#include
#include
#include

При переносе в Windows, все эти строки заменяются на одну:

Объявление winsock.h уже включено в windows.h.

Вторым шагом будет линковка приложению Wsock32.lib (Для VC++: меню Project->Settings, на вкладке Link, дописать wsock32.lib к списку библиотек).

UNIX и Windows имеют ряд общих, выполняющих одинаковые функций
процедур. Это большинство функций работы с TCP/UDP, все функции преобразования + используемые ими структуры. Это, например, функции htons() и inet_addr() и структуры sockaddr и sockaddr_in.

Вот список этих функций:
socket()
bind()
listen()
connect()
accept()
sendto()
recvfrom()
gethostname()

А вот список функций, делающих одно и то же, различающихся только названиями:

Читайте также:  Приложение еда для windows

Unix Windows
close() closesocket()
ioctl() ioctlsocket()
read() recv()
write() send()

Дополнительно к вышесказанному, каждое сокетное приложение Windows должно содержать вызовы функций WSASStartup() и WSACleanup(), которые подготавливают к использованию Winsock и освобождают его, соответственно.

Для начала, перенесем что-нибудь простенькое. Например утилиту, определяющую IP-адрес хоста по его имени. Вот UNIX код:

#include
#include /* Этот файл нужен функции
gethostbyname() */
#include
#include
#include

int main(int argc, char *argv[])
<
struct hostent *he;

if ((he=gethostbyname(argv[1]))==NULL)
<
printf («gethostbyname() error\n»);
exit (-1);
>

printf («Hostname : %s\n»,he->h_name); /* Вывод имени хоста */
printf («IP Address: %s\n»,inet_ntoa(*((struct in_addr *)he->h_addr))); /* И его IP-адреса
*/
>

Попытка скомпилировать этот код без изменений была горячо воспринята VC++ — компилятор ругнулся на отсутствие .h файлов и сообщил, что компилировать программу он не собирается :-). Первым делом удаляем 2-5 строки, заменив их на:

и немного изменим строку 6:

void main(int argc, char **argv)

не забыв прилинковать wsock32.lib к проекту. Теперь программа компилируется без проблем, но при попытке ею воспользоваться выдает лаконичное: «gethostbyname() error». В чем дело? Все просто, не были вызваны WSAStartup() и WSACleanup()! Добавляем вызовы этих функций и код нормально компилируется.

Вот код портированного, работающего Win приложения:

void main(int argc, char **argv)
<
WSADATA wsdata;
WSAStartup(0x0101,&wsdata);
struct hostent *he;

if (argc! = 2)
<
printf(«Usage: %s hostname\n»,argv[0]);
>

if ((he = gethostbyname(argv[1])) == NULL)
<
printf(«gethostbyname() error\n»);
>

printf («Hostname : %s\n»,he->h_name);
printf(«IP Address: %s\n»,inet_ntoa(*((struct in_addr *)he->h_addr)));

Конечно, это — очень простое приложение. Попробуем перенести программу посложнее
— TCP streaming server.

#include
#include
#include
#include

#define PORT 3550 /* Порт, открываемый программой */
#define BACKLOG 2 /* Число соединений */

main()
<
int fd, fd2; /* дескрипторы */
struct sockaddr_in server; /* информация о сервере */
struct sockaddr_in client; /* информация о клиенте */
int sin_size;

if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 )
< /* вызов socket() */
printf («socket() error\n»);
exit (-1);
>

server.sin_family = AF_INET;
server.sin_port = htons (PORT);
server.sin_addr.s_addr = INADDR_ANY;
bzero (&(server.sin_zero),8);

printf («You got a connection from %s\n», inet_ntoa(client.sin_addr) );
send (fd2,»Welcome to my server.\n»,22,0);
close (fd2);
>>

Итак, сначала повторим шаги из предыдущего примера — оставим объявления только windows.h и stdio.h и прилинкуем wsock32.lib. Попытка компиляции приносит две ошибки: одна — по поводу функции bzero(), вторая — по поводу функции
close() — компилятор сообщает, что она — invalid identifier :-). Первая ошибка лечится очень просто — удаляем всю 21-ю строку. Для исправления второй, смотрим в таблицу, приведенную выше и заменяем close() на ее Win-аналог — closesocket(). Добавляем вызовы WSAStartup() и WSACleanup() и voila — программа компилируется без проблем. После запуска программы видим пустую командную строку, все правильно — сервер ждет клиента :-).

Windows код сервера:

#include
#include
#define PORT 3550
#define BACKLOG 2

main()
<
WSADATA wsdata;
WSAStartup(0x0101,&wsdata);

struct sockaddr_in server;
struct sockaddr_in client;
int sin_size;

if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 )
<
printf(«socket() error\n»);
exit(-1);
>

server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = INADDR_ANY;

if (listen (fd,BACKLOG) == -1)
<
printf («listen() error\n»);
exit (-1);
>

while (1)
<
sin_size=sizeof (struct sockaddr_in);

printf («You got a connection from %s\n»,inet_ntoa(client.sin_addr) );
send (fd2,»Welcome to my server.\n»,22,0);
closesocket (fd2);

TCP streaming client

#include
#include
#include
#include
#include /* необходим для struct hostent */

#define PORT 3550 /* Порт, к которому будем коннектиться */
#define MAXDATASIZE 100 /* Макс. размер данных в байтах */

int main (int argc, char *argv[])
<
int fd, numbytes; /* дескрипторы */
char buf[MAXDATASIZE]; /* здесь будем хранить полученный текст */

struct hostent *he;
struct sockaddr_in server;

if ((he=gethostbyname(argv[1]))==NULL)
<
printf(«gethostbyname() error\n»);
exit(-1);
>

if ((fd=socket(AF_INET, SOCK_STREAM, 0))==-1)
<
printf(«socket() error\n»);
exit(-1);
>

server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr = *((struct in_addr *)he->h_addr);
bzero(&(server.sin_zero),8);

if ((numbytes=recv(fd,buf,MAXDATASIZE,0)) == -1)
<
printf(«recv() error\n»);
exit(-1);
>
buf[numbytes]=’\0′;
printf(«Server Message: %s\n»,buf);
close(fd);
>

И, без лишних слов, Windows код — для его получения нужно проделать те же, вышеописанные, шаги.

#define PORT 3550
#define MAXDATASIZE 100

int main(int argc, char *argv[])
<
WSADATA wsdata;
WSAStartup(0x0101,&wsdata);
int fd, numbytes;
char buf[MAXDATASIZE];
struct hostent *he;
struct sockaddr_in server;

if ((he=gethostbyname(argv[1])) == NULL)
<
printf(«gethostbyname() error\n»);
exit(-1);
>

if ((fd=socket(AF_INET, SOCK_STREAM, 0))==-1)
<
printf(«socket() error\n»);
exit(-1);
>

server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr = *((struct in_addr *)he->h_addr);

if ((numbytes=recv(fd,buf,MAXDATASIZE,0)) == -1)
<
printf(«recv() error\n»);
exit(-1);
>

buf[numbytes] = ‘\0’;
printf(«Server Message: %s\n»,buf);
closesocket(fd);
WSACleanup();
return -1;
>

Запустив клиента (при запущенном сервере, естественно) с аргументом localhost (что-то вроде tcp_client.exe localhost) видим приветствие сервера — «Welcome to my server». С чем я тебя и поздравляю
:-).

Вот те шаги, которые нужно делать в первую очередь, при переносе приложений:

1. Заменить объявления заголовочных файлов UNIX на windows.h и прилинковать wsock32.lib
2. Добавить вызовы функций WSAStartup() и WSACleanup()
3. Заменить функции вроде close() и ioctl() на их Windows-аналоги

Можно даже написать небольшую программу делающую это автоматически (например на Perl). Она здорово облегчит процесс порта приложений.

Все примеры из статьи (exe + исходники) можно скачать
здесь.

Оцените статью