s4:kdc: samba_kdc_lookup_realm() only needs sdb_entry
[Samba.git] / nsswitch / wb_common.c
blob1a3ed1241c5f84fdf8406f0edf8f6373ad6a085a
1 /*
2 Unix SMB/CIFS implementation.
4 winbind client common code
6 Copyright (C) Tim Potter 2000
7 Copyright (C) Andrew Tridgell 2000
8 Copyright (C) Andrew Bartlett 2002
9 Copyright (C) Matthew Newton 2015
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.
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.
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/>.
26 #include "replace.h"
27 #include "system/select.h"
28 #include "winbind_client.h"
30 #ifdef HAVE_PTHREAD_H
31 #include <pthread.h>
32 #endif
34 static char client_name[32];
36 /* Global context */
38 struct winbindd_context {
39 int winbindd_fd; /* winbind file descriptor */
40 bool is_privileged; /* using the privileged socket? */
41 pid_t our_pid; /* calling process pid */
44 #ifdef HAVE_PTHREAD
45 static pthread_mutex_t wb_global_ctx_mutex = PTHREAD_MUTEX_INITIALIZER;
46 #endif
48 static struct winbindd_context *get_wb_global_ctx(void)
50 static struct winbindd_context wb_global_ctx = {
51 .winbindd_fd = -1,
52 .is_privileged = false,
53 .our_pid = 0
56 #ifdef HAVE_PTHREAD
57 pthread_mutex_lock(&wb_global_ctx_mutex);
58 #endif
59 return &wb_global_ctx;
62 static void put_wb_global_ctx(void)
64 #ifdef HAVE_PTHREAD
65 pthread_mutex_unlock(&wb_global_ctx_mutex);
66 #endif
67 return;
70 void winbind_set_client_name(const char *name)
72 if (name == NULL || strlen(name) == 0) {
73 return;
76 (void)snprintf(client_name, sizeof(client_name), "%s", name);
79 static const char *winbind_get_client_name(void)
81 if (client_name[0] == '\0') {
82 const char *progname = getprogname();
83 int len;
85 if (progname == NULL) {
86 progname = "<unknown>";
89 len = snprintf(client_name,
90 sizeof(client_name),
91 "%s",
92 progname);
93 if (len <= 0) {
94 return progname;
98 return client_name;
101 /* Initialise a request structure */
103 static void winbindd_init_request(struct winbindd_request *request,
104 int request_type)
106 request->length = sizeof(struct winbindd_request);
108 request->cmd = (enum winbindd_cmd)request_type;
109 request->pid = getpid();
111 (void)snprintf(request->client_name,
112 sizeof(request->client_name),
113 "%s",
114 winbind_get_client_name());
117 /* Initialise a response structure */
119 static void init_response(struct winbindd_response *response)
121 /* Initialise return value */
123 response->result = WINBINDD_ERROR;
126 /* Close established socket */
128 static void winbind_close_sock(struct winbindd_context *ctx)
130 if (!ctx) {
131 return;
134 if (ctx->winbindd_fd != -1) {
135 close(ctx->winbindd_fd);
136 ctx->winbindd_fd = -1;
140 /* Destructor for global context to ensure fd is closed */
142 #ifdef HAVE_DESTRUCTOR_ATTRIBUTE
143 __attribute__((destructor))
144 #elif defined (HAVE_PRAGMA_FINI)
145 #pragma fini (winbind_destructor)
146 #endif
147 static void winbind_destructor(void)
149 struct winbindd_context *ctx;
151 ctx = get_wb_global_ctx();
152 winbind_close_sock(ctx);
153 put_wb_global_ctx();
156 #define CONNECT_TIMEOUT 30
158 /* Make sure socket handle isn't stdin, stdout or stderr */
159 #define RECURSION_LIMIT 3
161 static int make_nonstd_fd_internals(int fd, int limit /* Recursion limiter */)
163 int new_fd;
164 if (fd >= 0 && fd <= 2) {
165 #ifdef F_DUPFD
166 if ((new_fd = fcntl(fd, F_DUPFD, 3)) == -1) {
167 return -1;
169 /* Paranoia */
170 if (new_fd < 3) {
171 close(new_fd);
172 return -1;
174 close(fd);
175 return new_fd;
176 #else
177 if (limit <= 0)
178 return -1;
180 new_fd = dup(fd);
181 if (new_fd == -1)
182 return -1;
184 /* use the program stack to hold our list of FDs to close */
185 new_fd = make_nonstd_fd_internals(new_fd, limit - 1);
186 close(fd);
187 return new_fd;
188 #endif
190 return fd;
193 /****************************************************************************
194 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
195 else
196 if SYSV use O_NDELAY
197 if BSD use FNDELAY
198 Set close on exec also.
199 ****************************************************************************/
201 static int make_safe_fd(int fd)
203 int result, flags;
204 int new_fd = make_nonstd_fd_internals(fd, RECURSION_LIMIT);
205 if (new_fd == -1) {
206 close(fd);
207 return -1;
210 /* Socket should be nonblocking. */
211 #ifdef O_NONBLOCK
212 #define FLAG_TO_SET O_NONBLOCK
213 #else
214 #ifdef SYSV
215 #define FLAG_TO_SET O_NDELAY
216 #else /* BSD */
217 #define FLAG_TO_SET FNDELAY
218 #endif
219 #endif
221 if ((flags = fcntl(new_fd, F_GETFL)) == -1) {
222 close(new_fd);
223 return -1;
226 flags |= FLAG_TO_SET;
227 if (fcntl(new_fd, F_SETFL, flags) == -1) {
228 close(new_fd);
229 return -1;
232 #undef FLAG_TO_SET
234 /* Socket should be closed on exec() */
235 #ifdef FD_CLOEXEC
236 result = flags = fcntl(new_fd, F_GETFD, 0);
237 if (flags >= 0) {
238 flags |= FD_CLOEXEC;
239 result = fcntl( new_fd, F_SETFD, flags );
241 if (result < 0) {
242 close(new_fd);
243 return -1;
245 #endif
246 return new_fd;
250 * @internal
252 * @brief Check if we talk to the privileged pipe which should be owned by root.
254 * This checks if we have uid_wrapper running and if this is the case it will
255 * allow one to connect to the winbind privileged pipe even it is not owned by root.
257 * @param[in] uid The uid to check if we can safely talk to the pipe.
259 * @return If we have access it returns true, else false.
261 static bool winbind_privileged_pipe_is_root(uid_t uid)
263 if (uid == 0) {
264 return true;
267 if (uid_wrapper_enabled()) {
268 return true;
271 return false;
274 /* Connect to winbindd socket */
276 static int winbind_named_pipe_sock(const char *dir)
278 struct sockaddr_un sunaddr;
279 struct stat st;
280 int fd;
281 int wait_time;
282 int slept;
283 int ret;
285 /* Check permissions on unix socket directory */
287 if (lstat(dir, &st) == -1) {
288 errno = ENOENT;
289 return -1;
293 * This tells us that the pipe is owned by a privileged
294 * process, as we will be sending passwords to it.
296 if (!S_ISDIR(st.st_mode) ||
297 !winbind_privileged_pipe_is_root(st.st_uid)) {
298 errno = ENOENT;
299 return -1;
302 /* Connect to socket */
304 sunaddr = (struct sockaddr_un) { .sun_family = AF_UNIX };
306 ret = snprintf(sunaddr.sun_path, sizeof(sunaddr.sun_path),
307 "%s/%s", dir, WINBINDD_SOCKET_NAME);
308 if ((ret == -1) || (ret >= sizeof(sunaddr.sun_path))) {
309 errno = ENAMETOOLONG;
310 return -1;
313 /* If socket file doesn't exist, don't bother trying to connect
314 with retry. This is an attempt to make the system usable when
315 the winbindd daemon is not running. */
317 if (lstat(sunaddr.sun_path, &st) == -1) {
318 errno = ENOENT;
319 return -1;
322 /* Check permissions on unix socket file */
325 * This tells us that the pipe is owned by a privileged
326 * process, as we will be sending passwords to it.
328 if (!S_ISSOCK(st.st_mode) ||
329 !winbind_privileged_pipe_is_root(st.st_uid)) {
330 errno = ENOENT;
331 return -1;
334 /* Connect to socket */
336 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
337 return -1;
340 /* Set socket non-blocking and close on exec. */
342 if ((fd = make_safe_fd( fd)) == -1) {
343 return fd;
346 for (wait_time = 0; connect(fd, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1;
347 wait_time += slept) {
348 struct pollfd pfd;
349 int connect_errno = 0;
350 socklen_t errnosize;
352 if (wait_time >= CONNECT_TIMEOUT)
353 goto error_out;
355 switch (errno) {
356 case EINPROGRESS:
357 pfd.fd = fd;
358 pfd.events = POLLOUT;
360 ret = poll(&pfd, 1, (CONNECT_TIMEOUT - wait_time) * 1000);
362 if (ret > 0) {
363 errnosize = sizeof(connect_errno);
365 ret = getsockopt(fd, SOL_SOCKET,
366 SO_ERROR, &connect_errno, &errnosize);
368 if (ret >= 0 && connect_errno == 0) {
369 /* Connect succeed */
370 goto out;
374 slept = CONNECT_TIMEOUT;
375 break;
376 case EAGAIN:
377 slept = rand() % 3 + 1;
378 sleep(slept);
379 break;
380 default:
381 goto error_out;
386 out:
388 return fd;
390 error_out:
392 close(fd);
393 return -1;
396 static const char *winbindd_socket_dir(void)
398 if (nss_wrapper_enabled()) {
399 const char *env_dir;
401 env_dir = getenv("SELFTEST_WINBINDD_SOCKET_DIR");
402 if (env_dir != NULL) {
403 return env_dir;
407 return WINBINDD_SOCKET_DIR;
410 /* Connect to winbindd socket */
412 static int winbind_open_pipe_sock(struct winbindd_context *ctx,
413 int recursing, int need_priv)
415 #ifdef HAVE_UNIXSOCKET
416 struct winbindd_request request;
417 struct winbindd_response response;
419 ZERO_STRUCT(request);
420 ZERO_STRUCT(response);
422 if (!ctx) {
423 return -1;
426 if (ctx->our_pid != getpid()) {
427 winbind_close_sock(ctx);
428 ctx->our_pid = getpid();
431 if ((need_priv != 0) && !ctx->is_privileged) {
432 winbind_close_sock(ctx);
435 if (ctx->winbindd_fd != -1) {
436 return ctx->winbindd_fd;
439 if (recursing) {
440 return -1;
443 ctx->winbindd_fd = winbind_named_pipe_sock(winbindd_socket_dir());
445 if (ctx->winbindd_fd == -1) {
446 return -1;
449 ctx->is_privileged = false;
451 /* version-check the socket */
453 request.wb_flags = WBFLAG_RECURSE;
454 if ((winbindd_request_response(ctx, WINBINDD_INTERFACE_VERSION, &request,
455 &response) != NSS_STATUS_SUCCESS) ||
456 (response.data.interface_version != WINBIND_INTERFACE_VERSION)) {
457 winbind_close_sock(ctx);
458 return -1;
461 if (need_priv == 0) {
462 return ctx->winbindd_fd;
465 /* try and get priv pipe */
467 request.wb_flags = WBFLAG_RECURSE;
469 /* Note that response needs to be initialized to avoid
470 * crashing on clean up after WINBINDD_PRIV_PIPE_DIR call failed
471 * as interface version (from the first request) returned as a fstring,
472 * thus response.extra_data.data will not be NULL even though
473 * winbindd response did not write over it due to a failure */
474 ZERO_STRUCT(response);
475 if (winbindd_request_response(ctx, WINBINDD_PRIV_PIPE_DIR, &request,
476 &response) == NSS_STATUS_SUCCESS) {
477 int fd;
478 fd = winbind_named_pipe_sock((char *)response.extra_data.data);
479 if (fd != -1) {
480 close(ctx->winbindd_fd);
481 ctx->winbindd_fd = fd;
482 ctx->is_privileged = true;
485 SAFE_FREE(response.extra_data.data);
488 if (!ctx->is_privileged) {
489 return -1;
492 return ctx->winbindd_fd;
493 #else
494 return -1;
495 #endif /* HAVE_UNIXSOCKET */
498 /* Write data to winbindd socket */
500 static int winbind_write_sock(struct winbindd_context *ctx, void *buffer,
501 int count, int recursing, int need_priv)
503 int fd, result, nwritten;
505 /* Open connection to winbind daemon */
507 restart:
509 fd = winbind_open_pipe_sock(ctx, recursing, need_priv);
510 if (fd == -1) {
511 errno = ENOENT;
512 return -1;
515 /* Write data to socket */
517 nwritten = 0;
519 while(nwritten < count) {
520 struct pollfd pfd;
521 int ret;
523 /* Catch pipe close on other end by checking if a read()
524 call would not block by calling poll(). */
526 pfd.fd = fd;
527 pfd.events = POLLIN|POLLOUT|POLLHUP;
529 ret = poll(&pfd, 1, -1);
530 if (ret == -1) {
531 winbind_close_sock(ctx);
532 return -1; /* poll error */
535 /* Write should be OK if fd not available for reading */
537 if ((ret == 1) && (pfd.revents & (POLLIN|POLLHUP|POLLERR))) {
539 /* Pipe has closed on remote end */
541 winbind_close_sock(ctx);
542 goto restart;
545 /* Do the write */
547 result = write(fd, (char *)buffer + nwritten,
548 count - nwritten);
550 if ((result == -1) || (result == 0)) {
552 /* Write failed */
554 winbind_close_sock(ctx);
555 return -1;
558 nwritten += result;
561 return nwritten;
564 /* Read data from winbindd socket */
566 static int winbind_read_sock(struct winbindd_context *ctx,
567 void *buffer, int count)
569 int fd;
570 int nread = 0;
571 int total_time = 0;
573 fd = winbind_open_pipe_sock(ctx, false, false);
574 if (fd == -1) {
575 return -1;
578 /* Read data from socket */
579 while(nread < count) {
580 struct pollfd pfd;
581 int ret;
583 /* Catch pipe close on other end by checking if a read()
584 call would not block by calling poll(). */
586 pfd.fd = fd;
587 pfd.events = POLLIN|POLLHUP;
589 /* Wait for 5 seconds for a reply. May need to parameterise this... */
591 ret = poll(&pfd, 1, 5000);
592 if (ret == -1) {
593 winbind_close_sock(ctx);
594 return -1; /* poll error */
597 if (ret == 0) {
598 /* Not ready for read yet... */
599 if (total_time >= 300) {
600 /* Timeout */
601 winbind_close_sock(ctx);
602 return -1;
604 total_time += 5;
605 continue;
608 if ((ret == 1) && (pfd.revents & (POLLIN|POLLHUP|POLLERR))) {
610 /* Do the Read */
612 int result = read(fd, (char *)buffer + nread,
613 count - nread);
615 if ((result == -1) || (result == 0)) {
617 /* Read failed. I think the only useful thing we
618 can do here is just return -1 and fail since the
619 transaction has failed half way through. */
621 winbind_close_sock(ctx);
622 return -1;
625 nread += result;
630 return nread;
633 /* Read reply */
635 static int winbindd_read_reply(struct winbindd_context *ctx,
636 struct winbindd_response *response)
638 int result1, result2 = 0;
640 if (!response) {
641 return -1;
644 /* Read fixed length response */
646 result1 = winbind_read_sock(ctx, response,
647 sizeof(struct winbindd_response));
649 /* We actually send the pointer value of the extra_data field from
650 the server. This has no meaning in the client's address space
651 so we clear it out. */
653 response->extra_data.data = NULL;
655 if (result1 == -1) {
656 return -1;
659 if (response->length < sizeof(struct winbindd_response)) {
660 return -1;
663 /* Read variable length response */
665 if (response->length > sizeof(struct winbindd_response)) {
666 int extra_data_len = response->length -
667 sizeof(struct winbindd_response);
669 /* Mallocate memory for extra data */
671 if (!(response->extra_data.data = malloc(extra_data_len))) {
672 return -1;
675 result2 = winbind_read_sock(ctx, response->extra_data.data,
676 extra_data_len);
677 if (result2 == -1) {
678 winbindd_free_response(response);
679 return -1;
683 /* Return total amount of data read */
685 return result1 + result2;
689 * send simple types of requests
692 static NSS_STATUS winbindd_send_request(
693 struct winbindd_context *ctx,
694 int req_type,
695 int need_priv,
696 struct winbindd_request *request)
698 struct winbindd_request lrequest;
700 /* Check for our tricky environment variable */
702 if (winbind_env_set()) {
703 return NSS_STATUS_NOTFOUND;
706 if (!request) {
707 ZERO_STRUCT(lrequest);
708 request = &lrequest;
711 /* Fill in request and send down pipe */
713 winbindd_init_request(request, req_type);
715 if (winbind_write_sock(ctx, request, sizeof(*request),
716 request->wb_flags & WBFLAG_RECURSE,
717 need_priv) == -1)
719 /* Set ENOENT for consistency. Required by some apps */
720 errno = ENOENT;
722 return NSS_STATUS_UNAVAIL;
725 if ((request->extra_len != 0) &&
726 (winbind_write_sock(ctx, request->extra_data.data,
727 request->extra_len,
728 request->wb_flags & WBFLAG_RECURSE,
729 need_priv) == -1))
731 /* Set ENOENT for consistency. Required by some apps */
732 errno = ENOENT;
734 return NSS_STATUS_UNAVAIL;
737 return NSS_STATUS_SUCCESS;
741 * Get results from winbindd request
744 static NSS_STATUS winbindd_get_response(struct winbindd_context *ctx,
745 struct winbindd_response *response)
747 struct winbindd_response lresponse;
749 if (!response) {
750 ZERO_STRUCT(lresponse);
751 response = &lresponse;
754 init_response(response);
756 /* Wait for reply */
757 if (winbindd_read_reply(ctx, response) == -1) {
758 /* Set ENOENT for consistency. Required by some apps */
759 errno = ENOENT;
761 return NSS_STATUS_UNAVAIL;
764 /* Throw away extra data if client didn't request it */
765 if (response == &lresponse) {
766 winbindd_free_response(response);
769 /* Copy reply data from socket */
770 if (response->result != WINBINDD_OK) {
771 return NSS_STATUS_NOTFOUND;
774 return NSS_STATUS_SUCCESS;
777 /* Handle simple types of requests */
779 NSS_STATUS winbindd_request_response(struct winbindd_context *ctx,
780 int req_type,
781 struct winbindd_request *request,
782 struct winbindd_response *response)
784 NSS_STATUS status = NSS_STATUS_UNAVAIL;
785 bool release_global_ctx = false;
787 if (ctx == NULL) {
788 ctx = get_wb_global_ctx();
789 release_global_ctx = true;
792 status = winbindd_send_request(ctx, req_type, 0, request);
793 if (status != NSS_STATUS_SUCCESS) {
794 goto out;
796 status = winbindd_get_response(ctx, response);
798 out:
799 if (release_global_ctx) {
800 put_wb_global_ctx();
802 return status;
805 NSS_STATUS winbindd_priv_request_response(struct winbindd_context *ctx,
806 int req_type,
807 struct winbindd_request *request,
808 struct winbindd_response *response)
810 NSS_STATUS status = NSS_STATUS_UNAVAIL;
811 bool release_global_ctx = false;
813 if (ctx == NULL) {
814 ctx = get_wb_global_ctx();
815 release_global_ctx = true;
818 status = winbindd_send_request(ctx, req_type, 1, request);
819 if (status != NSS_STATUS_SUCCESS) {
820 goto out;
822 status = winbindd_get_response(ctx, response);
824 out:
825 if (release_global_ctx) {
826 put_wb_global_ctx();
828 return status;
831 /* Create and free winbindd context */
833 struct winbindd_context *winbindd_ctx_create(void)
835 struct winbindd_context *ctx;
837 ctx = calloc(1, sizeof(struct winbindd_context));
839 if (!ctx) {
840 return NULL;
843 ctx->winbindd_fd = -1;
845 return ctx;
848 void winbindd_ctx_free(struct winbindd_context *ctx)
850 winbind_close_sock(ctx);
851 free(ctx);