s3: Slightly simplify winbind_write_sock
[nivanova/samba-autobuild/.git] / 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 Lesser General Public
13    License as published by the Free Software Foundation; either
14    version 3 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 Lesser General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #include "winbind_client.h"
26
27 /* Global variables.  These are effectively the client state information */
28
29 int winbindd_fd = -1;           /* fd for winbindd socket */
30 static int is_privileged = 0;
31
32 /* Free a response structure */
33
34 void winbindd_free_response(struct winbindd_response *response)
35 {
36         /* Free any allocated extra_data */
37
38         if (response)
39                 SAFE_FREE(response->extra_data.data);
40 }
41
42 /* Initialise a request structure */
43
44 static void winbindd_init_request(struct winbindd_request *request,
45                                   int request_type)
46 {
47         request->length = sizeof(struct winbindd_request);
48
49         request->cmd = (enum winbindd_cmd)request_type;
50         request->pid = getpid();
51
52 }
53
54 /* Initialise a response structure */
55
56 static void init_response(struct winbindd_response *response)
57 {
58         /* Initialise return value */
59
60         response->result = WINBINDD_ERROR;
61 }
62
63 /* Close established socket */
64
65 #if HAVE_FUNCTION_ATTRIBUTE_DESTRUCTOR
66 __attribute__((destructor))
67 #endif
68 static void winbind_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
78 /* Make sure socket handle isn't stdin, stdout or stderr */
79 #define RECURSION_LIMIT 3
80
81 static int make_nonstd_fd_internals(int fd, int limit /* Recursion limiter */)
82 {
83         int new_fd;
84         if (fd >= 0 && fd <= 2) {
85 #ifdef F_DUPFD
86                 if ((new_fd = fcntl(fd, F_DUPFD, 3)) == -1) {
87                         return -1;
88                 }
89                 /* Paranoia */
90                 if (new_fd < 3) {
91                         close(new_fd);
92                         return -1;
93                 }
94                 close(fd);
95                 return new_fd;
96 #else
97                 if (limit <= 0)
98                         return -1;
99
100                 new_fd = dup(fd);
101                 if (new_fd == -1)
102                         return -1;
103
104                 /* use the program stack to hold our list of FDs to close */
105                 new_fd = make_nonstd_fd_internals(new_fd, limit - 1);
106                 close(fd);
107                 return new_fd;
108 #endif
109         }
110         return fd;
111 }
112
113 /****************************************************************************
114  Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
115  else
116  if SYSV use O_NDELAY
117  if BSD use FNDELAY
118  Set close on exec also.
119 ****************************************************************************/
120
121 static int make_safe_fd(int fd)
122 {
123         int result, flags;
124         int new_fd = make_nonstd_fd_internals(fd, RECURSION_LIMIT);
125         if (new_fd == -1) {
126                 close(fd);
127                 return -1;
128         }
129
130         /* Socket should be nonblocking. */
131 #ifdef O_NONBLOCK
132 #define FLAG_TO_SET O_NONBLOCK
133 #else
134 #ifdef SYSV
135 #define FLAG_TO_SET O_NDELAY
136 #else /* BSD */
137 #define FLAG_TO_SET FNDELAY
138 #endif
139 #endif
140
141         if ((flags = fcntl(new_fd, F_GETFL)) == -1) {
142                 close(new_fd);
143                 return -1;
144         }
145
146         flags |= FLAG_TO_SET;
147         if (fcntl(new_fd, F_SETFL, flags) == -1) {
148                 close(new_fd);
149                 return -1;
150         }
151
152 #undef FLAG_TO_SET
153
154         /* Socket should be closed on exec() */
155 #ifdef FD_CLOEXEC
156         result = flags = fcntl(new_fd, F_GETFD, 0);
157         if (flags >= 0) {
158                 flags |= FD_CLOEXEC;
159                 result = fcntl( new_fd, F_SETFD, flags );
160         }
161         if (result < 0) {
162                 close(new_fd);
163                 return -1;
164         }
165 #endif
166         return new_fd;
167 }
168
169 /* Connect to winbindd socket */
170
171 static int winbind_named_pipe_sock(const char *dir)
172 {
173         struct sockaddr_un sunaddr;
174         struct stat st;
175         char *path = NULL;
176         int fd;
177         int wait_time;
178         int slept;
179
180         /* Check permissions on unix socket directory */
181
182         if (lstat(dir, &st) == -1) {
183                 errno = ENOENT;
184                 return -1;
185         }
186
187         if (!S_ISDIR(st.st_mode) ||
188             (st.st_uid != 0 && st.st_uid != geteuid())) {
189                 errno = ENOENT;
190                 return -1;
191         }
192
193         /* Connect to socket */
194
195         if (asprintf(&path, "%s/%s", dir, WINBINDD_SOCKET_NAME) < 0) {
196                 return -1;
197         }
198
199         ZERO_STRUCT(sunaddr);
200         sunaddr.sun_family = AF_UNIX;
201         strncpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path) - 1);
202
203         /* If socket file doesn't exist, don't bother trying to connect
204            with retry.  This is an attempt to make the system usable when
205            the winbindd daemon is not running. */
206
207         if (lstat(path, &st) == -1) {
208                 errno = ENOENT;
209                 SAFE_FREE(path);
210                 return -1;
211         }
212
213         SAFE_FREE(path);
214         /* Check permissions on unix socket file */
215
216         if (!S_ISSOCK(st.st_mode) ||
217             (st.st_uid != 0 && st.st_uid != geteuid())) {
218                 errno = ENOENT;
219                 return -1;
220         }
221
222         /* Connect to socket */
223
224         if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
225                 return -1;
226         }
227
228         /* Set socket non-blocking and close on exec. */
229
230         if ((fd = make_safe_fd( fd)) == -1) {
231                 return fd;
232         }
233
234         for (wait_time = 0; connect(fd, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1;
235                         wait_time += slept) {
236                 struct timeval tv;
237                 fd_set w_fds;
238                 int ret;
239                 int connect_errno = 0;
240                 socklen_t 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
288 static const char *winbindd_socket_dir(void)
289 {
290 #ifdef SOCKET_WRAPPER
291         const char *env_dir;
292
293         env_dir = getenv(WINBINDD_SOCKET_DIR_ENVVAR);
294         if (env_dir) {
295                 return env_dir;
296         }
297 #endif
298
299         return WINBINDD_SOCKET_DIR;
300 }
301
302 /* Connect to winbindd socket */
303
304 static int winbind_open_pipe_sock(int recursing, int need_priv)
305 {
306 #ifdef HAVE_UNIXSOCKET
307         static pid_t our_pid;
308         struct winbindd_request request;
309         struct winbindd_response response;
310         ZERO_STRUCT(request);
311         ZERO_STRUCT(response);
312
313         if (our_pid != getpid()) {
314                 winbind_close_sock();
315                 our_pid = getpid();
316         }
317
318         if ((need_priv != 0) && (is_privileged == 0)) {
319                 winbind_close_sock();
320         }
321
322         if (winbindd_fd != -1) {
323                 return winbindd_fd;
324         }
325
326         if (recursing) {
327                 return -1;
328         }
329
330         if ((winbindd_fd = winbind_named_pipe_sock(winbindd_socket_dir())) == -1) {
331                 return -1;
332         }
333
334         is_privileged = 0;
335
336         /* version-check the socket */
337
338         request.wb_flags = WBFLAG_RECURSE;
339         if ((winbindd_request_response(WINBINDD_INTERFACE_VERSION, &request, &response) != NSS_STATUS_SUCCESS) || (response.data.interface_version != WINBIND_INTERFACE_VERSION)) {
340                 winbind_close_sock();
341                 return -1;
342         }
343
344         /* try and get priv pipe */
345
346         request.wb_flags = WBFLAG_RECURSE;
347         if (winbindd_request_response(WINBINDD_PRIV_PIPE_DIR, &request, &response) == NSS_STATUS_SUCCESS) {
348                 int fd;
349                 if ((fd = winbind_named_pipe_sock((char *)response.extra_data.data)) != -1) {
350                         close(winbindd_fd);
351                         winbindd_fd = fd;
352                         is_privileged = 1;
353                 }
354         }
355
356         if ((need_priv != 0) && (is_privileged == 0)) {
357                 return -1;
358         }
359
360         SAFE_FREE(response.extra_data.data);
361
362         return winbindd_fd;
363 #else
364         return -1;
365 #endif /* HAVE_UNIXSOCKET */
366 }
367
368 /* Write data to winbindd socket */
369
370 static int winbind_write_sock(void *buffer, int count, int recursing,
371                               int need_priv)
372 {
373         int result, nwritten;
374
375         /* Open connection to winbind daemon */
376
377  restart:
378
379         if (winbind_open_pipe_sock(recursing, need_priv) == -1) {
380                 errno = ENOENT;
381                 return -1;
382         }
383
384         /* Write data to socket */
385
386         nwritten = 0;
387
388         while(nwritten < count) {
389                 struct timeval tv;
390                 fd_set r_fds;
391
392                 /* Catch pipe close on other end by checking if a read()
393                    call would not block by calling select(). */
394
395                 FD_ZERO(&r_fds);
396                 FD_SET(winbindd_fd, &r_fds);
397                 ZERO_STRUCT(tv);
398
399                 if (select(winbindd_fd + 1, &r_fds, NULL, NULL, &tv) == -1) {
400                         winbind_close_sock();
401                         return -1;                   /* Select error */
402                 }
403
404                 /* Write should be OK if fd not available for reading */
405
406                 if (FD_ISSET(winbindd_fd, &r_fds)) {
407
408                         /* Pipe has closed on remote end */
409
410                         winbind_close_sock();
411                         goto restart;
412                 }
413
414                 /* Do the write */
415
416                 result = write(winbindd_fd,
417                                (char *)buffer + nwritten,
418                                count - nwritten);
419
420                 if ((result == -1) || (result == 0)) {
421
422                         /* Write failed */
423
424                         winbind_close_sock();
425                         return -1;
426                 }
427
428                 nwritten += result;
429         }
430
431         return nwritten;
432 }
433
434 /* Read data from winbindd socket */
435
436 static int winbind_read_sock(void *buffer, int count)
437 {
438         int nread = 0;
439         int total_time = 0, selret;
440
441         if (winbindd_fd == -1) {
442                 return -1;
443         }
444
445         /* Read data from socket */
446         while(nread < count) {
447                 struct timeval tv;
448                 fd_set r_fds;
449
450                 /* Catch pipe close on other end by checking if a read()
451                    call would not block by calling select(). */
452
453                 FD_ZERO(&r_fds);
454                 FD_SET(winbindd_fd, &r_fds);
455                 ZERO_STRUCT(tv);
456                 /* Wait for 5 seconds for a reply. May need to parameterise this... */
457                 tv.tv_sec = 5;
458
459                 if ((selret = select(winbindd_fd + 1, &r_fds, NULL, NULL, &tv)) == -1) {
460                         winbind_close_sock();
461                         return -1;                   /* Select error */
462                 }
463
464                 if (selret == 0) {
465                         /* Not ready for read yet... */
466                         if (total_time >= 30) {
467                                 /* Timeout */
468                                 winbind_close_sock();
469                                 return -1;
470                         }
471                         total_time += 5;
472                         continue;
473                 }
474
475                 if (FD_ISSET(winbindd_fd, &r_fds)) {
476
477                         /* Do the Read */
478
479                         int result = read(winbindd_fd, (char *)buffer + nread,
480                               count - nread);
481
482                         if ((result == -1) || (result == 0)) {
483
484                                 /* Read failed.  I think the only useful thing we
485                                    can do here is just return -1 and fail since the
486                                    transaction has failed half way through. */
487
488                                 winbind_close_sock();
489                                 return -1;
490                         }
491
492                         nread += result;
493
494                 }
495         }
496
497         return nread;
498 }
499
500 /* Read reply */
501
502 static int winbindd_read_reply(struct winbindd_response *response)
503 {
504         int result1, result2 = 0;
505
506         if (!response) {
507                 return -1;
508         }
509
510         /* Read fixed length response */
511
512         result1 = winbind_read_sock(response,
513                                     sizeof(struct winbindd_response));
514         if (result1 == -1) {
515                 return -1;
516         }
517
518         /* We actually send the pointer value of the extra_data field from
519            the server.  This has no meaning in the client's address space
520            so we clear it out. */
521
522         response->extra_data.data = NULL;
523
524         /* Read variable length response */
525
526         if (response->length > sizeof(struct winbindd_response)) {
527                 int extra_data_len = response->length -
528                         sizeof(struct winbindd_response);
529
530                 /* Mallocate memory for extra data */
531
532                 if (!(response->extra_data.data = malloc(extra_data_len))) {
533                         return -1;
534                 }
535
536                 result2 = winbind_read_sock(response->extra_data.data,
537                                             extra_data_len);
538                 if (result2 == -1) {
539                         winbindd_free_response(response);
540                         return -1;
541                 }
542         }
543
544         /* Return total amount of data read */
545
546         return result1 + result2;
547 }
548
549 /*
550  * send simple types of requests
551  */
552
553 NSS_STATUS winbindd_send_request(int req_type, int need_priv,
554                                  struct winbindd_request *request)
555 {
556         struct winbindd_request lrequest;
557
558         /* Check for our tricky environment variable */
559
560         if (winbind_env_set()) {
561                 return NSS_STATUS_NOTFOUND;
562         }
563
564         if (!request) {
565                 ZERO_STRUCT(lrequest);
566                 request = &lrequest;
567         }
568
569         /* Fill in request and send down pipe */
570
571         winbindd_init_request(request, req_type);
572
573         if (winbind_write_sock(request, sizeof(*request),
574                                request->wb_flags & WBFLAG_RECURSE,
575                                need_priv) == -1)
576         {
577                 /* Set ENOENT for consistency.  Required by some apps */
578                 errno = ENOENT;
579
580                 return NSS_STATUS_UNAVAIL;
581         }
582
583         if ((request->extra_len != 0) &&
584             (winbind_write_sock(request->extra_data.data,
585                                 request->extra_len,
586                                 request->wb_flags & WBFLAG_RECURSE,
587                                 need_priv) == -1))
588         {
589                 /* Set ENOENT for consistency.  Required by some apps */
590                 errno = ENOENT;
591
592                 return NSS_STATUS_UNAVAIL;
593         }
594
595         return NSS_STATUS_SUCCESS;
596 }
597
598 /*
599  * Get results from winbindd request
600  */
601
602 NSS_STATUS winbindd_get_response(struct winbindd_response *response)
603 {
604         struct winbindd_response lresponse;
605
606         if (!response) {
607                 ZERO_STRUCT(lresponse);
608                 response = &lresponse;
609         }
610
611         init_response(response);
612
613         /* Wait for reply */
614         if (winbindd_read_reply(response) == -1) {
615                 /* Set ENOENT for consistency.  Required by some apps */
616                 errno = ENOENT;
617
618                 return NSS_STATUS_UNAVAIL;
619         }
620
621         /* Throw away extra data if client didn't request it */
622         if (response == &lresponse) {
623                 winbindd_free_response(response);
624         }
625
626         /* Copy reply data from socket */
627         if (response->result != WINBINDD_OK) {
628                 return NSS_STATUS_NOTFOUND;
629         }
630
631         return NSS_STATUS_SUCCESS;
632 }
633
634 /* Handle simple types of requests */
635
636 NSS_STATUS winbindd_request_response(int req_type,
637                             struct winbindd_request *request,
638                             struct winbindd_response *response)
639 {
640         NSS_STATUS status = NSS_STATUS_UNAVAIL;
641         int count = 0;
642
643         while ((status == NSS_STATUS_UNAVAIL) && (count < 10)) {
644                 status = winbindd_send_request(req_type, 0, request);
645                 if (status != NSS_STATUS_SUCCESS)
646                         return(status);
647                 status = winbindd_get_response(response);
648                 count += 1;
649         }
650
651         return status;
652 }
653
654 NSS_STATUS winbindd_priv_request_response(int req_type,
655                                           struct winbindd_request *request,
656                                           struct winbindd_response *response)
657 {
658         NSS_STATUS status = NSS_STATUS_UNAVAIL;
659         int count = 0;
660
661         while ((status == NSS_STATUS_UNAVAIL) && (count < 10)) {
662                 status = winbindd_send_request(req_type, 1, request);
663                 if (status != NSS_STATUS_SUCCESS)
664                         return(status);
665                 status = winbindd_get_response(response);
666                 count += 1;
667         }
668
669         return status;
670 }