r6149: Fixes bugs #2498 and 2484.
[kai/samba.git] / source3 / nsswitch / wb_common.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    winbind client common code
5
6    Copyright (C) Tim Potter 2000
7    Copyright (C) Andrew Tridgell 2000
8    Copyright (C) Andrew Bartlett 2002
9    
10    
11    This library is free software; you can redistribute it and/or
12    modify it under the terms of the GNU Library General Public
13    License as published by the Free Software Foundation; either
14    version 2 of the License, or (at your option) any later version.
15    
16    This library is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19    Library General Public License for more details.
20    
21    You should have received a copy of the GNU Library General Public
22    License along with this library; if not, write to the
23    Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24    Boston, MA  02111-1307, USA.   
25 */
26
27 #include "winbind_client.h"
28
29 #define CONST_DISCARD(type, ptr)      ((type) ((void *) (ptr)))
30 #define CONST_ADD(type, ptr)          ((type) ((const void *) (ptr)))
31
32 /* Global variables.  These are effectively the client state information */
33
34 int winbindd_fd = -1;           /* fd for winbindd socket */
35
36 /* Free a response structure */
37
38 void free_response(struct winbindd_response *response)
39 {
40         /* Free any allocated extra_data */
41
42         if (response)
43                 SAFE_FREE(response->extra_data);
44 }
45
46 /* Initialise a request structure */
47
48 void init_request(struct winbindd_request *request, int request_type)
49 {
50         request->length = sizeof(struct winbindd_request);
51
52         request->cmd = (enum winbindd_cmd)request_type;
53         request->pid = getpid();
54
55 }
56
57 /* Initialise a response structure */
58
59 void init_response(struct winbindd_response *response)
60 {
61         /* Initialise return value */
62
63         response->result = WINBINDD_ERROR;
64 }
65
66 /* Close established socket */
67
68 void close_sock(void)
69 {
70         if (winbindd_fd != -1) {
71                 close(winbindd_fd);
72                 winbindd_fd = -1;
73         }
74 }
75
76 #define CONNECT_TIMEOUT 30
77 #define WRITE_TIMEOUT CONNECT_TIMEOUT
78 #define READ_TIMEOUT CONNECT_TIMEOUT
79
80 /* Make sure socket handle isn't stdin, stdout or stderr */
81 #define RECURSION_LIMIT 3
82
83 static int make_nonstd_fd_internals(int fd, int limit /* Recursion limiter */) 
84 {
85         int new_fd;
86         if (fd >= 0 && fd <= 2) {
87 #ifdef F_DUPFD 
88                 if ((new_fd = fcntl(fd, F_DUPFD, 3)) == -1) {
89                         return -1;
90                 }
91                 /* Paranoia */
92                 if (new_fd < 3) {
93                         close(new_fd);
94                         return -1;
95                 }
96                 close(fd);
97                 return new_fd;
98 #else
99                 if (limit <= 0)
100                         return -1;
101                 
102                 new_fd = dup(fd);
103                 if (new_fd == -1) 
104                         return -1;
105
106                 /* use the program stack to hold our list of FDs to close */
107                 new_fd = make_nonstd_fd_internals(new_fd, limit - 1);
108                 close(fd);
109                 return new_fd;
110 #endif
111         }
112         return fd;
113 }
114
115 /****************************************************************************
116  Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
117  else
118  if SYSV use O_NDELAY
119  if BSD use FNDELAY
120  Set close on exec also.
121 ****************************************************************************/
122
123 static int make_safe_fd(int fd) 
124 {
125         int result, flags;
126         int new_fd = make_nonstd_fd_internals(fd, RECURSION_LIMIT);
127         if (new_fd == -1) {
128                 close(fd);
129                 return -1;
130         }
131
132         /* Socket should be nonblocking. */
133 #ifdef O_NONBLOCK
134 #define FLAG_TO_SET O_NONBLOCK
135 #else
136 #ifdef SYSV
137 #define FLAG_TO_SET O_NDELAY
138 #else /* BSD */
139 #define FLAG_TO_SET FNDELAY
140 #endif
141 #endif
142
143         if ((flags = fcntl(new_fd, F_GETFL)) == -1) {
144                 close(new_fd);
145                 return -1;
146         }
147
148         flags |= FLAG_TO_SET;
149         if (fcntl(new_fd, F_SETFL, flags) == -1) {
150                 close(new_fd);
151                 return -1;
152         }
153
154 #undef FLAG_TO_SET
155
156         /* Socket should be closed on exec() */
157 #ifdef FD_CLOEXEC
158         result = flags = fcntl(new_fd, F_GETFD, 0);
159         if (flags >= 0) {
160                 flags |= FD_CLOEXEC;
161                 result = fcntl( new_fd, F_SETFD, flags );
162         }
163         if (result < 0) {
164                 close(new_fd);
165                 return -1;
166         }
167 #endif
168         return new_fd;
169 }
170
171 /* Connect to winbindd socket */
172
173 static int winbind_named_pipe_sock(const char *dir)
174 {
175         struct sockaddr_un sunaddr;
176         struct stat st;
177         pstring path;
178         int fd;
179         int wait_time;
180         int slept;
181         
182         /* Check permissions on unix socket directory */
183         
184         if (lstat(dir, &st) == -1) {
185                 return -1;
186         }
187         
188         if (!S_ISDIR(st.st_mode) || 
189             (st.st_uid != 0 && st.st_uid != geteuid())) {
190                 return -1;
191         }
192         
193         /* Connect to socket */
194         
195         strncpy(path, dir, sizeof(path) - 1);
196         path[sizeof(path) - 1] = '\0';
197         
198         strncat(path, "/", sizeof(path) - 1 - strlen(path));
199         path[sizeof(path) - 1] = '\0';
200         
201         strncat(path, WINBINDD_SOCKET_NAME, sizeof(path) - 1 - strlen(path));
202         path[sizeof(path) - 1] = '\0';
203         
204         ZERO_STRUCT(sunaddr);
205         sunaddr.sun_family = AF_UNIX;
206         strncpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path) - 1);
207         
208         /* If socket file doesn't exist, don't bother trying to connect
209            with retry.  This is an attempt to make the system usable when
210            the winbindd daemon is not running. */
211
212         if (lstat(path, &st) == -1) {
213                 return -1;
214         }
215         
216         /* Check permissions on unix socket file */
217         
218         if (!S_ISSOCK(st.st_mode) || 
219             (st.st_uid != 0 && st.st_uid != geteuid())) {
220                 return -1;
221         }
222         
223         /* Connect to socket */
224         
225         if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
226                 return -1;
227         }
228
229         /* Set socket non-blocking and close on exec. */
230
231         if ((fd = make_safe_fd( fd)) == -1) {
232                 return fd;
233         }
234
235         for (wait_time = 0; connect(fd, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1;
236                         wait_time += slept) {
237                 struct timeval tv;
238                 fd_set w_fds;
239                 int ret;
240                 int connect_errno = 0, errnosize;
241
242                 if (wait_time >= CONNECT_TIMEOUT)
243                         goto error_out;
244
245                 switch (errno) {
246                         case EINPROGRESS:
247                                 FD_ZERO(&w_fds);
248                                 FD_SET(fd, &w_fds);
249                                 tv.tv_sec = CONNECT_TIMEOUT - wait_time;
250                                 tv.tv_usec = 0;
251
252                                 ret = select(fd + 1, NULL, &w_fds, NULL, &tv);
253
254                                 if (ret > 0) {
255                                         errnosize = sizeof(connect_errno);
256
257                                         ret = getsockopt(fd, SOL_SOCKET,
258                                                         SO_ERROR, &connect_errno, &errnosize);
259
260                                         if (ret >= 0 && connect_errno == 0) {
261                                                 /* Connect succeed */
262                                                 goto out;
263                                         }
264                                 }
265
266                                 slept = CONNECT_TIMEOUT;
267                                 break;
268                         case EAGAIN:
269                                 slept = rand() % 3 + 1;
270                                 sleep(slept);
271                                 break;
272                         default:
273                                 goto error_out;
274                 }
275
276         }
277
278   out:
279
280         return fd;
281
282   error_out:
283
284         close(fd);
285         return -1;
286
287         if (connect(fd, (struct sockaddr *)&sunaddr, 
288                     sizeof(sunaddr)) == -1) {
289                 close(fd);
290                 return -1;
291         }
292         
293         return fd;
294 }
295
296 /* Connect to winbindd socket */
297
298 int winbind_open_pipe_sock(void)
299 {
300 #ifdef HAVE_UNIXSOCKET
301         static pid_t our_pid;
302         struct winbindd_request request;
303         struct winbindd_response response;
304         ZERO_STRUCT(request);
305         ZERO_STRUCT(response);
306
307         if (our_pid != getpid()) {
308                 close_sock();
309                 our_pid = getpid();
310         }
311         
312         if (winbindd_fd != -1) {
313                 return winbindd_fd;
314         }
315
316         if ((winbindd_fd = winbind_named_pipe_sock(WINBINDD_SOCKET_DIR)) == -1) {
317                 return -1;
318         }
319
320         /* version-check the socket */
321
322         if ((winbindd_request(WINBINDD_INTERFACE_VERSION, &request, &response) != NSS_STATUS_SUCCESS) || (response.data.interface_version != WINBIND_INTERFACE_VERSION)) {
323                 close_sock();
324                 return -1;
325         }
326
327         /* try and get priv pipe */
328
329         if (winbindd_request(WINBINDD_PRIV_PIPE_DIR, &request, &response) == NSS_STATUS_SUCCESS) {
330                 int fd;
331                 if ((fd = winbind_named_pipe_sock(response.extra_data)) != -1) {
332                         close(winbindd_fd);
333                         winbindd_fd = fd;
334                 }
335         }
336
337         SAFE_FREE(response.extra_data);
338
339         return winbindd_fd;
340 #else
341         return -1;
342 #endif /* HAVE_UNIXSOCKET */
343 }
344
345 /* Write data to winbindd socket */
346
347 int write_sock(void *buffer, int count)
348 {
349         int result, nwritten;
350         
351         /* Open connection to winbind daemon */
352         
353  restart:
354         
355         if (winbind_open_pipe_sock() == -1) {
356                 return -1;
357         }
358         
359         /* Write data to socket */
360         
361         nwritten = 0;
362         
363         while(nwritten < count) {
364                 struct timeval tv;
365                 fd_set r_fds;
366                 
367                 /* Catch pipe close on other end by checking if a read()
368                    call would not block by calling select(). */
369
370                 FD_ZERO(&r_fds);
371                 FD_SET(winbindd_fd, &r_fds);
372                 ZERO_STRUCT(tv);
373                 
374                 if (select(winbindd_fd + 1, &r_fds, NULL, NULL, &tv) == -1) {
375                         close_sock();
376                         return -1;                   /* Select error */
377                 }
378                 
379                 /* Write should be OK if fd not available for reading */
380                 
381                 if (!FD_ISSET(winbindd_fd, &r_fds)) {
382                         
383                         /* Do the write */
384                         
385                         result = write(winbindd_fd,
386                                        (char *)buffer + nwritten, 
387                                        count - nwritten);
388                         
389                         if ((result == -1) || (result == 0)) {
390                                 
391                                 /* Write failed */
392                                 
393                                 close_sock();
394                                 return -1;
395                         }
396                         
397                         nwritten += result;
398                         
399                 } else {
400                         
401                         /* Pipe has closed on remote end */
402                         
403                         close_sock();
404                         goto restart;
405                 }
406         }
407         
408         return nwritten;
409 }
410
411 /* Read data from winbindd socket */
412
413 static int read_sock(void *buffer, int count)
414 {
415         int result = 0, nread = 0;
416         int total_time = 0, selret;
417
418         /* Read data from socket */
419         while(nread < count) {
420                 struct timeval tv;
421                 fd_set r_fds;
422                 
423                 /* Catch pipe close on other end by checking if a read()
424                    call would not block by calling select(). */
425
426                 FD_ZERO(&r_fds);
427                 FD_SET(winbindd_fd, &r_fds);
428                 ZERO_STRUCT(tv);
429                 /* Wait for 5 seconds for a reply. May need to parameterise this... */
430                 tv.tv_sec = 5;
431
432                 if ((selret = select(winbindd_fd + 1, &r_fds, NULL, NULL, &tv)) == -1) {
433                         close_sock();
434                         return -1;                   /* Select error */
435                 }
436                 
437                 if (selret == 0) {
438                         /* Not ready for read yet... */
439                         if (total_time >= 30) {
440                                 /* Timeout */
441                                 close_sock();
442                                 return -1;
443                         }
444                         total_time += 5;
445                         continue;
446                 }
447
448                 if (FD_ISSET(winbindd_fd, &r_fds)) {
449                         
450                         /* Do the Read */
451                         
452                         result = read(winbindd_fd, (char *)buffer + nread, 
453                               count - nread);
454                         
455                         if ((result == -1) || (result == 0)) {
456                                 
457                                 /* Read failed.  I think the only useful thing we
458                                    can do here is just return -1 and fail since the
459                                    transaction has failed half way through. */
460                         
461                                 close_sock();
462                                 return -1;
463                         }
464                         
465                         nread += result;
466                         
467                 }
468         }
469         
470         return result;
471 }
472
473 /* Read reply */
474
475 int read_reply(struct winbindd_response *response)
476 {
477         int result1, result2 = 0;
478
479         if (!response) {
480                 return -1;
481         }
482         
483         /* Read fixed length response */
484         
485         if ((result1 = read_sock(response, sizeof(struct winbindd_response)))
486             == -1) {
487                 
488                 return -1;
489         }
490         
491         /* We actually send the pointer value of the extra_data field from
492            the server.  This has no meaning in the client's address space
493            so we clear it out. */
494
495         response->extra_data = NULL;
496
497         /* Read variable length response */
498         
499         if (response->length > sizeof(struct winbindd_response)) {
500                 int extra_data_len = response->length - 
501                         sizeof(struct winbindd_response);
502                 
503                 /* Mallocate memory for extra data */
504                 
505                 if (!(response->extra_data = malloc(extra_data_len))) {
506                         return -1;
507                 }
508                 
509                 if ((result2 = read_sock(response->extra_data, extra_data_len))
510                     == -1) {
511                         free_response(response);
512                         return -1;
513                 }
514         }
515         
516         /* Return total amount of data read */
517         
518         return result1 + result2;
519 }
520
521 /* 
522  * send simple types of requests 
523  */
524
525 NSS_STATUS winbindd_send_request(int req_type, struct winbindd_request *request)
526 {
527         struct winbindd_request lrequest;
528         char *env;
529         int  value;
530         
531         /* Check for our tricky environment variable */
532
533         if ( (env = getenv(WINBINDD_DONT_ENV)) != NULL ) {
534                 value = atoi(env);
535                 if ( value == 1 )
536                         return NSS_STATUS_NOTFOUND;
537         }
538
539         if (!request) {
540                 ZERO_STRUCT(lrequest);
541                 request = &lrequest;
542         }
543         
544         /* Fill in request and send down pipe */
545
546         init_request(request, req_type);
547         
548         if (write_sock(request, sizeof(*request)) == -1) {
549                 return NSS_STATUS_UNAVAIL;
550         }
551         
552         return NSS_STATUS_SUCCESS;
553 }
554
555 /*
556  * Get results from winbindd request
557  */
558
559 NSS_STATUS winbindd_get_response(struct winbindd_response *response)
560 {
561         struct winbindd_response lresponse;
562
563         if (!response) {
564                 ZERO_STRUCT(lresponse);
565                 response = &lresponse;
566         }
567
568         init_response(response);
569
570         /* Wait for reply */
571         if (read_reply(response) == -1) {
572                 return NSS_STATUS_UNAVAIL;
573         }
574
575         /* Throw away extra data if client didn't request it */
576         if (response == &lresponse) {
577                 free_response(response);
578         }
579
580         /* Copy reply data from socket */
581         if (response->result != WINBINDD_OK) {
582                 return NSS_STATUS_NOTFOUND;
583         }
584         
585         return NSS_STATUS_SUCCESS;
586 }
587
588 /* Handle simple types of requests */
589
590 NSS_STATUS winbindd_request(int req_type, 
591                             struct winbindd_request *request,
592                             struct winbindd_response *response)
593 {
594         NSS_STATUS status;
595
596         status = winbindd_send_request(req_type, request);
597         if (status != NSS_STATUS_SUCCESS) 
598                 return(status);
599         return winbindd_get_response(response);
600 }
601
602 /*************************************************************************
603  A couple of simple functions to disable winbindd lookups and re-
604  enable them
605  ************************************************************************/
606  
607 /* Use putenv() instead of setenv() in these functions as not all
608    environments have the latter. */
609
610 BOOL winbind_off( void )
611 {
612         static char *s = CONST_DISCARD(char *, WINBINDD_DONT_ENV "=1");
613
614         return putenv(s) != -1;
615 }
616
617 BOOL winbind_on( void )
618 {
619         static char *s = CONST_DISCARD(char *, WINBINDD_DONT_ENV "=0");
620
621         return putenv(s) != -1;
622 }