Link with C++ linker
[oweals/cde.git] / cde / programs / dtpdmd / manager.c
1 /*
2  * CDE - Common Desktop Environment
3  *
4  * Copyright (c) 1993-2012, The Open Group. All rights reserved.
5  *
6  * These libraries and programs are free software; you can
7  * redistribute them and/or modify them under the terms of the GNU
8  * Lesser General Public License as published by the Free Software
9  * Foundation; either version 2 of the License, or (at your option)
10  * any later version.
11  *
12  * These libraries and programs are distributed in the hope that
13  * they will be useful, but WITHOUT ANY WARRANTY; without even the
14  * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15  * PURPOSE. See the GNU Lesser General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with these librararies and programs; if not, write
20  * to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
21  * Floor, Boston, MA 02110-1301 USA
22  */
23 /******************************************************************************
24  ******************************************************************************
25  **
26  ** File:         manager.c
27  ** RCS:          $XConsortium: manager.c /main/8 1996/10/30 19:10:15 cde-hp $
28  **
29  ** Description:
30  **
31  ** (c) Copyright 1995, Hewlett-Packard Company, all rights reserved.
32  **
33  ******************************************************************************
34  *****************************************************************************/
35
36 #define MANAGER_DOT_C
37
38 #define OPTIONAL_PXAUTH_PRETEST 1
39
40 #include "dtpdmdP.h"
41 #include "nlmsg.h"
42 #include <locale.h>
43 #include <unistd.h>
44
45
46
47 /******************************************************************************
48  ******************************************************************************
49  *
50  * The following PDM_MANAGER : PDM_START routines are registered
51  * per child, and dispatched out of XtAppNextEvent
52  */
53
54 /********************************************************************
55  *
56  * message_pipe_handler()
57  *
58  * Takes stderr from the child, via a pipe, and stores the output
59  * in the client tracking record.
60  * 
61  */
62 static void message_pipe_handler( XtPointer w, int *source, XtInputId *id)
63 {
64     int    i, inc;
65     struct stat statBuffer;
66     int    delt_with;
67     int    n, keepon;
68
69     /*
70      * Find out who is generating output.
71      */
72     delt_with = False;
73
74     for ( i = 0; i < g.serviceRecNum; i++ ) {
75         if ( g.serviceRecs[i]->message_pipe[0] == *source ) {
76             delt_with = True;
77             /*
78              * Fetch size and grow message_string to hold more.
79              */
80             if ( fstat(*source, &statBuffer) ) {
81                 /* unable to get size */
82                 statBuffer.st_size = 0;         /* bail out below */
83             }
84
85             if ( statBuffer.st_size > 0 ) {
86                 if ( g.serviceRecs[i]->message_string ) {
87                     inc = strlen( g.serviceRecs[i]->message_string );
88
89                     g.serviceRecs[i]->message_string = Xrealloc(
90                                 (char *) g.serviceRecs[i]->message_string,
91                                 statBuffer.st_size + inc + 1 );
92                 }
93                 else {
94                     inc = 0;
95
96                     g.serviceRecs[i]->message_string = Xmalloc(
97                                 statBuffer.st_size + 1 );
98                 }
99
100                 /*
101                  * Read off what we know is there.
102                  */
103                 keepon = True;
104                 while (keepon) {
105                     n = read( *source, &(g.serviceRecs[i]->message_string[inc]),
106                                 statBuffer.st_size );
107
108                     if ( n == statBuffer.st_size ) {
109                         /* read all there is (per the previous stat) */
110                         keepon = False;
111                     }
112                     else if (( n == -1 ) && ( errno == EINTR )) {
113                         /* an interrupt came in before the read could start */
114                         keepon = True;
115                     }
116                     else if (( n == -1 ) || ( n == 0 )) {
117                         /* problems - bail out */
118                         g.serviceRecs[i]->message_pipe[0] = -1;
119                         close(*source);
120                         XtRemoveInput(*id);
121                         keepon = False;
122                     }
123                     else {
124                         /* only a partial read, probably a sig, try for more */
125                         inc += n;
126                         statBuffer.st_size -= n;
127                         keepon = True;
128                     }
129                 }
130
131                 /*
132                  * NULL terminate what we have so far to make it look
133                  * like a string.
134                  */
135                 g.serviceRecs[i]->message_string[statBuffer.st_size+inc] = '\0';
136             }
137             else {
138                 /*
139                  * No more to read - this really means the pipe is
140                  * going down.
141                  */
142                 g.serviceRecs[i]->message_pipe[0] = -1;
143                 close (*source);
144                 XtRemoveInput(*id);
145             }
146         }
147     }
148
149     if (!delt_with) {
150         /*
151          * Some stray pipe that we no longer have information on.
152          */
153         close(*source);
154         XtRemoveInput(*id);
155     }
156
157     /*
158      * Scan client records and see who is ready to be
159      * shut down.
160      */
161     mgr_shutdown_scan();
162 }
163
164
165 /******************************************************************************
166  ******************************************************************************
167  *
168  * The following PDM_MANAGER : PDM_START routines are called by
169  * the dispatch routines to service selection requests and
170  * associated events.
171  */
172
173 /********************************************************************
174  *
175  * Setup a child service record per the selection request.
176  */
177 void mgr_initialize( XEvent *report, XpPdmServiceRec *rec )
178 {
179     Display *testdpy;
180     char    buf[1024];
181
182     Display *selection_display;
183     Window   requestor;
184     Atom     prop_atom;
185     unsigned long tafter;
186
187     XTextProperty  text_prop;
188     char           **list;
189     int            list_cnt;
190
191     /*
192      * Grab the PDM_CLIENT_PROP from which all the juicy
193      * information is retrieved.
194      */
195     selection_display = report->xselectionrequest.display;
196     requestor = report->xselectionrequest.requestor;
197     prop_atom = report->xselectionrequest.property;
198
199     if ( XGetWindowProperty( selection_display, requestor, prop_atom,
200                         0, 100000, True, AnyPropertyType,
201                         &text_prop.encoding,
202                         &text_prop.format,
203                         &text_prop.nitems,
204                         &tafter,
205                         &text_prop.value ) != Success ) {
206         /*
207          * Error
208          */
209         rec->pdm_exec_errorcode = g.pdm_start_error;
210
211         sprintf( buf, PDMD_MSG_5, g.prog_name );
212         rec->pdm_exec_errormessage = xpstrdup( buf );
213
214         return;
215     }
216
217     if ( text_prop.format != 8 ) {
218         /*
219          * Error
220          */
221         rec->pdm_exec_errorcode = g.pdm_start_error;
222
223         sprintf( buf, PDMD_MSG_6, g.prog_name );
224         rec->pdm_exec_errormessage = xpstrdup( buf );
225
226         return;
227     }
228
229     if ( XmbTextPropertyToTextList( selection_display, &text_prop,
230                                      &list, &list_cnt ) < 0 ) {
231         /*
232          * Error
233          */
234         rec->pdm_exec_errorcode = g.pdm_start_error;
235
236         sprintf( buf, PDMD_MSG_7, g.prog_name );
237         rec->pdm_exec_errormessage = xpstrdup( buf );
238
239         return;
240     }
241
242     /*
243      * Fill in the PDM_MANAGER portion of the client record.
244      */
245     rec->video_display_str  = xpstrdup( list[0] );
246     rec->video_window       = strtol(list[1], (char **)NULL, 16);
247     rec->print_display_str  = xpstrdup( list[2] );
248     rec->print_window       = strtol(list[3], (char **)NULL, 16);
249     rec->print_context      = strtol(list[4], (char **)NULL, 16);
250     rec->locale_hint        = xpstrdup( list[5] );
251     XFreeStringList( list );
252
253     rec->selection_display  = selection_display;
254     rec->requestor          = requestor;
255     rec->prop_atom          = prop_atom;
256     rec->selection          = report->xselectionrequest.selection;
257     rec->time               = report->xselectionrequest.time;
258
259     rec->mgr_flag           = True;     /* mgr portion of rec now valid */
260
261     /*
262      * Optimization.  The only live display connection, for which we
263      * need to trap XIO errors, is "selection display".  For the
264      * "video" and "print" displays, we have the display strings and
265      * can establish connections as we need them.  Since they are rarely
266      * used, and opening them up here would create XIO liability problems
267      * and a startup performance hit, we won't establish connections now.
268      *
269      * One optimization however is to see if the "print" display would
270      * just happen to be the same at the "selection display" currently
271      * open.
272      */
273     if ( !strcmp( XDisplayString(rec->selection_display),
274                   rec->print_display_str ) ) {
275         rec->seldpy_as_printdpy = True;
276     }
277     else {
278         rec->seldpy_as_printdpy = False;
279
280 #ifdef OPTIONAL_PXAUTH_PRETEST
281         /*
282          * Verify connectability to the Print Server.
283          *
284          * Note: once beyond the selection phase, all communication
285          *       will be by way of the Print Server.  If we cannot
286          *       connect later, then we will have no way to deliver
287          *       EXIT_PXAUTH, EXIT_VXAUTH, EXIT_ERROR, EXIT_OK or
288          *       EXIT_CANCEL.  Real bad news!
289          *
290          * It is better to discover now that we don't have
291          * connection authorization for the print display since
292          * we can still let the user know of PXAUTH problems
293          * via the selection display currently open.
294          *
295          * Unfortunately, this pre-test is a performance hit in the
296          * startup phase.
297          */
298         if ( ! (testdpy = XOpenDisplay(rec->print_display_str)) ) {
299             rec->pdm_exec_errorcode = g.pdm_start_pxauth;
300             return;
301         }
302         XCloseDisplay( testdpy );
303 #endif /* OPTIONAL_PXAUTH_PRETEST */
304     }
305
306 #ifdef OPTIONAL_VXAUTH_PRETEST
307     /*
308      * Verify connectability to the Video Server.
309      *
310      * It is better to discover now that we don't have
311      * connection authorization for the video display since
312      * we can still let the user know of VXAUTH problems
313      * via the selection display currently open.
314      *
315      * Unfortunately, this pre-test is a performance hit in the
316      * startup phase.
317      */
318     if ( ! (testdpy = XOpenDisplay(rec->video_display_str)) ) {
319         rec->pdm_exec_errorcode = g.pdm_start_vxauth;
320         return;
321     }
322     XCloseDisplay( testdpy );
323 #endif /* OPTIONAL_VXAUTH_PRETEST */
324
325 }
326 /********************************************************************
327  *
328  * fork/exec a child pdm after setting up a message pipe. 
329  */
330 void mgr_launch_pdm( XpPdmServiceRec *rec )
331 {
332     int       i;
333     struct sigaction svec;
334     char      buf[1024];
335     int       original_umask;
336     char      *existing_name;
337     FILE      *existing_file;
338     Xauth     *entry;
339     char      *envstr;
340
341
342     /*
343      * Setup message pipe.
344      */
345     if ( pipe(rec->message_pipe) == -1 ) {
346         rec->pdm_exec_errorcode = g.pdm_start_error;
347         sprintf( buf, PDMD_MSG_8, g.prog_name );
348         rec->pdm_exec_errormessage = xpstrdup( buf );
349         return;
350     }
351
352     rec->message_xtid = XtAppAddInput( g.context, rec->message_pipe[0],
353                           (XtPointer) XtInputReadMask,
354                           message_pipe_handler, (XtPointer) NULL );
355
356     /*
357      * See if a cookie file is needed.
358      */
359     if (rec->cookie_cnt) {
360         /*
361          * Create new .Xauthority file.
362          */
363         original_umask = umask (0077);      /* disallow non-owner access */
364         tmpnam( rec->auth_filename );
365         rec->auth_file = fopen( rec->auth_filename, "w" );
366
367         if (rec->auth_file) {
368             /*
369              * Copy existing .Xauthority entries.
370              */
371             existing_name = XauFileName ();
372
373             if (existing_name) {
374                 if (access (existing_name, R_OK) == 0) {     /* checks REAL id */
375                     existing_file = fopen (existing_name, "r");
376                     if (existing_file) {
377                         for (;;) {
378                             entry = XauReadAuth (existing_file);
379                             if (!entry)
380                                 break;
381
382                             XauWriteAuth( rec->auth_file, entry );
383                             XauDisposeAuth (entry);
384                         }
385                         fclose (existing_file);
386                     }
387                 }
388             }
389
390             /*
391              * Merge in cookies recently sent.
392              */
393             for ( i = 0; i < rec->cookie_cnt; i++ ) {
394                 XauWriteAuth( rec->auth_file, rec->cookies[i] );
395             }
396
397             fclose( rec->auth_file );
398         }
399         original_umask = umask (original_umask);
400     }
401
402
403     rec->pid = fork();
404
405     if ( rec->pid < 0 ) {
406         rec->pdm_exec_errorcode = g.pdm_start_error;
407         sprintf( buf, PDMD_MSG_9, g.prog_name );
408         rec->pdm_exec_errormessage = xpstrdup( buf );
409         return;
410     }
411     else if ( rec->pid == 0) {
412         /*
413          * Child process.
414          */
415
416         /*
417          * Hook stderr back to parent via message pipe.
418          */
419         dup2(rec->message_pipe[1], 2);
420         close(rec->message_pipe[0]);
421
422         /*
423          * The child should have default behavior for all signals.
424          */
425         sigemptyset(&svec.sa_mask);
426         svec.sa_flags   = 0;
427         svec.sa_handler = SIG_DFL;
428         (void) sigaction(SIGCLD, &svec, (struct sigaction *) NULL);
429
430         for (i=3; i < FOPEN_MAX; i++) {
431             if ((i != rec->message_pipe[1]) && 
432                 (rec->auth_file && (i != fileno(rec->auth_file))))
433             {
434                 (void) fcntl (i, F_SETFD, 1);
435             }
436         }
437
438         /*
439          * Set the new locale for the child.
440          *
441          * note: the locale hint will be of the form:
442          *
443          *    name_spec[;registry_spec[;ver_spec[;encoding_spec]]]
444          *
445          * for now, just pull out the name_spec (e.g. 'C')
446          * and use it.   With a little work, a more complex
447          * syntax could be understood and the appropriate
448          * actions taken here rather than just wedging
449          * name_spec into setlocale() and hoping.
450          */
451         if ( !(rec->locale_hint) ) {
452             /*
453              * Leave current locale alone.
454              */
455         }
456         else if ( strcmp( rec->locale_hint, "" ) ) {
457             /*
458              * Leave current locale alone.  Note that "" into
459              * setlocale says to go with default vs leave it alone.
460              */
461         }
462         else {
463             char *tptr1, *tptr2;
464
465             tptr1 = xpstrdup( rec->locale_hint );
466             tptr2 = strchr( tptr1, ';' );
467             if (tptr2) *tptr2 = '\0';
468         
469             setlocale( LC_ALL, tptr1 );
470             XFree( tptr1 );
471         }
472
473         /*
474          * Set XAUTHORITY env var if needed.
475          */
476         if ((rec->cookie_cnt) && (rec->auth_filename) && (rec->auth_file)) {
477             envstr = Xmalloc( strlen(rec->auth_filename) + 12 );
478             sprintf( envstr, "XAUTHORITY=%s", rec->auth_filename );
479             putenv( envstr );
480         }
481
482         /*
483          * Start the child for real.
484          */
485         (void) execvp(rec->pdm_exec_argvs[0], rec->pdm_exec_argvs);
486
487         (void) fprintf (stderr, PDMD_MSG_10, g.prog_name, rec->pdm_exec_argvs[0]);
488
489         /*
490          * tomg - need to deal with failed child start.
491          */
492         exit(PDM_EXIT_ERROR);
493     }
494     else {
495         /*
496          * Parent process.
497          */
498
499         /*
500          * Close the write end of the pipe - only the child needs it.
501          */
502         close(rec->message_pipe[1]);
503         rec->message_pipe[1] = -1;
504     }
505 }
506
507
508 /********************************************************************
509  *
510  * Figure out which pdm executable to later fork/exec.
511  */
512 void mgr_fetch_pdm( XpPdmServiceRec *rec )
513 {
514     char tstr[1024], *tptr1, *tptr2, *tptr3;
515     int  firstTime;
516     long now;
517     Display *tdpy;
518     int lxerrno;
519
520     if ( g.override_pdm ) {
521         /*
522          * Override all defaults and other possible settings.
523          */
524         tptr1 = xpstrdup(g.override_pdm);
525     }
526     else {
527         /*
528          * See if the print context says which pdm to run.
529          */
530         g.xerrno = 0;           /* Error Handler */
531         lxerrno = 0;            /* XIO Error Handler */
532
533         if ( setjmp( xio_quickie_jmp_buf ) == 0 ) {
534             XSetIOErrorHandler( xio_quickie_handler );
535
536             if ( rec->seldpy_as_printdpy ) {
537                 tptr1 = XpGetOneAttribute( rec->selection_display,
538                                    rec->print_context,
539                                    XPPrinterAttr, "dt-pdm-command" );
540             }
541             else {
542                 tdpy = XOpenDisplay( rec->print_display_str );
543                 if (tdpy) {
544                     tptr1 = XpGetOneAttribute( tdpy,
545                                    rec->print_context,
546                                    XPPrinterAttr, "dt-pdm-command" );
547                     XCloseDisplay( tdpy );
548                 }
549             }
550
551             XSetIOErrorHandler( NULL );
552         }
553         else {
554             lxerrno = 1;
555
556             XSetIOErrorHandler( NULL );
557         }
558
559         /*
560          * See if we got a useful pdm exec string.  Use
561          * default if not.
562          */
563         if ( g.xerrno || lxerrno ) {
564             rec->pdm_exec_errorcode = g.pdm_start_error;
565             return;
566         }
567         else if (!tptr1) {
568             tptr1 = xpstrdup(g.default_pdm);
569         }
570         else if (!tptr1[0]) {
571             tptr1 = xpstrdup(g.default_pdm);
572         }
573     }
574     
575     /*
576      * Convert pdm-command into argv[] style array.
577      *
578      * Note: this parsing code does NOT respect shell
579      * quotes and other items.   --tomg
580      */
581     rec->pdm_exec_argvs = (char **) NULL;
582
583     tptr2 = tptr1;      /* retain orig pointer for freeing */
584     firstTime = 1;
585
586     while (1) {
587         if (firstTime) {
588             tptr3 = xpstrtok( tptr2, " \n\t" );
589             firstTime = 0;
590
591             if (!tptr3) {
592                 /*
593                  * There were NO useful tokens to begin with, so
594                  * we'll have to fall back on the default.
595                  */
596                 xp_add_argv( &(rec->pdm_exec_argvs), xpstrdup( g.default_pdm ));
597                 break;
598             }
599         }
600         else {
601             tptr3 = xpstrtok( (char *) NULL, " \n\t" );
602         }
603
604         if (tptr3) {
605             xp_add_argv( &(rec->pdm_exec_argvs), xpstrdup( tptr3 ) );
606         }
607         else {
608             break;
609         }
610     }
611     Xfree(tptr1);
612
613     /*
614      * Add standard command line parameters.
615      */
616     xp_add_argv( &(rec->pdm_exec_argvs), xpstrdup("-display") );
617     xp_add_argv( &(rec->pdm_exec_argvs), xpstrdup(rec->video_display_str) );
618
619     xp_add_argv( &(rec->pdm_exec_argvs), xpstrdup("-window") );
620     sprintf( tstr, "0x%lx", rec->video_window );
621     xp_add_argv( &(rec->pdm_exec_argvs), xpstrdup(tstr) );
622
623     xp_add_argv( &(rec->pdm_exec_argvs), xpstrdup("-pdisplay") );
624     xp_add_argv( &(rec->pdm_exec_argvs), xpstrdup(rec->print_display_str) );
625
626     xp_add_argv( &(rec->pdm_exec_argvs), xpstrdup("-pwindow") );
627     sprintf( tstr, "0x%lx", rec->print_window );
628     xp_add_argv( &(rec->pdm_exec_argvs), xpstrdup(tstr) );
629
630     xp_add_argv( &(rec->pdm_exec_argvs), xpstrdup("-pcontext") );
631     sprintf( tstr, "0x%lx", rec->print_context );
632     xp_add_argv( &(rec->pdm_exec_argvs), xpstrdup(tstr) );
633 }
634
635 /********************************************************************
636  *
637  * Once a pdm has been lauched, reply to the SelectionRequest so that
638  * the requestors knows.
639  */
640 void mgr_launch_reply( XpPdmServiceRec *rec )
641 {
642     XEvent reply;
643     Status status;
644     FILE   *errlog;
645     long   now;
646     char   *eec;
647
648     Atom    tmpa;
649
650
651     XChangeProperty( rec->selection_display, rec->requestor,
652                      rec->prop_atom, XA_ATOM,
653                      32, PropModeReplace,
654                      (unsigned char *) &(rec->pdm_exec_errorcode),
655                      1 );
656
657     /*
658      * Write optional error message to log file.
659      *
660      * Expected errors like PXAUTH and VXAUTH should not have
661      * textual descriptions too - they're obvious as is.  Only
662      * real nasty errors should have a message for the log file.
663      */
664     if ((rec->pdm_exec_errormessage) && (g.log_file)) {
665         if ((errlog = fopen(g.log_file, "a+")) != NULL) {
666             now = time((time_t)0);
667
668             if ( rec->pdm_exec_errorcode == g.pdm_start_ok )
669                 eec = "PDM_START_OK";
670             else if ( rec->pdm_exec_errorcode == g.pdm_start_vxauth )
671                 eec = "PDM_START_VXAUTH";
672             else if ( rec->pdm_exec_errorcode == g.pdm_start_pxauth )
673                 eec = "PDM_START_PXAUTH";
674             else if ( rec->pdm_exec_errorcode == g.pdm_start_error )
675                 eec = "PDM_START_ERROR";
676             else
677                 eec = "unknown error";
678                 
679             fprintf( errlog, PDMD_MSG_11, g.prog_name, ctime(&now),
680                         rec->pdm_exec_errormessage,
681                         eec,
682                         rec->pdm_exec_argvs[0],
683                         rec->print_display_str,
684                         rec->video_display_str );
685
686             fclose(errlog);
687         }
688     }
689
690
691     /*
692      * Send a SelectionNotify event, which will conclude the
693      * selection handshake.
694      */
695     reply.xselection.type      = SelectionNotify;
696     reply.xselection.requestor = rec->requestor;
697     reply.xselection.selection = rec->selection;
698     reply.xselection.target    = g.pdm_start;
699     reply.xselection.property  = rec->prop_atom;
700     reply.xselection.time      = rec->time;
701
702     status = XSendEvent( rec->selection_display, rec->requestor, True, 0, &reply );
703 }
704
705 /********************************************************************
706  *
707  * Send the final OK/CANCEL ClientMessage.
708  */
709 void mgr_shutdown_reply( XpPdmServiceRec *rec )
710 {
711     XEvent cme;
712     Display *pdpy;
713     char *mess;
714     int inc;
715     char buf[2048];
716     int lxerrno;
717
718
719     /*
720      * Setup client message event.
721      */
722     cme.xclient.type         = ClientMessage;
723     cme.xclient.window       = rec->print_window;
724     cme.xclient.message_type = g.pdm_reply;
725     cme.xclient.format       = 32;
726
727     /*
728      * Look at the current exit code.  Let 'mess' be both a message
729      * string, and a string we would XInternAtom on if we find out
730      * that the "Print" X-Server is differnent than the "Selection"
731      * X-Server.  Up till now, we've been using atom constants
732      * generated via the Selection X-Server.
733      */
734     switch (rec->exit_code) {
735         case PDM_EXIT_OK:
736                 cme.xclient.data.l[0] = (long) g.pdm_exit_ok;
737                 mess = "PDM_EXIT_OK";
738                 break;
739         case PDM_EXIT_CANCEL:
740                 cme.xclient.data.l[0] = (long) g.pdm_exit_cancel;
741                 mess = "PDM_EXIT_CANCEL";
742                 break;
743         case PDM_EXIT_VXAUTH:
744                 cme.xclient.data.l[0] = (long) g.pdm_exit_vxauth;
745                 mess = "PDM_EXIT_VXAUTH";
746                 break;
747         case PDM_EXIT_PXAUTH:
748                 cme.xclient.data.l[0] = (long) g.pdm_exit_pxauth;
749                 mess = "PDM_EXIT_PXAUTH";
750                 break;
751         case PDM_EXIT_ERROR:
752         default:
753                 cme.xclient.data.l[0] = (long) g.pdm_exit_error;
754                 mess = "PDM_EXIT_ERROR";
755                 break;
756     }
757
758     /*
759      * Try to send ClientMessage that will carry the reply.
760      */
761
762     g.xerrno = 0;  /* Error Handler */
763     lxerrno = 0;   /* XIO Error Handler */
764
765     if ( setjmp( xio_quickie_jmp_buf ) == 0 ) {
766         XSetIOErrorHandler( xio_quickie_handler );
767
768         if ( rec->seldpy_as_printdpy ) {
769             /*
770              * Since the "Print" X-Server is the same as the
771              * "Selection" X-Server, against which we have an
772              * active display connection and atom values, go
773              * ahead and use it.
774              */
775             XSendEvent( rec->selection_display, rec->print_window, False, 0L, &cme );
776         }
777         else {
778             pdpy = XOpenDisplay( rec->print_display_str );
779             if (pdpy) {
780                 /*
781                  * The "Print" X-Server is different than the
782                  * "Selection" X-Server.  Map values over.
783                  */
784                 cme.xclient.message_type =
785                                 XInternAtom( pdpy, "PDM_REPLY", False );
786                 cme.xclient.data.l[0] =
787                                 (long) XInternAtom( pdpy, mess, False );
788                 XSendEvent( pdpy, rec->print_window, False, 0L, &cme );
789                 XCloseDisplay( pdpy );
790             }
791         }
792
793         XSetIOErrorHandler( NULL );
794     }
795     else {
796         lxerrno = 1;
797
798         XSetIOErrorHandler( NULL );
799     }
800
801     if ( g.xerrno || lxerrno ) {
802         /*
803          * Problem - we can't get back to the requestor.
804          *
805          * This is really a PANIC situation, since the requesting
806          * client will hang around forever, waiting for this
807          * final reply.  The best we can do it log an error for
808          * the sys admin, and hope they can notice.
809          */
810         if (g.xerrno)
811             sprintf( buf, PDMD_MSG_12, g.prog_name, mess );
812         else
813             sprintf( buf, PDMD_MSG_13, g.prog_name, mess );
814
815         rec->message_string2 = Xmalloc( strlen( buf ) + 1 );
816         strcpy( rec->message_string2 , buf );
817     }
818 }
819
820
821 Bool has_exec_token( XpPdmServiceRec *rec )
822 {
823     char *s1, *s2, *s3;
824     int i1;
825
826     s1 = rec->message_string;
827
828     if (s1) {
829         /*
830          * Look for "PDM_START_*" tokens burried in the
831          * stderr output of the PDM.  If found, react as
832          * required, and eliminate the token from the
833          * output.
834          */
835         if ( s2 = strstr( s1, "PDM_START_OK") ) {
836             rec->pdm_exec_errorcode = g.pdm_start_ok;
837             i1 = 12;
838         }
839         else if ( s2 = strstr( s1, "PDM_START_VXAUTH") ) {
840             rec->pdm_exec_errorcode = g.pdm_start_vxauth;
841             i1 = 16;
842         }
843         else if ( s2 = strstr( s1, "PDM_START_PXAUTH") ) {
844             rec->pdm_exec_errorcode = g.pdm_start_pxauth;
845             i1 = 16;
846         }
847         else if ( s2 = strstr( s1, "PDM_START_ERROR") ) {
848             rec->pdm_exec_errorcode = g.pdm_start_error;
849             i1 = 15;
850         }
851
852         if (s2) {
853             /*
854              * Compress out the token.
855              */
856             s3 = s2 + i1;
857             while ( *s2++ = *s3++ );
858
859             if ( strlen(s1) == 0 ) {
860                 /*
861                  * The token was it - free the buffer now so that
862                  * it appears no stderr was ever generated. 
863                  */
864                 Xfree( rec->message_string );
865                 rec->message_string = (char *) NULL;
866             }
867             else if ((strlen(s1) == 1) && (s1[0] == '\n')) {
868                 /*
869                  * All but a \n remains - free the buffer.
870                  */
871                 Xfree( rec->message_string );
872                 rec->message_string = (char *) NULL;
873             }
874
875             return( True );
876         }
877         else {
878             return( False );
879         }
880     }
881     else {
882         return( False );
883     }
884 }
885
886 /********************************************************************
887  *
888  * Search through all the child tracking records and see if
889  * any can be shutdown.
890  */
891 void mgr_shutdown_scan()
892 {
893     int        i;
894     long       now;
895     FILE       *errlog;
896     static int errlog_problem_notice = 0;
897     Bool       shutdown_time;
898
899     for ( i = 0; i < g.serviceRecNum; i++ ) {
900
901         shutdown_time = False;
902
903         if ( (g.serviceRecs[i]->do_launch_reply) &&
904              (has_exec_token(g.serviceRecs[i]) )    ) {
905             /*
906              * Need to send our PDM_START fork/exec reply still.
907              *
908              * Note that if we send pdm_start_ok, we'll need to send
909              * a pdm_exit_* code later.  If we send pdm_start_vxauth,
910              * pdm_start_pxauth, or pdm_start_error, it indicates to
911              * the client a fatal condition, and they will NOT receive
912              * any more messages, including any pdm_exit_* codes.  The
913              * dtpdmd will hang around however, if for no other reason
914              * than to capture stderr and log it when the child finally
915              * goes down.
916              */
917             mgr_launch_reply( g.serviceRecs[i] );
918             g.serviceRecs[i]->do_launch_reply = False;  /* it has been done */
919         }
920
921         if ( (g.serviceRecs[i]->pdm_exec_errorcode == g.pdm_start_ok) &&
922              (g.serviceRecs[i]->exit_received) &&
923              (g.serviceRecs[i]->message_pipe[0] == -1) ) {
924             /*
925              * Child is down, and since we sent a pdm_start_ok,
926              * we need to send a PDM_REPLY pdm_exit_* code too.
927              */
928             mgr_shutdown_reply( g.serviceRecs[i] );
929         }
930
931         if ( (g.serviceRecs[i]->exit_received) &&
932              (g.serviceRecs[i]->message_pipe[0] == -1) ) {
933             /*
934              * Child is down.  Log any final error messages
935              * from the child, and from the dtpdmd on behalf of
936              * the child.
937              */
938             if ( ((g.serviceRecs[i]->message_string) ||
939                   (g.serviceRecs[i]->message_string2)) && (g.log_file) ) {
940                 if ((errlog = fopen(g.log_file, "a+")) != NULL) {
941                     now = time((time_t)0);
942
943                     fprintf (errlog, PDMD_MSG_14, g.prog_name, ctime(&now),
944                                         g.serviceRecs[i]->pdm_exec_argvs[0],
945                                         g.serviceRecs[i]->print_display_str,
946                                         g.serviceRecs[i]->video_display_str,
947                                         g.serviceRecs[i]->exit_code,
948                                         g.serviceRecs[i]->message_string);
949
950                     if (g.serviceRecs[i]->message_string2) {
951                         fprintf (errlog, PDMD_MSG_15, g.serviceRecs[i]->message_string2);
952                     }
953
954                     fprintf (errlog, "\n");
955                     fclose(errlog);
956                 }
957                 else if (!errlog_problem_notice) {
958                     fprintf (stderr, PDMD_MSG_16, g.prog_name, g.log_file );
959                     fflush (stderr);
960                     errlog_problem_notice = 1;
961                 }
962             }
963
964             /*
965              * The child is done and can be cleaned up.
966              */
967             delete_rec( g.serviceRecs[i] );
968         }
969     }
970 }
971