XEmacs 21.2-b1
[chise/xemacs-chise.git.1] / src / process-nt.c
1 /* Asynchronous subprocess implemenation for Win32
2    Copyright (C) 1985, 1986, 1987, 1988, 1992, 1993, 1994, 1995
3    Free Software Foundation, Inc.
4    Copyright (C) 1995 Sun Microsystems, Inc.
5    Copyright (C) 1995, 1996 Ben Wing.
6
7 This file is part of XEmacs.
8
9 XEmacs is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
12 later version.
13
14 XEmacs is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with XEmacs; see the file COPYING.  If not, write to
21 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 Boston, MA 02111-1307, USA.  */
23
24 /* Written by Kirill M. Katsnelson <kkm@kis.ru>, April 1998 */
25
26 #include <config.h>
27 #include "lisp.h"
28
29 #include "hash.h"
30 #include "lstream.h"
31 #include "process.h"
32 #include "procimpl.h"
33 #include "sysdep.h"
34
35 #include <windows.h>
36 #include <shellapi.h>
37 #include <signal.h>
38 #ifdef HAVE_SOCKETS
39 #include <winsock.h>
40 #endif
41
42 /* Bound by winnt.el */
43 Lisp_Object Qnt_quote_process_args;
44
45 /* Implemenation-specific data. Pointed to by Lisp_Process->process_data */
46 struct nt_process_data
47 {
48   HANDLE h_process;
49 };
50
51 #define NT_DATA(p) ((struct nt_process_data*)((p)->process_data))
52 \f
53 /*-----------------------------------------------------------------------*/
54 /* Process helpers                                                       */
55 /*-----------------------------------------------------------------------*/
56
57 /* This one breaks process abstraction. Prototype is in console-msw.h,
58    used by select_process method in event-msw.c */
59 HANDLE
60 get_nt_process_handle (struct Lisp_Process *p)
61 {
62   return (NT_DATA (p)->h_process);
63 }
64 \f
65 /*-----------------------------------------------------------------------*/
66 /* Running remote threads. See Microsoft Systems Journal 1994 Number 5   */
67 /* Jeffrey Richter, Load Your 32-bit DLL into Another Process's Address..*/
68 /*-----------------------------------------------------------------------*/
69
70 typedef struct
71 {
72   HANDLE h_process;
73   HANDLE h_thread;
74   LPVOID address;
75 } process_memory;
76
77 /*
78  * Allocate SIZE bytes in H_PROCESS address space. Fill in PMC used
79  * further by other routines. Return nonzero if successful.
80  *
81  * The memory in other process is allocated by creating a suspended
82  * thread. Initial stack of that thread is used as the memory
83  * block. The thread entry point is the routine ExitThread in
84  * kernel32.dll, so the allocated memory is freed just by resuming the 
85  * thread, which immediately terminates after that.
86  */
87
88 static int 
89 alloc_process_memory (HANDLE h_process, size_t size,
90                       process_memory* pmc)
91 {
92   LPTHREAD_START_ROUTINE adr_ExitThread =
93     (LPTHREAD_START_ROUTINE)
94     GetProcAddress (GetModuleHandle ("kernel32"), "ExitThread");
95   DWORD dw_unused;
96   CONTEXT context;
97   MEMORY_BASIC_INFORMATION mbi;
98
99   pmc->h_process = h_process;
100   pmc->h_thread = CreateRemoteThread (h_process, NULL, size,
101                                      adr_ExitThread, NULL,
102                                      CREATE_SUSPENDED, &dw_unused);
103   if (pmc->h_thread == NULL)
104     return 0;
105
106   /* Get context, for thread's stack pointer */
107   context.ContextFlags = CONTEXT_CONTROL;
108   if (!GetThreadContext (pmc->h_thread, &context))
109     goto failure;
110
111   /* Determine base address of the committed range */
112   if (sizeof(mbi) != VirtualQueryEx (h_process,
113 #if defined (_X86_)
114                                      (LPDWORD)context.Esp - 1,
115 #elif defined (_ALPHA_)
116                                      (LPDWORD)context.IntSp - 1,
117 #else
118 #error Unknown processor architecture
119 #endif
120                                      &mbi, sizeof(mbi)))
121     goto failure;
122
123   /* Change the page protection of the allocated memory to executable,
124      read, and write. */
125   if (!VirtualProtectEx (h_process, mbi.BaseAddress, size,
126                          PAGE_EXECUTE_READWRITE, &dw_unused))
127     goto failure;
128
129   pmc->address = mbi.BaseAddress;
130   return 1;
131
132  failure:
133   ResumeThread (pmc->h_thread);
134   pmc->address = 0;
135   return 0;
136 }
137
138 static void
139 free_process_memory (process_memory* pmc)
140 {
141   ResumeThread (pmc->h_thread);
142 }
143
144 /*
145  * Run ROUTINE in the context of process determined by H_PROCESS. The
146  * routine is passed the address of DATA as parameter. CODE_END is the 
147  * address immediately after ROUTINE's code. DATA_SIZE is the size of
148  * DATA structure.
149  *
150  * Note that the code must be positionally independent, and compiled
151  * without stack checks (they cause implicit calls into CRT so will
152  * fail). DATA should not refer any data in calling process, as both
153  * routine and its data are copied into remote process. Size of data
154  * and code together should not exceed one page (4K on x86 systems).
155  *
156  * Return the value returned by ROUTINE, or (DWORD)-1 if call failed.
157  */
158 static DWORD
159 run_in_other_process (HANDLE h_process,
160                       LPTHREAD_START_ROUTINE routine, LPVOID code_end,
161                       LPVOID data, size_t data_size)
162 {
163   process_memory pm;
164   size_t code_size = (LPBYTE)code_end - (LPBYTE)routine;
165   /* Need at most 3 extra bytes of memory, for data alignment */
166   size_t total_size = code_size + data_size + 3;
167   LPVOID remote_data;
168   HANDLE h_thread;
169   DWORD dw_unused;
170
171   /* Allocate memory */
172   if (!alloc_process_memory (h_process, total_size, &pm))
173     return (DWORD)-1;
174
175   /* Copy code */
176   if (!WriteProcessMemory (h_process, pm.address, (LPVOID)routine,
177                            code_size, NULL))
178     goto failure;
179
180   /* Copy data */
181   if (data_size)
182     {
183       remote_data = (LPBYTE)pm.address + ((code_size + 4) & ~3);
184       if (!WriteProcessMemory (h_process, remote_data, data, data_size, NULL))
185         goto failure;
186     }
187   else
188     remote_data = NULL;
189
190   /* Execute the remote copy of code, passing it remote data */
191   h_thread = CreateRemoteThread (h_process, NULL, 0,
192                                  (LPTHREAD_START_ROUTINE) pm.address,
193                                  remote_data, 0, &dw_unused);
194   if (h_thread == NULL)
195     goto failure;
196
197   /* Wait till thread finishes */
198   WaitForSingleObject (h_thread, INFINITE);
199
200   /* Free remote memory */
201   free_process_memory (&pm);
202
203   /* Return thread's exit code */
204   {
205     DWORD exit_code;
206     GetExitCodeThread (h_thread, &exit_code);
207     CloseHandle (h_thread);
208     return exit_code;
209   }
210
211  failure:
212   free_process_memory (&pm);
213   return (DWORD)-1;
214 }
215 \f
216 /*-----------------------------------------------------------------------*/
217 /* Sending signals                                                       */
218 /*-----------------------------------------------------------------------*/
219
220 /*
221  * We handle the following signals:
222  *
223  * SIGKILL, SIGTERM, SIGQUIT, SIGHUP - These four translate to ExitProcess
224  *    executed by the remote process
225  * SIGINT - The remote process is sent CTRL_BREAK_EVENT
226  */
227
228 /*
229  * Sending SIGKILL
230  */
231 typedef struct
232 {
233   void (WINAPI *adr_ExitProcess) (UINT);
234 } sigkill_data;
235
236 static DWORD WINAPI
237 sigkill_proc (sigkill_data* data)
238 {
239   (*data->adr_ExitProcess)(255);
240   return 1;
241 }
242
243 /* Watermark in code space */
244 static void
245 sigkill_code_end (void)
246 {
247 }
248
249 /*
250  * Sending break or control c
251  */
252 typedef struct
253 {
254   BOOL (WINAPI *adr_GenerateConsoleCtrlEvent) (DWORD, DWORD);
255   DWORD event;
256 } sigint_data;
257
258 static DWORD WINAPI
259 sigint_proc (sigint_data* data)
260 {
261   return (*data->adr_GenerateConsoleCtrlEvent) (data->event, 0);
262 }
263
264 /* Watermark in code space */
265 static void
266 sigint_code_end (void)
267 {
268 }
269
270 /*
271  * Enabling signals
272  */
273 typedef struct
274 {
275   BOOL (WINAPI *adr_SetConsoleCtrlHandler) (LPVOID, BOOL);
276 } sig_enable_data;
277
278 static DWORD WINAPI
279 sig_enable_proc (sig_enable_data* data)
280 {
281   (*data->adr_SetConsoleCtrlHandler) (NULL, FALSE);
282   return 1;
283 }
284
285 /* Watermark in code space */
286 static void
287 sig_enable_code_end (void)
288 {
289 }
290
291 /*
292  * Send signal SIGNO to process H_PROCESS.
293  * Return nonzero if successful.
294  */
295
296 /* This code assigns a return value of GetProcAddress to function pointers
297    of many different types. Instead of heavy obscure casts, we just disable
298    warnings about assignments to different function pointer types. */
299 #pragma warning (disable : 4113)
300
301 static int
302 send_signal (HANDLE h_process, int signo)
303 {
304   HMODULE h_kernel = GetModuleHandle ("kernel32");
305   DWORD retval;
306   
307   assert (h_kernel != NULL);
308   
309   switch (signo)
310     {
311     case SIGKILL:
312     case SIGTERM:
313     case SIGQUIT:
314     case SIGHUP:
315       {
316         sigkill_data d;
317         d.adr_ExitProcess = GetProcAddress (h_kernel, "ExitProcess");
318         assert (d.adr_ExitProcess);
319         retval = run_in_other_process (h_process,
320                                        sigkill_proc, sigkill_code_end,
321                                        &d, sizeof (d));
322         break;
323       }
324     case SIGINT:
325       {
326         sigint_data d;
327         d.adr_GenerateConsoleCtrlEvent =
328           GetProcAddress (h_kernel, "GenerateConsoleCtrlEvent");
329         assert (d.adr_GenerateConsoleCtrlEvent);
330         d.event = CTRL_C_EVENT;
331         retval = run_in_other_process (h_process,
332                                        sigint_proc, sigint_code_end,
333                                        &d, sizeof (d));
334         break;
335       }
336     default:
337       assert (0);
338     }
339
340   return (int)retval > 0 ? 1 : 0;
341 }
342
343 /*
344  * Enable CTRL_C_EVENT handling in a new child process
345  */
346 static void
347 enable_child_signals (HANDLE h_process)
348 {
349   HMODULE h_kernel = GetModuleHandle ("kernel32");
350   sig_enable_data d;
351   
352   assert (h_kernel != NULL);
353   d.adr_SetConsoleCtrlHandler =
354     GetProcAddress (h_kernel, "SetConsoleCtrlHandler");
355   assert (d.adr_SetConsoleCtrlHandler);
356   run_in_other_process (h_process,
357                         sig_enable_proc, sig_enable_code_end,
358                         &d, sizeof (d));
359 }
360   
361 #pragma warning (default : 4113)
362
363 /*
364  * Signal error if SIGNO is not supported
365  */
366 static void
367 validate_signal_number (int signo)
368 {
369   if (signo != SIGKILL && signo != SIGTERM
370       && signo != SIGQUIT && signo != SIGINT
371       && signo != SIGHUP)
372     signal_simple_error ("Signal number not supported", make_int (signo));
373 }
374 \f  
375 /*-----------------------------------------------------------------------*/
376 /* Process methods                                                       */
377 /*-----------------------------------------------------------------------*/
378
379 /*
380  * Allocate and initialize Lisp_Process->process_data
381  */
382
383 static void
384 nt_alloc_process_data (struct Lisp_Process *p)
385 {
386   p->process_data = xnew_and_zero (struct nt_process_data);
387 }
388
389 static void
390 nt_finalize_process_data (struct Lisp_Process *p, int for_disksave)
391 {
392   assert (!for_disksave);
393   if (NT_DATA(p)->h_process)
394     CloseHandle (NT_DATA(p)->h_process);
395 }
396
397 /*
398  * Initialize XEmacs process implemenation once
399  */
400 static void
401 nt_init_process (void)
402 {
403   /* Initialize winsock */
404   WSADATA wsa_data;
405   /* Request Winsock v1.1 Note the order: (minor=1, major=1) */
406   WSAStartup (MAKEWORD (1,1), &wsa_data);
407 }
408
409 /*
410  * Fork off a subprocess. P is a pointer to newly created subprocess
411  * object. If this function signals, the caller is responsible for
412  * deleting (and finalizing) the process object.
413  *
414  * The method must return PID of the new proces, a (positive??? ####) number
415  * which fits into Lisp_Int. No return value indicates an error, the method
416  * must signal an error instead.
417  */
418
419 /* #### This function completely ignores Vprocess_environment */
420
421 static void
422 signal_cannot_launch (Lisp_Object image_file, DWORD err)
423 {
424   mswindows_set_errno (err);
425   signal_simple_error_2 ("Error starting", image_file, lisp_strerror (errno));
426 }
427
428 static int
429 nt_create_process (struct Lisp_Process *p,
430                    Lisp_Object *argv, int nargv,
431                    Lisp_Object program, Lisp_Object cur_dir)
432 {
433   HANDLE hmyshove, hmyslurp, hprocin, hprocout;
434   LPTSTR command_line;
435   BOOL do_io, windowed;
436
437   /* Find out whether the application is windowed or not */
438   {
439     /* SHGetFileInfo tends to return ERROR_FILE_NOT_FOUND on most
440        errors. This leads to bogus error message. */
441     DWORD image_type;
442     char *p = strrchr ((char *)XSTRING_DATA (program), '.');
443     if (p != NULL &&
444         (stricmp (p, ".exe") == 0 ||
445          stricmp (p, ".com") == 0 ||
446          stricmp (p, ".bat") == 0 ||
447          stricmp (p, ".cmd") == 0))
448       {
449         image_type = SHGetFileInfo ((char *)XSTRING_DATA (program), 0,NULL,
450                                     0, SHGFI_EXETYPE);
451       }
452     else
453       {
454         char progname[MAX_PATH];
455         sprintf (progname, "%s.exe", (char *)XSTRING_DATA (program));
456         image_type = SHGetFileInfo (progname, 0, NULL, 0, SHGFI_EXETYPE);
457       }
458     if (image_type == 0)
459       signal_cannot_launch (program, (GetLastError () == ERROR_FILE_NOT_FOUND
460                                       ? ERROR_BAD_FORMAT : GetLastError ()));
461     windowed = HIWORD (image_type) != 0;
462   }
463
464   /* Decide whether to do I/O on process handles, or just mark the
465      process exited immediately upon successful launching. We do I/O if the
466      process is a console one, or if it is windowed but windowed_process_io
467      is non-zero */
468   do_io = !windowed || windowed_process_io ;
469   
470   if (do_io)
471     {
472       /* Create two unidirectional named pipes */
473       HANDLE htmp;
474       SECURITY_ATTRIBUTES sa;
475
476       sa.nLength = sizeof(sa);
477       sa.bInheritHandle = TRUE;
478       sa.lpSecurityDescriptor = NULL;
479
480       CreatePipe (&hprocin, &hmyshove, &sa, 0);
481       CreatePipe (&hmyslurp, &hprocout, &sa, 0);
482
483       /* Stupid Win32 allows to create a pipe with *both* ends either
484          inheritable or not. We need process ends inheritable, and local
485          ends not inheritable. */
486       DuplicateHandle (GetCurrentProcess(), hmyshove, GetCurrentProcess(), &htmp,
487                        0, FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS);
488       hmyshove = htmp;
489       DuplicateHandle (GetCurrentProcess(), hmyslurp, GetCurrentProcess(), &htmp,
490                        0, FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS);
491       hmyslurp = htmp;
492     }
493
494   /* Convert an argv vector into Win32 style command line by a call to
495      lisp function `nt-quote-process-args' which see (in winnt.el)*/
496   {
497     int i;
498     Lisp_Object args_or_ret = Qnil;
499     struct gcpro gcpro1;
500
501     GCPRO1 (args_or_ret);
502
503     for (i = 0; i < nargv; ++i)
504       args_or_ret = Fcons (*argv++, args_or_ret);
505     args_or_ret = Fnreverse (args_or_ret);
506     args_or_ret = Fcons (program, args_or_ret);
507
508     args_or_ret = call1 (Qnt_quote_process_args, args_or_ret);
509
510     if (!STRINGP (args_or_ret))
511       /* Luser wrote his/her own clever version */
512       error ("Bogus return value from `nt-quote-process-args'");
513
514     command_line = alloca_array (char, (XSTRING_LENGTH (program)
515                                         + XSTRING_LENGTH (args_or_ret) + 2));
516     strcpy (command_line, XSTRING_DATA (program));
517     strcat (command_line, " ");
518     strcat (command_line, XSTRING_DATA (args_or_ret));
519
520     UNGCPRO; /* args_or_ret */
521   }
522
523   /* Create process */
524   {
525     STARTUPINFO si;
526     PROCESS_INFORMATION pi;
527     DWORD err;
528
529     xzero (si);
530     si.dwFlags = STARTF_USESHOWWINDOW;
531     si.wShowWindow = windowed ? SW_SHOWNORMAL : SW_HIDE;
532     if (do_io)
533       {
534         si.hStdInput = hprocin;
535         si.hStdOutput = hprocout;
536         si.hStdError = hprocout;
537         si.dwFlags |= STARTF_USESTDHANDLES;
538       }
539
540     err = (CreateProcess (NULL, command_line, NULL, NULL, TRUE,
541                           CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP
542                           | CREATE_SUSPENDED,
543                           NULL, (char *) XSTRING_DATA (cur_dir), &si, &pi)
544            ? 0 : GetLastError ());
545
546     if (do_io)
547       {
548         /* These just have been inherited; we do not need a copy */
549         CloseHandle (hprocin);
550         CloseHandle (hprocout);
551       }
552     
553     /* Handle process creation failure */
554     if (err)
555       {
556         if (do_io)
557           {
558             CloseHandle (hmyshove);
559             CloseHandle (hmyslurp);
560           }
561         signal_cannot_launch (program, GetLastError ());
562       }
563
564     /* The process started successfully */
565     if (do_io)
566       {
567         NT_DATA(p)->h_process = pi.hProcess;
568         init_process_io_handles (p, (void*)hmyslurp, (void*)hmyshove, 0);
569       }
570     else
571       {
572         /* Indicate as if the process has exited immediately. */
573         p->status_symbol = Qexit;
574         CloseHandle (pi.hProcess);
575       }
576
577     if (!windowed)
578       enable_child_signals (pi.hProcess);
579
580     ResumeThread (pi.hThread);
581     CloseHandle (pi.hThread);
582
583     /* Hack to support Windows 95 negative pids */
584     return ((int)pi.dwProcessId < 0
585             ? -(int)pi.dwProcessId : (int)pi.dwProcessId);
586   }
587 }
588
589 /* 
590  * This method is called to update status fields of the process
591  * structure. If the process has not existed, this method is expected
592  * to do nothing.
593  *
594  * The method is called only for real child processes.  
595  */
596
597 static void
598 nt_update_status_if_terminated (struct Lisp_Process* p)
599 {
600   DWORD exit_code;
601   if (GetExitCodeProcess (NT_DATA(p)->h_process, &exit_code)
602       && exit_code != STILL_ACTIVE)
603     {
604       p->tick++;
605       p->core_dumped = 0;
606       /* The exit code can be a code returned by process, or an
607          NTSTATUS value. We cannot accurately handle the latter since
608          it is a full 32 bit integer */
609       if (exit_code & 0xC0000000)
610         {
611           p->status_symbol = Qsignal;
612           p->exit_code = exit_code & 0x1FFFFFFF;
613         }
614       else
615         {
616           p->status_symbol = Qexit;
617           p->exit_code = exit_code;
618         }
619     }
620 }
621
622 /*
623  * Stuff the entire contents of LSTREAM to the process ouptut pipe
624  */
625
626 /* #### If only this function could be somehow merged with
627    unix_send_process... */
628
629 static void
630 nt_send_process (Lisp_Object proc, struct lstream* lstream)
631 {
632   struct Lisp_Process *p = XPROCESS (proc);
633
634   /* use a reasonable-sized buffer (somewhere around the size of the
635      stream buffer) so as to avoid inundating the stream with blocked
636      data. */
637   Bufbyte chunkbuf[512];
638   Bytecount chunklen;
639
640   while (1)
641     {
642       int writeret;
643
644       chunklen = Lstream_read (lstream, chunkbuf, 512);
645       if (chunklen <= 0)
646         break; /* perhaps should abort() if < 0?
647                   This should never happen. */
648
649       /* Lstream_write() will never successfully write less than the
650          amount sent in.  In the worst case, it just buffers the
651          unwritten data. */
652       writeret = Lstream_write (XLSTREAM (DATA_OUTSTREAM(p)), chunkbuf,
653                                 chunklen);
654       Lstream_flush (XLSTREAM (DATA_OUTSTREAM(p)));
655       if (writeret < 0)
656         {
657           p->status_symbol = Qexit;
658           p->exit_code = ERROR_BROKEN_PIPE;
659           p->core_dumped = 0;
660           p->tick++;
661           process_tick++;
662           deactivate_process (proc);
663           error ("Broken pipe error sending to process %s; closed it",
664                  XSTRING_DATA (p->name));
665         }
666
667       {
668         int wait_ms = 25;
669         while (Lstream_was_blocked_p (XLSTREAM (p->pipe_outstream)))
670           {
671             /* Buffer is full.  Wait, accepting input; that may allow
672                the program to finish doing output and read more.  */
673             Faccept_process_output (Qnil, Qzero, make_int (wait_ms));
674             Lstream_flush (XLSTREAM (p->pipe_outstream));
675             wait_ms = min (1000, 2 * wait_ms);
676           }
677       }
678     }
679 }
680
681 /*
682  * Send a signal number SIGNO to PROCESS.
683  * CURRENT_GROUP means send to the process group that currently owns
684  * the terminal being used to communicate with PROCESS.
685  * This is used for various commands in shell mode.
686  * If NOMSG is zero, insert signal-announcements into process's buffers
687  * right away.
688  *
689  * If we can, we try to signal PROCESS by sending control characters
690  * down the pty.  This allows us to signal inferiors who have changed
691  * their uid, for which killpg would return an EPERM error.
692  *
693  * The method signals an error if the given SIGNO is not valid
694  */
695
696 static void
697 nt_kill_child_process (Lisp_Object proc, int signo,
698                        int current_group, int nomsg)
699 {
700   struct Lisp_Process *p = XPROCESS (proc);
701
702   /* Signal error if SIGNO cannot be sent */
703   validate_signal_number (signo);
704
705   /* Send signal */
706   if (!send_signal (NT_DATA(p)->h_process, signo))
707     error ("Cannot send signal to process");
708 }
709
710 /*
711  * Kill any process in the system given its PID.
712  *
713  * Returns zero if a signal successfully sent, or
714  * negative number upon failure
715  */
716 static int
717 nt_kill_process_by_pid (int pid, int signo)
718 {
719   HANDLE h_process;
720   int send_result;
721   
722   /* Signal error if SIGNO cannot be sent */
723   validate_signal_number (signo);
724
725   /* Try to open the process with required privileges */
726   h_process = OpenProcess (PROCESS_CREATE_THREAD
727                            | PROCESS_QUERY_INFORMATION 
728                            | PROCESS_VM_OPERATION
729                            | PROCESS_VM_WRITE,
730                            FALSE, pid);
731   if (h_process == NULL)
732     return -1;
733   
734   send_result = send_signal (h_process, signo);
735   
736   CloseHandle (h_process);
737
738   return send_result ? 0 : -1;
739 }
740 \f
741 /*-----------------------------------------------------------------------*/
742 /* Sockets connections                                                   */
743 /*-----------------------------------------------------------------------*/
744 #ifdef HAVE_SOCKETS
745
746 /* #### Hey MS, how long Winsock 2 for '95 will be in beta? */
747
748 #define SOCK_TIMER_ID 666
749 #define XM_SOCKREPLY (WM_USER + 666)
750
751 static int
752 get_internet_address (Lisp_Object host, struct sockaddr_in *address,
753                       Error_behavior errb)
754 {
755   char buf [MAXGETHOSTSTRUCT];
756   HWND hwnd;
757   HANDLE hasync;
758   int success = 0;
759
760   address->sin_family = AF_INET;
761
762   /* First check if HOST is already a numeric address */
763   {
764     unsigned long inaddr = inet_addr (XSTRING_DATA (host));
765     if (inaddr != INADDR_NONE)
766       {
767         address->sin_addr.s_addr = inaddr;
768         return 1;
769       }
770   }
771
772   /* Create a window which will receive completion messages */
773   hwnd = CreateWindow ("STATIC", NULL, WS_OVERLAPPED, 0, 0, 1, 1,
774                        NULL, NULL, NULL, NULL);
775   assert (hwnd);
776
777   /* Post name resolution request */
778   hasync = WSAAsyncGetHostByName (hwnd, XM_SOCKREPLY, XSTRING_DATA (host),
779                                   buf, sizeof (buf));
780   if (hasync == NULL)
781     goto done;
782
783   /* Set a timer to poll for quit every 250 ms */
784   SetTimer (hwnd, SOCK_TIMER_ID, 250, NULL);
785
786   while (1)
787     {
788       MSG msg;
789       GetMessage (&msg, hwnd, 0, 0);
790       if (msg.message == XM_SOCKREPLY)
791         {
792           /* Ok, got an answer */
793           if (WSAGETASYNCERROR(msg.lParam) == NO_ERROR)
794             success = 1;
795           goto done;
796         }
797       else if (msg.message == WM_TIMER && msg.wParam == SOCK_TIMER_ID)
798         {
799           if (QUITP)
800             {
801               WSACancelAsyncRequest (hasync);
802               KillTimer (hwnd, SOCK_TIMER_ID);
803               DestroyWindow (hwnd);
804               REALLY_QUIT;
805             }
806         }
807       DispatchMessage (&msg);
808     }
809
810  done:
811   KillTimer (hwnd, SOCK_TIMER_ID);
812   DestroyWindow (hwnd);
813   if (success)
814     {
815       /* BUF starts with struct hostent */
816       struct hostent* he = (struct hostent*) buf;
817       address->sin_addr.s_addr = *(unsigned long*)he->h_addr_list[0];
818     }
819   return success;
820 }
821
822 static Lisp_Object
823 nt_canonicalize_host_name (Lisp_Object host)
824 {
825   struct sockaddr_in address;
826
827   if (!get_internet_address (host, &address, ERROR_ME_NOT))
828     return host;
829
830   if (address.sin_family == AF_INET)
831     return build_string (inet_ntoa (address.sin_addr));
832   else
833     return host;
834 }
835
836 /* open a TCP network connection to a given HOST/SERVICE.  Treated
837    exactly like a normal process when reading and writing.  Only
838    differences are in status display and process deletion.  A network
839    connection has no PID; you cannot signal it.  All you can do is
840    deactivate and close it via delete-process */
841
842 static void
843 nt_open_network_stream (Lisp_Object name, Lisp_Object host, Lisp_Object service,
844                         Lisp_Object family, void** vinfd, void** voutfd)
845 {
846   struct sockaddr_in address;
847   SOCKET s;
848   int port;
849   int retval;
850
851   CHECK_STRING (host);
852
853   if (!EQ (family, Qtcpip))
854     error ("Unsupported protocol family \"%s\"",
855            string_data (symbol_name (XSYMBOL (family))));
856
857   if (INTP (service))
858     port = htons ((unsigned short) XINT (service));
859   else
860     {
861       struct servent *svc_info;
862       CHECK_STRING (service);
863       svc_info = getservbyname ((char *) XSTRING_DATA (service), "tcp");
864       if (svc_info == 0)
865         error ("Unknown service \"%s\"", XSTRING_DATA (service));
866       port = svc_info->s_port;
867     }
868
869   get_internet_address (host, &address, ERROR_ME);
870   address.sin_port = port;
871
872   s = socket (address.sin_family, SOCK_STREAM, 0);
873   if (s < 0)
874     report_file_error ("error creating socket", list1 (name));
875
876   /* We don't want to be blocked on connect */
877   {
878     unsigned int nonblock = 1;
879     ioctlsocket (s, FIONBIO, &nonblock);
880   }
881   
882   retval = connect (s, (struct sockaddr *) &address, sizeof (address));
883   if (retval != NO_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
884     goto connect_failed;
885
886   /* Wait while connection is established */
887   while (1)
888     {
889       fd_set fdset;
890       struct timeval tv;
891       int nsel;
892
893       if (QUITP)
894         {
895           closesocket (s);
896           REALLY_QUIT;
897         }
898
899       /* Poll for quit every 250 ms */
900       tv.tv_sec = 0;
901       tv.tv_usec = 250 * 1000;
902
903       FD_ZERO (&fdset);
904       FD_SET (s, &fdset);
905       nsel = select (0, NULL, &fdset, &fdset, &tv);
906
907       if (nsel > 0)
908         {
909           /* Check was connnection successful or not */
910           tv.tv_usec = 0;
911           nsel = select (0, NULL, NULL, &fdset, &tv);
912           if (nsel > 0)
913             goto connect_failed;
914           else
915             break;
916         }
917     }
918
919   /* We are connected at this point */
920   *vinfd = (void*)s;
921   DuplicateHandle (GetCurrentProcess(), (HANDLE)s,
922                    GetCurrentProcess(), (LPHANDLE)voutfd,
923                    0, FALSE, DUPLICATE_SAME_ACCESS);
924   return;
925
926  connect_failed:  
927   closesocket (s);
928   report_file_error ("connection failed", list2 (host, name));
929 }
930
931 #endif
932 \f
933 /*-----------------------------------------------------------------------*/
934 /* Initialization                                                        */
935 /*-----------------------------------------------------------------------*/
936
937 void
938 process_type_create_nt (void)
939 {
940   PROCESS_HAS_METHOD (nt, alloc_process_data);
941   PROCESS_HAS_METHOD (nt, finalize_process_data);
942   PROCESS_HAS_METHOD (nt, init_process);
943   PROCESS_HAS_METHOD (nt, create_process);
944   PROCESS_HAS_METHOD (nt, update_status_if_terminated);
945   PROCESS_HAS_METHOD (nt, send_process);
946   PROCESS_HAS_METHOD (nt, kill_child_process);
947   PROCESS_HAS_METHOD (nt, kill_process_by_pid);
948 #ifdef HAVE_SOCKETS
949   PROCESS_HAS_METHOD (nt, canonicalize_host_name);
950   PROCESS_HAS_METHOD (nt, open_network_stream);
951 #ifdef HAVE_MULTICAST
952 #error I won't do this until '95 has winsock2
953   PROCESS_HAS_METHOD (nt, open_multicast_group);
954 #endif
955 #endif
956 }
957
958 void
959 syms_of_process_nt (void)
960 {
961   defsymbol (&Qnt_quote_process_args, "nt-quote-process-args");
962 }
963
964 void
965 vars_of_process_nt (void)
966 {
967 }