+/*
+ * socket lookup function for linux.
+ * This code is used to associate uid, gid, jail/xid to packets,
+ * and store the info in a cache *ugp where they can be accessed quickly.
+ * The function returns 1 if the info is found, -1 otherwise.
+ *
+ * We do this only on selected protocols: TCP, ...
+ *
+ * Note- for locally generated, outgoing packets we don't need to
+ * do a lookup because the sk_buff already points to the socket where
+ * the info is.
+ */
+extern struct inet_hashinfo tcp_hashinfo;
+int
+linux_lookup(const int proto, const __be32 saddr, const __be16 sport,
+ const __be32 daddr, const __be16 dport,
+ struct sk_buff *skb, int dir, struct ip_fw_ugid *ugp)
+{
+ struct sock *sk;
+ int ret = -1; /* default return value */
+
+ if (proto != IPPROTO_TCP)
+ return -1;
+
+ if ((dir ? (void *)skb->dst : (void *)skb->dev) == NULL) {
+ panic(" -- this should not happen\n");
+ return -1;
+ }
+
+ /*
+ * inet_lookup above 2.6.24 has an additional 'net' parameter
+ * so we use a macro to conditionally supply it.
+ * Also we need to switch dst and src depending on the direction.
+ */
+#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,24)
+#define _OPT_NET_ARG
+#else /* 2.6.25 and above */
+#define _OPT_NET_ARG dev_net(skb->dev),
+#endif
+
+ sk = (dir) ?
+ inet_lookup(_OPT_NET_ARG &tcp_hashinfo,
+ daddr, dport, saddr, sport, // matches outgoing for server sockets
+ net_iif(skb)) :
+ inet_lookup(_OPT_NET_ARG &tcp_hashinfo,
+ saddr, sport, daddr, dport, // matches incoming for server sockets
+ skb->dev->ifindex);
+
+#undef _OPT_NET_ARG
+ /* no match, nothing to be done */
+ if (sk == NULL)
+ return -1;
+
+ /*
+ * On a match, sk is returned with a refcount.
+ * In tcp states less that TCP_TIME_WAIT sk references a struct sock
+ * which is what we want,
+ * otherwise it references a struct inet_timewait_sock which does
+ * not point to credentials.
+ * Once again we need conditional code because the UID and GID
+ * location changes between the two kernels.
+ */
+#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,28)
+/* use the current's real uid/gid */
+#define _CURR_UID f_uid
+#define _CURR_GID f_gid
+#else /* 2.6.29 and above */
+/* use the current's file access real uid/gid */
+#define _CURR_UID f_cred->fsuid
+#define _CURR_GID f_cred->fsgid
+#endif
+ if (sk->sk_state < TCP_TIME_WAIT && sk->sk_socket && sk->sk_socket->file) {
+ ugp->fw_uid = sk->sk_socket->file->_CURR_UID;
+ ret = 1;
+ }
+ sock_put(sk);
+#undef _CURR_UID
+#undef _CURR_GID
+
+ //printf("%s dir %d skb->dst %p skb->dev %p ret %d\n", __FUNCTION__, dir, skb->dst, skb->dev, ret);
+ return ret;
+}