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