Add context versions of wbclient functions
[gd/samba/.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    Copyright (C) Matthew Newton 2015
10
11
12    This library is free software; you can redistribute it and/or
13    modify it under the terms of the GNU Lesser General Public
14    License as published by the Free Software Foundation; either
15    version 3 of the License, or (at your option) any later version.
16
17    This library is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20    Library General Public License for more details.
21
22    You should have received a copy of the GNU Lesser General Public License
23    along with this program.  If not, see <http://www.gnu.org/licenses/>.
24 */
25
26 #include "replace.h"
27 #include "system/select.h"
28 #include "winbind_client.h"
29
30 /* Global context */
31
32 struct winbindd_context {
33         int winbindd_fd;        /* winbind file descriptor */
34         bool is_privileged;     /* using the privileged socket? */
35         pid_t our_pid;          /* calling process pid */
36 };
37
38 static struct winbindd_context wb_global_ctx = {
39         .winbindd_fd = -1,
40         .is_privileged = 0,
41         .our_pid = 0
42 };
43
44 /* Free a response structure */
45
46 void winbindd_free_response(struct winbindd_response *response)
47 {
48         /* Free any allocated extra_data */
49
50         if (response)
51                 SAFE_FREE(response->extra_data.data);
52 }
53
54 /* Initialise a request structure */
55
56 static void winbindd_init_request(struct winbindd_request *request,
57                                   int request_type)
58 {
59         request->length = sizeof(struct winbindd_request);
60
61         request->cmd = (enum winbindd_cmd)request_type;
62         request->pid = getpid();
63
64 }
65
66 /* Initialise a response structure */
67
68 static void init_response(struct winbindd_response *response)
69 {
70         /* Initialise return value */
71
72         response->result = WINBINDD_ERROR;
73 }
74
75 /* Close established socket */
76
77 static void winbind_close_sock(struct winbindd_context *ctx)
78 {
79         if (!ctx) {
80                 return;
81         }
82
83         if (ctx->winbindd_fd != -1) {
84                 close(ctx->winbindd_fd);
85                 ctx->winbindd_fd = -1;
86         }
87 }
88
89 /* Destructor for global context to ensure fd is closed */
90
91 #if HAVE_FUNCTION_ATTRIBUTE_DESTRUCTOR
92 __attribute__((destructor))
93 #endif
94 static void winbind_destructor(void)
95 {
96         winbind_close_sock(&wb_global_ctx);
97 }
98
99 #define CONNECT_TIMEOUT 30
100
101 /* Make sure socket handle isn't stdin, stdout or stderr */
102 #define RECURSION_LIMIT 3
103
104 static int make_nonstd_fd_internals(int fd, int limit /* Recursion limiter */)
105 {
106         int new_fd;
107         if (fd >= 0 && fd <= 2) {
108 #ifdef F_DUPFD
109                 if ((new_fd = fcntl(fd, F_DUPFD, 3)) == -1) {
110                         return -1;
111                 }
112                 /* Paranoia */
113                 if (new_fd < 3) {
114                         close(new_fd);
115                         return -1;
116                 }
117                 close(fd);
118                 return new_fd;
119 #else
120                 if (limit <= 0)
121                         return -1;
122
123                 new_fd = dup(fd);
124                 if (new_fd == -1)
125                         return -1;
126
127                 /* use the program stack to hold our list of FDs to close */
128                 new_fd = make_nonstd_fd_internals(new_fd, limit - 1);
129                 close(fd);
130                 return new_fd;
131 #endif
132         }
133         return fd;
134 }
135
136 /****************************************************************************
137  Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
138  else
139  if SYSV use O_NDELAY
140  if BSD use FNDELAY
141  Set close on exec also.
142 ****************************************************************************/
143
144 static int make_safe_fd(int fd)
145 {
146         int result, flags;
147         int new_fd = make_nonstd_fd_internals(fd, RECURSION_LIMIT);
148         if (new_fd == -1) {
149                 close(fd);
150                 return -1;
151         }
152
153         /* Socket should be nonblocking. */
154 #ifdef O_NONBLOCK
155 #define FLAG_TO_SET O_NONBLOCK
156 #else
157 #ifdef SYSV
158 #define FLAG_TO_SET O_NDELAY
159 #else /* BSD */
160 #define FLAG_TO_SET FNDELAY
161 #endif
162 #endif
163
164         if ((flags = fcntl(new_fd, F_GETFL)) == -1) {
165                 close(new_fd);
166                 return -1;
167         }
168
169         flags |= FLAG_TO_SET;
170         if (fcntl(new_fd, F_SETFL, flags) == -1) {
171                 close(new_fd);
172                 return -1;
173         }
174
175 #undef FLAG_TO_SET
176
177         /* Socket should be closed on exec() */
178 #ifdef FD_CLOEXEC
179         result = flags = fcntl(new_fd, F_GETFD, 0);
180         if (flags >= 0) {
181                 flags |= FD_CLOEXEC;
182                 result = fcntl( new_fd, F_SETFD, flags );
183         }
184         if (result < 0) {
185                 close(new_fd);
186                 return -1;
187         }
188 #endif
189         return new_fd;
190 }
191
192 /**
193  * @internal
194  *
195  * @brief Check if we talk to the priviliged pipe which should be owned by root.
196  *
197  * This checks if we have uid_wrapper running and if this is the case it will
198  * allow to connect to the winbind privileged pipe even it is not owned by root.
199  *
200  * @param[in]  uid      The uid to check if we can safely talk to the pipe.
201  *
202  * @return              If we have access it returns true, else false.
203  */
204 static bool winbind_privileged_pipe_is_root(uid_t uid)
205 {
206         if (uid == 0) {
207                 return true;
208         }
209
210         if (uid_wrapper_enabled()) {
211                 return true;
212         }
213
214         return false;
215 }
216
217 /* Connect to winbindd socket */
218
219 static int winbind_named_pipe_sock(const char *dir)
220 {
221         struct sockaddr_un sunaddr;
222         struct stat st;
223         char *path = NULL;
224         int fd;
225         int wait_time;
226         int slept;
227
228         /* Check permissions on unix socket directory */
229
230         if (lstat(dir, &st) == -1) {
231                 errno = ENOENT;
232                 return -1;
233         }
234
235         /*
236          * This tells us that the pipe is owned by a privileged
237          * process, as we will be sending passwords to it.
238          */
239         if (!S_ISDIR(st.st_mode) ||
240             !winbind_privileged_pipe_is_root(st.st_uid)) {
241                 errno = ENOENT;
242                 return -1;
243         }
244
245         /* Connect to socket */
246
247         if (asprintf(&path, "%s/%s", dir, WINBINDD_SOCKET_NAME) < 0) {
248                 return -1;
249         }
250
251         ZERO_STRUCT(sunaddr);
252         sunaddr.sun_family = AF_UNIX;
253         strncpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path) - 1);
254
255         /* If socket file doesn't exist, don't bother trying to connect
256            with retry.  This is an attempt to make the system usable when
257            the winbindd daemon is not running. */
258
259         if (lstat(path, &st) == -1) {
260                 errno = ENOENT;
261                 SAFE_FREE(path);
262                 return -1;
263         }
264
265         SAFE_FREE(path);
266         /* Check permissions on unix socket file */
267
268         /*
269          * This tells us that the pipe is owned by a privileged
270          * process, as we will be sending passwords to it.
271          */
272         if (!S_ISSOCK(st.st_mode) ||
273             !winbind_privileged_pipe_is_root(st.st_uid)) {
274                 errno = ENOENT;
275                 return -1;
276         }
277
278         /* Connect to socket */
279
280         if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
281                 return -1;
282         }
283
284         /* Set socket non-blocking and close on exec. */
285
286         if ((fd = make_safe_fd( fd)) == -1) {
287                 return fd;
288         }
289
290         for (wait_time = 0; connect(fd, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1;
291                         wait_time += slept) {
292                 struct pollfd pfd;
293                 int ret;
294                 int connect_errno = 0;
295                 socklen_t errnosize;
296
297                 if (wait_time >= CONNECT_TIMEOUT)
298                         goto error_out;
299
300                 switch (errno) {
301                         case EINPROGRESS:
302                                 pfd.fd = fd;
303                                 pfd.events = POLLOUT;
304
305                                 ret = poll(&pfd, 1, (CONNECT_TIMEOUT - wait_time) * 1000);
306
307                                 if (ret > 0) {
308                                         errnosize = sizeof(connect_errno);
309
310                                         ret = getsockopt(fd, SOL_SOCKET,
311                                                         SO_ERROR, &connect_errno, &errnosize);
312
313                                         if (ret >= 0 && connect_errno == 0) {
314                                                 /* Connect succeed */
315                                                 goto out;
316                                         }
317                                 }
318
319                                 slept = CONNECT_TIMEOUT;
320                                 break;
321                         case EAGAIN:
322                                 slept = rand() % 3 + 1;
323                                 sleep(slept);
324                                 break;
325                         default:
326                                 goto error_out;
327                 }
328
329         }
330
331   out:
332
333         return fd;
334
335   error_out:
336
337         close(fd);
338         return -1;
339 }
340
341 static const char *winbindd_socket_dir(void)
342 {
343         if (nss_wrapper_enabled()) {
344                 const char *env_dir;
345
346                 env_dir = getenv("SELFTEST_WINBINDD_SOCKET_DIR");
347                 if (env_dir != NULL) {
348                         return env_dir;
349                 }
350         }
351
352         return WINBINDD_SOCKET_DIR;
353 }
354
355 /* Connect to winbindd socket */
356
357 static int winbind_open_pipe_sock(struct winbindd_context *ctx,
358                                   int recursing, int need_priv)
359 {
360 #ifdef HAVE_UNIXSOCKET
361         struct winbindd_request request;
362         struct winbindd_response response;
363
364         ZERO_STRUCT(request);
365         ZERO_STRUCT(response);
366
367         if (!ctx) {
368                 return -1;
369         }
370
371         if (ctx->our_pid != getpid()) {
372                 winbind_close_sock(ctx);
373                 ctx->our_pid = getpid();
374         }
375
376         if ((need_priv != 0) && (ctx->is_privileged == 0)) {
377                 winbind_close_sock(ctx);
378         }
379
380         if (ctx->winbindd_fd != -1) {
381                 return ctx->winbindd_fd;
382         }
383
384         if (recursing) {
385                 return -1;
386         }
387
388         ctx->winbindd_fd = winbind_named_pipe_sock(winbindd_socket_dir());
389
390         if (ctx->winbindd_fd == -1) {
391                 return -1;
392         }
393
394         ctx->is_privileged = 0;
395
396         /* version-check the socket */
397
398         request.wb_flags = WBFLAG_RECURSE;
399         if ((winbindd_request_response(ctx, WINBINDD_INTERFACE_VERSION, &request,
400                                        &response) != NSS_STATUS_SUCCESS) ||
401             (response.data.interface_version != WINBIND_INTERFACE_VERSION)) {
402                 winbind_close_sock(ctx);
403                 return -1;
404         }
405
406         /* try and get priv pipe */
407
408         request.wb_flags = WBFLAG_RECURSE;
409
410         /* Note that response needs to be initialized to avoid
411          * crashing on clean up after WINBINDD_PRIV_PIPE_DIR call failed
412          * as interface version (from the first request) returned as a fstring,
413          * thus response.extra_data.data will not be NULL even though
414          * winbindd response did not write over it due to a failure */
415         ZERO_STRUCT(response);
416         if (winbindd_request_response(ctx, WINBINDD_PRIV_PIPE_DIR, &request,
417                                       &response) == NSS_STATUS_SUCCESS) {
418                 int fd;
419                 fd = winbind_named_pipe_sock((char *)response.extra_data.data);
420                 if (fd != -1) {
421                         close(ctx->winbindd_fd);
422                         ctx->winbindd_fd = fd;
423                         ctx->is_privileged = 1;
424                 }
425         }
426
427         if ((need_priv != 0) && (ctx->is_privileged == 0)) {
428                 return -1;
429         }
430
431         SAFE_FREE(response.extra_data.data);
432
433         return ctx->winbindd_fd;
434 #else
435         return -1;
436 #endif /* HAVE_UNIXSOCKET */
437 }
438
439 /* Write data to winbindd socket */
440
441 static int winbind_write_sock(struct winbindd_context *ctx, void *buffer,
442                               int count, int recursing, int need_priv)
443 {
444         int fd, result, nwritten;
445
446         /* Open connection to winbind daemon */
447
448  restart:
449
450         fd = winbind_open_pipe_sock(ctx, recursing, need_priv);
451         if (fd == -1) {
452                 errno = ENOENT;
453                 return -1;
454         }
455
456         /* Write data to socket */
457
458         nwritten = 0;
459
460         while(nwritten < count) {
461                 struct pollfd pfd;
462                 int ret;
463
464                 /* Catch pipe close on other end by checking if a read()
465                    call would not block by calling poll(). */
466
467                 pfd.fd = fd;
468                 pfd.events = POLLIN|POLLOUT|POLLHUP;
469
470                 ret = poll(&pfd, 1, -1);
471                 if (ret == -1) {
472                         winbind_close_sock(ctx);
473                         return -1;                   /* poll error */
474                 }
475
476                 /* Write should be OK if fd not available for reading */
477
478                 if ((ret == 1) && (pfd.revents & (POLLIN|POLLHUP|POLLERR))) {
479
480                         /* Pipe has closed on remote end */
481
482                         winbind_close_sock(ctx);
483                         goto restart;
484                 }
485
486                 /* Do the write */
487
488                 result = write(fd, (char *)buffer + nwritten,
489                                count - nwritten);
490
491                 if ((result == -1) || (result == 0)) {
492
493                         /* Write failed */
494
495                         winbind_close_sock(ctx);
496                         return -1;
497                 }
498
499                 nwritten += result;
500         }
501
502         return nwritten;
503 }
504
505 /* Read data from winbindd socket */
506
507 static int winbind_read_sock(struct winbindd_context *ctx,
508                              void *buffer, int count)
509 {
510         int fd;
511         int nread = 0;
512         int total_time = 0;
513
514         fd = winbind_open_pipe_sock(ctx, false, false);
515         if (fd == -1) {
516                 return -1;
517         }
518
519         /* Read data from socket */
520         while(nread < count) {
521                 struct pollfd pfd;
522                 int ret;
523
524                 /* Catch pipe close on other end by checking if a read()
525                    call would not block by calling poll(). */
526
527                 pfd.fd = fd;
528                 pfd.events = POLLIN|POLLHUP;
529
530                 /* Wait for 5 seconds for a reply. May need to parameterise this... */
531
532                 ret = poll(&pfd, 1, 5000);
533                 if (ret == -1) {
534                         winbind_close_sock(ctx);
535                         return -1;                   /* poll error */
536                 }
537
538                 if (ret == 0) {
539                         /* Not ready for read yet... */
540                         if (total_time >= 30) {
541                                 /* Timeout */
542                                 winbind_close_sock(ctx);
543                                 return -1;
544                         }
545                         total_time += 5;
546                         continue;
547                 }
548
549                 if ((ret == 1) && (pfd.revents & (POLLIN|POLLHUP|POLLERR))) {
550
551                         /* Do the Read */
552
553                         int result = read(fd, (char *)buffer + nread,
554                               count - nread);
555
556                         if ((result == -1) || (result == 0)) {
557
558                                 /* Read failed.  I think the only useful thing we
559                                    can do here is just return -1 and fail since the
560                                    transaction has failed half way through. */
561
562                                 winbind_close_sock(ctx);
563                                 return -1;
564                         }
565
566                         nread += result;
567
568                 }
569         }
570
571         return nread;
572 }
573
574 /* Read reply */
575
576 static int winbindd_read_reply(struct winbindd_context *ctx,
577                                struct winbindd_response *response)
578 {
579         int result1, result2 = 0;
580
581         if (!response) {
582                 return -1;
583         }
584
585         /* Read fixed length response */
586
587         result1 = winbind_read_sock(ctx, response,
588                                     sizeof(struct winbindd_response));
589
590         /* We actually send the pointer value of the extra_data field from
591            the server.  This has no meaning in the client's address space
592            so we clear it out. */
593
594         response->extra_data.data = NULL;
595
596         if (result1 == -1) {
597                 return -1;
598         }
599
600         if (response->length < sizeof(struct winbindd_response)) {
601                 return -1;
602         }
603
604         /* Read variable length response */
605
606         if (response->length > sizeof(struct winbindd_response)) {
607                 int extra_data_len = response->length -
608                         sizeof(struct winbindd_response);
609
610                 /* Mallocate memory for extra data */
611
612                 if (!(response->extra_data.data = malloc(extra_data_len))) {
613                         return -1;
614                 }
615
616                 result2 = winbind_read_sock(ctx, response->extra_data.data,
617                                             extra_data_len);
618                 if (result2 == -1) {
619                         winbindd_free_response(response);
620                         return -1;
621                 }
622         }
623
624         /* Return total amount of data read */
625
626         return result1 + result2;
627 }
628
629 /*
630  * send simple types of requests
631  */
632
633 NSS_STATUS winbindd_send_request(struct winbindd_context *ctx,
634                                  int req_type, int need_priv,
635                                  struct winbindd_request *request)
636 {
637         struct winbindd_request lrequest;
638
639         /* Check for our tricky environment variable */
640
641         if (winbind_env_set()) {
642                 return NSS_STATUS_NOTFOUND;
643         }
644
645         if (!request) {
646                 ZERO_STRUCT(lrequest);
647                 request = &lrequest;
648         }
649
650         /* Fill in request and send down pipe */
651
652         winbindd_init_request(request, req_type);
653
654         if (winbind_write_sock(ctx, request, sizeof(*request),
655                                request->wb_flags & WBFLAG_RECURSE,
656                                need_priv) == -1)
657         {
658                 /* Set ENOENT for consistency.  Required by some apps */
659                 errno = ENOENT;
660
661                 return NSS_STATUS_UNAVAIL;
662         }
663
664         if ((request->extra_len != 0) &&
665             (winbind_write_sock(ctx, request->extra_data.data,
666                                 request->extra_len,
667                                 request->wb_flags & WBFLAG_RECURSE,
668                                 need_priv) == -1))
669         {
670                 /* Set ENOENT for consistency.  Required by some apps */
671                 errno = ENOENT;
672
673                 return NSS_STATUS_UNAVAIL;
674         }
675
676         return NSS_STATUS_SUCCESS;
677 }
678
679 /*
680  * Get results from winbindd request
681  */
682
683 NSS_STATUS winbindd_get_response(struct winbindd_context *ctx,
684                                  struct winbindd_response *response)
685 {
686         struct winbindd_response lresponse;
687
688         if (!response) {
689                 ZERO_STRUCT(lresponse);
690                 response = &lresponse;
691         }
692
693         init_response(response);
694
695         /* Wait for reply */
696         if (winbindd_read_reply(ctx, response) == -1) {
697                 /* Set ENOENT for consistency.  Required by some apps */
698                 errno = ENOENT;
699
700                 return NSS_STATUS_UNAVAIL;
701         }
702
703         /* Throw away extra data if client didn't request it */
704         if (response == &lresponse) {
705                 winbindd_free_response(response);
706         }
707
708         /* Copy reply data from socket */
709         if (response->result != WINBINDD_OK) {
710                 return NSS_STATUS_NOTFOUND;
711         }
712
713         return NSS_STATUS_SUCCESS;
714 }
715
716 /* Handle simple types of requests */
717
718 NSS_STATUS winbindd_request_response(struct winbindd_context *ctx,
719                                      int req_type,
720                                      struct winbindd_request *request,
721                                      struct winbindd_response *response)
722 {
723         NSS_STATUS status = NSS_STATUS_UNAVAIL;
724         int count = 0;
725         struct winbindd_context *wb_ctx = ctx;
726
727         if (ctx == NULL) {
728                 wb_ctx = &wb_global_ctx;
729         }
730
731         while ((status == NSS_STATUS_UNAVAIL) && (count < 10)) {
732                 status = winbindd_send_request(wb_ctx, req_type, 0, request);
733                 if (status != NSS_STATUS_SUCCESS)
734                         return(status);
735                 status = winbindd_get_response(wb_ctx, response);
736                 count += 1;
737         }
738
739         return status;
740 }
741
742 NSS_STATUS winbindd_priv_request_response(struct winbindd_context *ctx,
743                                           int req_type,
744                                           struct winbindd_request *request,
745                                           struct winbindd_response *response)
746 {
747         NSS_STATUS status = NSS_STATUS_UNAVAIL;
748         int count = 0;
749         struct winbindd_context *wb_ctx;
750
751         if (ctx == NULL) {
752                 wb_ctx = &wb_global_ctx;
753         }
754
755         while ((status == NSS_STATUS_UNAVAIL) && (count < 10)) {
756                 status = winbindd_send_request(wb_ctx, req_type, 1, request);
757                 if (status != NSS_STATUS_SUCCESS)
758                         return(status);
759                 status = winbindd_get_response(wb_ctx, response);
760                 count += 1;
761         }
762
763         return status;
764 }
765
766 /* Create and free winbindd context */
767
768 struct winbindd_context *winbindd_ctx_create(void)
769 {
770         struct winbindd_context *ctx;
771
772         ctx = calloc(1, sizeof(struct winbindd_context));
773
774         if (!ctx) {
775                 return NULL;
776         }
777
778         ctx->winbindd_fd = -1;
779
780         return ctx;
781 }
782
783 void winbindd_ctx_free(struct winbindd_context *ctx)
784 {
785         winbind_close_sock(ctx);
786         free(ctx);
787 }