16db26757Swiz /*
26db26757Swiz * Copyright (c) 2022 Nicholas Marriott <nicholas.marriott@gmail.com>
36db26757Swiz *
46db26757Swiz * Permission to use, copy, modify, and distribute this software for any
56db26757Swiz * purpose with or without fee is hereby granted, provided that the above
66db26757Swiz * copyright notice and this permission notice appear in all copies.
76db26757Swiz *
86db26757Swiz * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
96db26757Swiz * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
106db26757Swiz * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
116db26757Swiz * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
126db26757Swiz * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
136db26757Swiz * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
146db26757Swiz * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
156db26757Swiz */
166db26757Swiz
176db26757Swiz #include <sys/types.h>
186db26757Swiz #include <sys/socket.h>
196db26757Swiz
206db26757Swiz #include <stdio.h>
21*c23f9150Swiz #include <unistd.h>
226db26757Swiz
236db26757Swiz #ifdef HAVE_UCRED_H
246db26757Swiz #include <ucred.h>
256db26757Swiz #endif
266db26757Swiz
276db26757Swiz #include "compat.h"
286db26757Swiz
296db26757Swiz int
getpeereid(int s,uid_t * uid,gid_t * gid)306db26757Swiz getpeereid(int s, uid_t *uid, gid_t *gid)
316db26757Swiz {
326db26757Swiz #ifdef HAVE_SO_PEERCRED
336db26757Swiz struct ucred uc;
346db26757Swiz int len = sizeof uc;
356db26757Swiz
366db26757Swiz if (getsockopt(s, SOL_SOCKET, SO_PEERCRED, &uc, &len) == -1)
376db26757Swiz return (-1);
386db26757Swiz *uid = uc.uid;
396db26757Swiz *gid = uc.gid;
406db26757Swiz return (0);
416db26757Swiz #elif defined(HAVE_GETPEERUCRED)
426db26757Swiz ucred_t *ucred = NULL;
436db26757Swiz
446db26757Swiz if (getpeerucred(s, &ucred) == -1)
456db26757Swiz return (-1);
466db26757Swiz if ((*uid = ucred_geteuid(ucred)) == -1)
476db26757Swiz return (-1);
486db26757Swiz if ((*gid = ucred_getrgid(ucred)) == -1)
496db26757Swiz return (-1);
506db26757Swiz ucred_free(ucred);
516db26757Swiz return (0);
526db26757Swiz #else
53*c23f9150Swiz *uid = geteuid();
54*c23f9150Swiz *gid = getegid();
55*c23f9150Swiz return (0);
566db26757Swiz #endif
576db26757Swiz }
58