Add GNU LGPL headers to all .c .C and .h files
[oweals/cde.git] / cde / lib / DtSvc / DtEncap / spc-net.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 /* $XConsortium: spc-net.c /main/9 1996/11/21 19:53:44 drk $
24  * File:         spc-net.c 
25  * Language:     C
26  *
27  * (c) Copyright 1989, Hewlett-Packard Company, all rights reserved.
28  *
29  * (c) Copyright 1993, 1994 Hewlett-Packard Company                     *
30  * (c) Copyright 1993, 1994 International Business Machines Corp.       *
31  * (c) Copyright 1993, 1994 Sun Microsystems, Inc.                      *
32  * (c) Copyright 1993, 1994 Novell, Inc.                                *
33  */
34
35 #define  __need_timeval
36 #define  __need_fd_set
37 #define  __need_all_errors
38
39 #include <bms/sbport.h> /* NOTE: sbport.h must be the first include. */
40 #include <errno.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43
44 #define X_INCLUDE_NETDB_H
45 #define XOS_USE_XT_LOCKING
46 #include <X11/Xos_r.h>
47
48 #include <SPC/spcP.h>
49 #include <bms/MemoryMgr.h>
50 #include <SPC/spc-proto.h>
51 #include "DtSvcLock.h"
52
53 extern int SPC_Initialized;
54
55 /*
56  ****
57  **** Client-side code
58  ****
59 */
60
61 /* Variables representing the local machine (initialized only once) */
62
63 static struct hostent *official_hp = NULL;
64 XeString official_hostname = NULL;
65
66 /*
67  * my_gethost will return a copy of the data returned by gethostbyname
68  *
69 */
70
71 /*----------------------------------------------------------------------+*/
72 static struct hostent *my_gethost(XeString hostname)
73 /*----------------------------------------------------------------------+*/
74 {
75   struct hostent *host_def, *copy;
76   int alias_count, i, addr_count, addrlen;
77   _Xgethostbynameparams host_buf;
78
79   host_def = _XGethostbyname(hostname, host_buf);
80   if (host_def == NULL)
81     return(FALSE);
82   
83   copy=(struct hostent *)XeMalloc(sizeof(struct hostent));
84   
85   /* Copy non-pointer info */
86   memcpy((char *)copy, (char *)host_def, sizeof(struct hostent));
87   
88   alias_count=0;
89
90   while(host_def->h_aliases[alias_count++]);
91
92   copy->h_aliases=(char **)XeMalloc(alias_count*(sizeof(XeString)));
93   
94   addr_count=0;
95   while(host_def->h_addr_list[addr_count++]);
96
97   copy->h_addr_list=(char **)XeMalloc(addr_count*(sizeof(XeString)));
98   
99   /* Copy Hostname */
100
101   copy->h_name=SPC_copy_string(host_def->h_name);
102
103   /* Copy the host address.  We do not use SPC_copy_string here,
104      because the address is not a string, and may have embedded
105      NULLs in it. */
106   
107   addrlen = host_def->h_length;
108   addr_count -= 1;
109   copy->h_addr_list[addr_count]=XeChar_NULL;
110   for (i=0; i < addr_count; i++) {
111     copy->h_addr_list[i]=(char *)XeMalloc(addrlen);
112     memcpy(copy->h_addr_list[i], host_def->h_addr_list[i], addrlen);
113   }
114   
115   while(alias_count--) {
116     copy->h_aliases[alias_count]=SPC_copy_string(host_def->h_aliases[alias_count]);
117   }
118
119   return(copy);
120 }
121                                  
122 /*
123  * SPC_Lookup_Host will try its darndest to return a hostent structure
124  * for the passed hostname.
125  *
126 */
127
128 /*----------------------------------------------------------------------+*/
129 static struct hostent *SPC_Lookup_Host(XeString hostname)
130 /*----------------------------------------------------------------------+*/
131 {
132
133   struct hostent *official_def;
134   
135   official_def = my_gethost(hostname);
136   if(!official_def) {
137     SPC_Error(SPC_Unknown_Host, hostname);
138     return(SPC_ERROR);
139   }
140
141   return(official_def);
142   
143 }
144
145 /*
146  *
147  * SPC_Init_Local_Host_Info will initialize the local host info.  It
148  * is intended to be called only once.
149  *
150 */
151
152 /*----------------------------------------------------------------------+*/
153 Boolean SPC_Init_Local_Host_Info(void)
154 /*----------------------------------------------------------------------+*/
155 {
156   _DtSvcProcessLock();
157   official_hostname=(XeString) XeMalloc(MAXHOSTNAMELEN+1);
158   
159   Xegethostname(official_hostname, MAXHOSTNAMELEN);
160   official_hostname[MAXHOSTNAMELEN]=0;
161   
162   if(!official_hp)
163     official_hp = SPC_Lookup_Host(official_hostname);
164
165   _DtSvcProcessUnlock();
166   return(official_hp != NULL);
167 }
168
169 /*
170  * SPC_Local_Hostname takes a string indicating a hostname, and returns
171  * TRUE if it represents a local host, and FALSE if it is remote.
172  */
173
174 /*----------------------------------------------------------------------+*/
175 SPC_Local_Hostname(XeString hostname)
176 /*----------------------------------------------------------------------+*/
177 {
178   /* Return TRUE if the specified hostname is local, otherwise it's remote */
179
180   /* If no hostname specified, then local by definition */
181
182   if (!hostname || !*hostname) return TRUE;
183
184 #ifdef DEBUG  
185   return(FALSE);
186 #endif
187
188   return(XeIsLocalHostP(hostname));
189 }
190
191 /*
192  *
193  * SPC_Open_Connection will a connection pointer to be used for any
194  * subsequent communication to the remote host.  It will either return
195  * an already opened connection, or create and initialize a new one.
196  *
197 */
198
199 /*----------------------------------------------------------------------+*/
200 SPC_Connection_Ptr SPC_Open_Connection(XeString hostname)
201 /*----------------------------------------------------------------------+*/
202 {
203   SPC_Connection_Ptr connection;
204   int seqno;
205   XeString canonical_hostname;
206   int tmp_errorno;
207
208   /* I was told that XeFindShortHost was the correct routine to use here,
209      but that may change in the future. */
210
211   canonical_hostname=XeFindShortHost(hostname);
212   
213   /* check for a currently open connection */
214   connection=SPC_Lookup_Connection(canonical_hostname);
215   if(connection) {
216     if(connection->connected) {
217       XeFree(canonical_hostname);
218       return(connection);
219     }
220     else {
221       SPC_Close_Connection(connection);
222       connection=NULL;
223     }
224   }
225       
226   /* None currently open.  Grab a new one & initialize it. */
227
228   if((connection = SPC_Make_Connection(canonical_hostname))==SPC_ERROR) {
229     SPC_Close_Connection(connection);
230     XeFree(canonical_hostname);
231     return(SPC_ERROR);
232   }
233   connection->local=official_hp;
234   if((connection->remote = SPC_Lookup_Host(canonical_hostname)) == SPC_ERROR) {
235     SPC_Close_Connection(connection);
236     XeFree(canonical_hostname);
237     return(SPC_ERROR);
238   }
239   
240   if(SPC_Contact_Server(connection)==SPC_ERROR) {
241     SPC_Close_Connection(connection);
242     XeFree(canonical_hostname);
243     return(SPC_ERROR);
244   }
245
246   connection->connected=TRUE;
247   
248   if(SPC_Validate_User(canonical_hostname, connection)==SPC_ERROR) {
249     SPC_Close_Connection(connection);
250     XeFree(canonical_hostname);
251     return(SPC_ERROR);
252   }
253
254   seqno=SPC_Write_Protocol_Request(connection, NULL, ENVIRON_RESET);
255   _DtSvcProcessLock();
256   tmp_errorno = XeSPCErrorNumber;
257   if(SPC_Waitfor_Reply(connection, NULL, seqno) == SPC_ERROR) {
258     SPC_Close_Connection(connection);
259     /*
260      * XeSPCErrorNumber could have been changed but want to
261      * return the value from Write_Protocol_Request to the 
262      * client.
263      */
264     if (tmp_errorno != 0)
265       XeSPCErrorNumber = tmp_errorno;
266     XeFree(canonical_hostname);
267     _DtSvcProcessUnlock();
268     return(SPC_ERROR);
269   }
270   _DtSvcProcessUnlock();
271
272   /* We no long ever send a RESET_TERMIO request as this was hpux */
273   /* specific and VERY non-portable.                              */
274
275   if (connection->protocol_version >= 2) {
276       seqno=SPC_Write_Protocol_Request(connection, NULL, RESET_TERMIOS);
277       if(SPC_Waitfor_Reply(connection, NULL, seqno) == SPC_ERROR) {
278           SPC_Close_Connection(connection);
279           XeFree(canonical_hostname);
280           return(SPC_ERROR);
281       }
282   }
283   
284   XeFree(canonical_hostname);
285   return(connection);
286   
287 }
288
289 /*----------------------------------------------------------------------+*/
290 SPC_Open_Socket(SPC_Connection_Ptr conn,
291                 int type)
292 /*----------------------------------------------------------------------+*/
293 {
294
295   struct servent *service;
296   
297   conn->sid=socket(type, SOCK_STREAM, NULL);
298   if(conn->sid == ERROR) {
299     SPC_Error(SPC_Bad_Socket);
300     return(SPC_ERROR);
301   }
302   
303   service=getservbyname(SPC_SERVICE, SPC_PROTOCOL);
304   if (!service) {
305     SPC_Error(SPC_Bad_Service, SPC_SERVICE, SPC_PROTOCOL);
306     return(FALSE);
307   }
308
309   return(service->s_port);
310 }
311
312
313 /*
314  *
315  * SPC_Contact_Server will attempt to contact the server specified by
316  * the passed connection data structure.  IT ASSUMES THAT ALL FIELDS
317  * EXCEPT THE SOCKET ID ARE FILLED IN!!!
318  *
319 */
320
321 /*----------------------------------------------------------------------+*/
322 SPC_Contact_Server(SPC_Connection_Ptr connection)
323 /*----------------------------------------------------------------------+*/
324 {
325   struct sockaddr_in saddr;
326   short addrtype;
327   struct hostent *remote;
328   
329   
330   /* Check that the connection is initialized correctly */
331   if(!connection)
332     return(SPC_ERROR);
333   if(!(remote=connection->remote))
334     return(SPC_ERROR);
335   if(connection->connected)
336     return(TRUE);
337   
338   addrtype=saddr.sin_family=remote->h_addrtype;
339   if(!(saddr.sin_port=SPC_Open_Socket(connection, addrtype)))
340     return(SPC_ERROR);
341   memcpy(&saddr.sin_addr, remote->h_addr, remote->h_length);
342
343   if(connect(connection->sid, (struct sockaddr *)&saddr, sizeof(saddr)) == ERROR) {
344     SPC_Error(SPC_Bad_Connect,
345               XeFindShortHost(remote->h_name));
346     return(SPC_ERROR);
347   }
348
349   return(TRUE);
350 }
351
352 /*
353  ****
354  **** Server (daemon) side code
355  ****
356 */ 
357
358 #define BACKLOG                  50
359 #define MAX_SERVER_BIND_ATTEMPTS 30
360 #define SERVER_PAUSE_INTERVAL    10
361
362 /*----------------------------------------------------------------------+*/
363 SPC_Connection_Ptr SPC_Init_Child(SPC_Connection_Ptr conn,
364                                   int from)
365 /*----------------------------------------------------------------------+*/
366 {
367   /* We are the child.  Close the connection file descriptor
368      (which is the socket, not our input). */
369   close(conn->sid);
370
371   /* Make the from file descriptor correspond to STDIN/STDOUT */
372   dup2(from, STDIN);
373   close(from);
374   dup2(STDIN, STDOUT);
375
376   /* make conn point to STDIN */
377   
378   conn->sid=STDIN;
379
380   return(conn);
381 }
382
383 SPC_Connection_Ptr SPC_Standalone_Daemon(SPC_Connection_Ptr conn)
384 {
385   struct sockaddr_in saddr, client_saddr;
386 #ifdef USL
387   /* Only UnixWare 2.02 uses the Spec1170 parameter profile for accept(). */
388   size_t len=sizeof(client_saddr);
389 #else
390   int len=sizeof(client_saddr);
391 #endif
392   int server_bind_attempts      = MAX_SERVER_BIND_ATTEMPTS;
393   int server_bind_pause         = SERVER_PAUSE_INTERVAL;
394   int pid, from;
395 #if defined(__aix)
396   int on=1;                               /* required by setsockopt */
397 #endif
398
399   saddr.sin_family=AF_INET;
400   if(!(saddr.sin_port=SPC_Open_Socket(conn, saddr.sin_family)))
401     return(SPC_ERROR);
402   saddr.sin_addr.s_addr=INADDR_ANY; /* Any host address */
403
404   /* Reuse the socket address if it is still in a timeout state */
405
406 #if defined(__aix)
407   if (setsockopt(conn->sid, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))==ERROR) {
408 #else
409   if (setsockopt(conn->sid, SOL_SOCKET, SO_REUSEADDR, NULL, NULL)==ERROR) {
410 #endif
411     SPC_Error(SPC_Bad_Reuse);
412     return(SPC_ERROR);
413   }
414
415   while (bind(conn->sid, (struct sockaddr *)&saddr, sizeof(saddr)) == ERROR) {
416     if (errno == EADDRINUSE) {
417       SPC_Error(SPC_Bind_Timeout);
418       /* Try to get the connection in a little while */
419       if (server_bind_attempts > 0) {
420         server_bind_attempts--;
421         sleep(server_bind_pause);
422       }
423       else {
424         /* We don't want to wait forever */
425         SPC_Error(SPC_Timeout);
426         return(SPC_ERROR);
427       }
428     } else {
429       SPC_Error(SPC_Bad_Bind);
430       return(SPC_ERROR);
431     }
432   }
433
434   /* Set up a queue for incoming connection requests */
435
436   listen(conn->sid, BACKLOG);
437
438   /* We are running standalone, so we need to loop forever waiting for
439      requests.  When we get one, we will fork a child to take care of
440      the processing for us, and then the parent will listen some more */
441
442   for(;;) {
443     struct hostent              *addr_ret;
444     _Xgethostbynameparams       addr_buf;
445
446     /* Attempt to accept a connection with a client */
447     
448     from = accept(conn->sid, (struct sockaddr *)&client_saddr, &len);
449     if (from == ERROR) {
450       SPC_Error(SPC_Bad_Accept);
451       return(SPC_ERROR);
452     }
453     
454     addr_ret = _XGethostbyaddr((char *)&client_saddr.sin_addr,
455                                sizeof(client_saddr.sin_addr),
456                                client_saddr.sin_family,
457                                addr_buf);
458
459     conn->remote = addr_ret;
460     strncpy(conn->hostname, conn->remote->h_name, MAXHOSTNAMELEN);
461
462 #ifdef DEBUG
463     pid = NULL;
464 #else    
465     /* Fork a process to handle I/O from/to client */
466     pid = fork();
467 #endif
468     
469     if (pid == ERROR) {
470       SPC_Error(SPC_Cannot_Fork);
471       /* We don't return here, but simply go around for a new try */
472     }
473
474     if (!pid)
475       /* We are the child.  Do whatever processing we need to do
476          on the connection & return */
477       return(SPC_Init_Child(conn, from));
478     /* Otherwise, we are still the parent.  Loop around for another
479        connection request */
480   }
481 }
482
483 /*----------------------------------------------------------------------+*/
484 SPC_Inetd_Daemon(SPC_Connection_Ptr conn)
485 /*----------------------------------------------------------------------+*/
486 {
487   conn->sid=0;
488   return(TRUE);
489 }
490
491 /*----------------------------------------------------------------------+*/
492 SPC_Connection_Ptr SPC_Start_Daemon(int standalone)
493 /*----------------------------------------------------------------------+*/
494 {
495
496   SPC_Connection_Ptr connection;
497
498   /* Do whatever it takes to initialize SPC */
499   _DtSvcProcessLock();
500   if (!SPC_Initialized)
501       if(SPC_Initialize()==SPC_ERROR) {
502           _DtSvcProcessUnlock();
503           return(SPC_ERROR);
504       }
505   _DtSvcProcessUnlock();
506
507   /* Get ourselves a connection structure.  We don't know the name
508      of the remote client yet, so use the null string as hostname */
509
510   if((connection=SPC_Make_Connection(NULL))==SPC_ERROR)
511     return(SPC_ERROR);
512   connection->local=official_hp;
513   if(standalone) {
514     if((SPC_Standalone_Daemon(connection))==SPC_ERROR)
515       return(SPC_ERROR);
516   } else {
517     if((SPC_Inetd_Daemon(connection))==SPC_ERROR)
518       return(SPC_ERROR);
519   }
520   connection->connected=TRUE;
521   return(connection);
522 }