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