TODO: nmbd... (doesn't compile yet)
[metze/samba/wip.git] / source3 / nmbd / nmbd_packets.c
index 1e72c188882ab897edeaae44712847aef1d07d92..fe21a6b509c0f9b179818c8aca282488c681febf 100644 (file)
 #include "includes.h"
 #include "nmbd/nmbd.h"
 #include "../lib/util/select.h"
+#include "system/select.h"
+#include "libsmb/libsmb.h"
 
 extern int ClientNMB;
 extern int ClientDGRAM;
 extern int global_nmb_port;
 
-extern int num_response_packets;
-
 bool rescan_listen_set = False;
 
+static struct nb_packet_server *packet_server;
+
+bool nmbd_init_packet_server(void)
+{
+       NTSTATUS status;
+
+       status = nb_packet_server_create(
+               NULL, nmbd_event_context(),
+               lp_parm_int(-1, "nmbd", "unexpected_clients", 200),
+               &packet_server);
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(0, ("ERROR: nb_packet_server_create failed: %s\n",
+                         nt_errstr(status)));
+               return false;
+       }
+       return true;
+}
+
 
 /*******************************************************************
   The global packet linked-list. Incoming entries are 
@@ -74,12 +92,12 @@ static int find_subnet_mailslot_fd_for_address( struct in_addr local_ip )
 Get/Set problematic nb_flags as network byte order 16 bit int.
 **************************************************************************/
 
-uint16 get_nb_flags(char *buf)
+uint16_t get_nb_flags(char *buf)
 {
-       return ((((uint16)*buf)&0xFFFF) & NB_FLGMSK);
+       return ((((uint16_t)*buf)&0xFFFF) & NB_FLGMSK);
 }
 
-void set_nb_flags(char *buf, uint16 nb_flags)
+void set_nb_flags(char *buf, uint16_t nb_flags)
 {
        *buf++ = ((nb_flags & NB_FLGMSK) & 0xFF);
        *buf = '\0';
@@ -89,7 +107,7 @@ void set_nb_flags(char *buf, uint16 nb_flags)
 Dumps out the browse packet data.
 **************************************************************************/
 
-static void debug_browse_data(char *outbuf, int len)
+static void debug_browse_data(const char *outbuf, int len)
 {
        int i,j;
 
@@ -125,12 +143,12 @@ static void debug_browse_data(char *outbuf, int len)
   Generates the unique transaction identifier
 **************************************************************************/
 
-static uint16 name_trn_id=0;
+static uint16_t name_trn_id=0;
 
-static uint16 generate_name_trn_id(void)
+static uint16_t generate_name_trn_id(void)
 {
        if (!name_trn_id) {
-               name_trn_id = ((unsigned)time(NULL)%(unsigned)0x7FFF) + ((unsigned)sys_getpid()%(unsigned)100);
+               name_trn_id = ((unsigned)time(NULL)%(unsigned)0x7FFF) + ((unsigned)getpid()%(unsigned)100);
        }
        name_trn_id = (name_trn_id+1) % (unsigned)0x7FFF;
        return name_trn_id;
@@ -222,7 +240,7 @@ static struct packet_struct *create_and_init_netbios_packet(struct nmb_name *nmb
 **************************************************************************/
 
 static bool create_and_init_additional_record(struct packet_struct *packet,
-                                                     uint16 nb_flags,
+                                                     uint16_t nb_flags,
                                                      const struct in_addr *register_ip)
 {
        struct nmb_packet *nmb = &packet->packet.nmb;
@@ -315,7 +333,7 @@ static bool initiate_name_query_packet_from_wins_server( struct packet_struct *p
 **************************************************************************/
 
 static bool initiate_name_register_packet( struct packet_struct *packet,
-                                    uint16 nb_flags, const struct in_addr *register_ip)
+                                    uint16_t nb_flags, const struct in_addr *register_ip)
 {
        struct nmb_packet *nmb = &packet->packet.nmb;
 
@@ -339,7 +357,7 @@ static bool initiate_name_register_packet( struct packet_struct *packet,
 **************************************************************************/
 
 static bool initiate_multihomed_name_register_packet(struct packet_struct *packet,
-                                                    uint16 nb_flags, struct in_addr *register_ip)
+                                                    uint16_t nb_flags, struct in_addr *register_ip)
 {
        struct nmb_packet *nmb = &packet->packet.nmb;
        fstring second_ip_buf;
@@ -367,7 +385,7 @@ for name %s IP %s (bcast=%s) to IP %s\n",
 **************************************************************************/
 
 static bool initiate_name_refresh_packet( struct packet_struct *packet,
-                                   uint16 nb_flags, struct in_addr *refresh_ip)
+                                   uint16_t nb_flags, struct in_addr *refresh_ip)
 {
        struct nmb_packet *nmb = &packet->packet.nmb;
 
@@ -391,7 +409,7 @@ static bool initiate_name_refresh_packet( struct packet_struct *packet,
 **************************************************************************/
 
 static bool initiate_name_release_packet( struct packet_struct *packet,
-                                   uint16 nb_flags, struct in_addr *release_ip)
+                                   uint16_t nb_flags, struct in_addr *release_ip)
 {
        struct nmb_packet *nmb = &packet->packet.nmb;
 
@@ -464,7 +482,7 @@ struct response_record *queue_register_name( struct subnet_record *subrec,
                           register_name_fail_function fail_fn,
                           struct userdata_struct *userdata,
                           struct nmb_name *nmbname,
-                          uint16 nb_flags)
+                          uint16_t nb_flags)
 {
        struct packet_struct *p;
        struct response_record *rrec;
@@ -479,7 +497,7 @@ struct response_record *queue_register_name( struct subnet_record *subrec,
                return NULL;
 
        in_addr_to_sockaddr_storage(&ss, subrec->bcast_ip);
-       pss = iface_ip((struct sockaddr *)&ss);
+       pss = iface_ip((struct sockaddr *)(void *)&ss);
        if (!pss || pss->ss_family != AF_INET) {
                p->locked = False;
                free_packet(p);
@@ -515,7 +533,7 @@ struct response_record *queue_register_name( struct subnet_record *subrec,
 void queue_wins_refresh(struct nmb_name *nmbname,
                        response_function resp_fn,
                        timeout_response_function timeout_fn,
-                       uint16 nb_flags,
+                       uint16_t nb_flags,
                        struct in_addr refresh_ip,
                        const char *tag)
 {
@@ -582,7 +600,7 @@ struct response_record *queue_register_multihomed_name( struct subnet_record *su
                                                        register_name_fail_function fail_fn,
                                                        struct userdata_struct *userdata,
                                                        struct nmb_name *nmbname,
-                                                       uint16 nb_flags,
+                                                       uint16_t nb_flags,
                                                        struct in_addr register_ip,
                                                        struct in_addr wins_ip)
 {
@@ -640,7 +658,7 @@ struct response_record *queue_release_name( struct subnet_record *subrec,
                                            release_name_fail_function fail_fn,
                                            struct userdata_struct *userdata,
                                            struct nmb_name *nmbname,
-                                           uint16 nb_flags,
+                                           uint16_t nb_flags,
                                            struct in_addr release_ip,
                                            struct in_addr dest_ip)
 {
@@ -943,9 +961,10 @@ void reply_netbios_packet(struct packet_struct *orig_packet,
                        return;
        }
 
-       DEBUG(4,("reply_netbios_packet: sending a reply of packet type: %s %s to ip %s \
-for id %hu\n", packet_type, nmb_namestr(&orig_nmb->question.question_name),
-                       inet_ntoa(packet.ip), orig_nmb->header.name_trn_id));
+       DEBUG(4, ("reply_netbios_packet: sending a reply of packet type: %s "
+                 "%s to ip %s for id %d\n", packet_type,
+                 nmb_namestr(&orig_nmb->question.question_name),
+                 inet_ntoa(packet.ip), orig_nmb->header.name_trn_id));
 
        nmb->header.name_trn_id = orig_nmb->header.name_trn_id;
        nmb->header.opcode = opcode;
@@ -1012,7 +1031,7 @@ for id %hu\n", packet_type, nmb_namestr(&orig_nmb->question.question_name),
 
 void queue_packet(struct packet_struct *packet)
 {
-       DLIST_ADD_END(packet_queue, packet, struct packet_struct *);
+       DLIST_ADD_END(packet_queue, packet);
 }
 
 /****************************************************************************
@@ -1043,7 +1062,7 @@ static struct subnet_record *find_subnet_for_dgram_browse_packet(struct packet_s
 Dispatch a browse frame from port 138 to the correct processing function.
 ****************************************************************************/
 
-static void process_browse_packet(struct packet_struct *p, char *buf,int len)
+static void process_browse_packet(struct packet_struct *p, const char *buf,int len)
 {
        struct dgram_packet *dgram = &p->packet.dgram;
        int command = CVAL(buf,0);
@@ -1053,9 +1072,9 @@ static void process_browse_packet(struct packet_struct *p, char *buf,int len)
 
        /* Drop the packet if it's a different NetBIOS scope, or the source is from one of our names. */
        pull_ascii(scope, dgram->dest_name.scope, 64, 64, STR_TERMINATE);
-       if (!strequal(scope, global_scope())) {
+       if (!strequal(scope, lp_netbios_scope())) {
                DEBUG(7,("process_browse_packet: Discarding datagram from IP %s. Scope (%s) \
-mismatch with our scope (%s).\n", inet_ntoa(p->ip), scope, global_scope()));
+mismatch with our scope (%s).\n", inet_ntoa(p->ip), scope, lp_netbios_scope()));
                return;
        }
 
@@ -1130,7 +1149,7 @@ command code %d from %s IP %s to %s\n", subrec->subnet_name, command, nmb_namest
  Dispatch a LanMan browse frame from port 138 to the correct processing function.
 ****************************************************************************/
 
-static void process_lanman_packet(struct packet_struct *p, char *buf,int len)
+static void process_lanman_packet(struct packet_struct *p, const char *buf,int len)
 {
        struct dgram_packet *dgram = &p->packet.dgram;
        int command = SVAL(buf,0);
@@ -1141,9 +1160,9 @@ static void process_lanman_packet(struct packet_struct *p, char *buf,int len)
        /* Drop the packet if it's a different NetBIOS scope, or the source is from one of our names. */
 
        pull_ascii(scope, dgram->dest_name.scope, 64, 64, STR_TERMINATE);
-       if (!strequal(scope, global_scope())) {
+       if (!strequal(scope, lp_netbios_scope())) {
                DEBUG(7,("process_lanman_packet: Discarding datagram from IP %s. Scope (%s) \
-mismatch with our scope (%s).\n", inet_ntoa(p->ip), scope, global_scope()));
+mismatch with our scope (%s).\n", inet_ntoa(p->ip), scope, lp_netbios_scope()));
                return;
        }
 
@@ -1197,21 +1216,21 @@ static bool listening(struct packet_struct *p,struct nmb_name *nbname)
 
 static void process_dgram(struct packet_struct *p)
 {
-       char *buf;
-       char *buf2;
+       const char *buf;
+       const char *buf2;
        int len;
        struct dgram_packet *dgram = &p->packet.dgram;
 
        /* If we aren't listening to the destination name then ignore the packet */
        if (!listening(p,&dgram->dest_name)) {
-                       unexpected_packet(p);
+                       nb_packet_dispatch(packet_server, p);
                        DEBUG(5,("process_dgram: ignoring dgram packet sent to name %s from %s\n",
                                nmb_namestr(&dgram->dest_name), inet_ntoa(p->ip)));
                        return;
        }
 
        if (dgram->header.msg_type != 0x10 && dgram->header.msg_type != 0x11 && dgram->header.msg_type != 0x12) {
-               unexpected_packet(p);
+               nb_packet_dispatch(packet_server, p);
                /* Don't process error packets etc yet */
                DEBUG(5,("process_dgram: ignoring dgram packet sent to name %s from IP %s as it is \
 an error packet of type %x\n", nmb_namestr(&dgram->dest_name), inet_ntoa(p->ip), dgram->header.msg_type));
@@ -1271,33 +1290,33 @@ packet sent to name %s from IP %s\n",
 
        DEBUG(4,("process_dgram: datagram from %s to %s IP %s for %s of type %d len=%d\n",
                nmb_namestr(&dgram->source_name),nmb_namestr(&dgram->dest_name),
-               inet_ntoa(p->ip), smb_buf(buf),CVAL(buf2,0),len));
+               inet_ntoa(p->ip), smb_buf_const(buf),CVAL(buf2,0),len));
 
        /* Datagram packet received for the browser mailslot */
-       if (strequal(smb_buf(buf),BROWSE_MAILSLOT)) {
+       if (strequal(smb_buf_const(buf),BROWSE_MAILSLOT)) {
                process_browse_packet(p,buf2,len);
                return;
        }
 
        /* Datagram packet received for the LAN Manager mailslot */
-       if (strequal(smb_buf(buf),LANMAN_MAILSLOT)) {
+       if (strequal(smb_buf_const(buf),LANMAN_MAILSLOT)) {
                process_lanman_packet(p,buf2,len);
                return;
        }
 
        /* Datagram packet received for the domain logon mailslot */
-       if (strequal(smb_buf(buf),NET_LOGON_MAILSLOT)) {
+       if (strequal(smb_buf_const(buf),NET_LOGON_MAILSLOT)) {
                process_logon_packet(p,buf2,len,NET_LOGON_MAILSLOT);
                return;
        }
 
        /* Datagram packet received for the NT domain logon mailslot */
-       if (strequal(smb_buf(buf),NT_LOGON_MAILSLOT)) {
+       if (strequal(smb_buf_const(buf),NT_LOGON_MAILSLOT)) {
                process_logon_packet(p,buf2,len,NT_LOGON_MAILSLOT);
                return;
        }
 
-       unexpected_packet(p);
+       nb_packet_dispatch(packet_server, p);
 }
 
 /****************************************************************************
@@ -1415,15 +1434,17 @@ static struct subnet_record *find_subnet_for_nmb_packet( struct packet_struct *p
 
                rrec = find_response_record( &subrec, nmb->header.name_trn_id);
                if(rrec == NULL) {
-                       DEBUG(3,("find_subnet_for_nmb_packet: response record not found for response id %hu\n",
-                               nmb->header.name_trn_id));
-                       unexpected_packet(p);
+                       DEBUG(3, ("find_subnet_for_nmb_packet: response "
+                                 "record not found for response id %d\n",
+                                 nmb->header.name_trn_id));
+                       nb_packet_dispatch(packet_server, p);
                        return NULL;
                }
 
                if(subrec == NULL) {
-                       DEBUG(0,("find_subnet_for_nmb_packet: subnet record not found for response id %hu\n",
-                               nmb->header.name_trn_id));
+                       DEBUG(0, ("find_subnet_for_nmb_packet: subnet record "
+                                 "not found for response id %d\n",
+                                 nmb->header.name_trn_id));
                        return NULL;
                }
 
@@ -1545,8 +1566,9 @@ static void process_nmb_response(struct packet_struct *p)
                return;
 
        if(rrec == NULL) {
-               DEBUG(0,("process_nmb_response: response packet received but no response record \
-found for id = %hu. Ignoring packet.\n", nmb->header.name_trn_id));
+               DEBUG(0, ("process_nmb_response: response packet received but "
+                         "no response record found for id = %d. Ignoring "
+                         "packet.\n", nmb->header.name_trn_id));
                return;
        }
 
@@ -1656,93 +1678,96 @@ on subnet %s\n", rrec->response_id, inet_ntoa(rrec->packet->ip), subrec->subnet_
   plus the broadcast sockets.
 ***************************************************************************/
 
-static bool create_listen_fdset(fd_set **ppset, int **psock_array, int *listen_number, int *maxfd)
+struct socket_attributes {
+       enum packet_type type;
+       bool broadcast;
+       int fd;
+       bool triggered;
+};
+
+static bool create_listen_array(struct socket_attributes **pattrs,
+                                 int *pnum_sockets)
 {
-       int *sock_array = NULL;
        struct subnet_record *subrec = NULL;
        int count = 0;
        int num = 0;
-       fd_set *pset = SMB_MALLOC_P(fd_set);
-
-       if(pset == NULL) {
-               DEBUG(0,("create_listen_fdset: malloc fail !\n"));
-               return True;
-       }
+       struct socket_attributes *attrs;
 
-       /* The Client* sockets */
-       count++;
+       /* The ClientNMB and ClientDGRAM sockets */
+       count = 2;
 
        /* Check that we can add all the fd's we need. */
-       for (subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec))
-               count++;
-
-       /* each interface gets 4 sockets */
-       count *= 4;
-
-       if(count > FD_SETSIZE) {
-               DEBUG(0,("create_listen_fdset: Too many file descriptors needed (%d). We can \
-only use %d.\n", count, FD_SETSIZE));
-               SAFE_FREE(pset);
-               return True;
+       for (subrec = FIRST_SUBNET;
+            subrec != NULL;
+            subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
+               if (subrec->nmb_sock != -1) {
+                       count += 1;
+               }
+               if (subrec->dgram_sock != -1) {
+                       count += 1;
+               }
+               if (subrec->nmb_bcast != -1) {
+                       count += 1;
+               }
+               if (subrec->dgram_bcast != -1) {
+                       count += 1;
+               }
        }
 
-       if((sock_array = SMB_MALLOC_ARRAY(int, count)) == NULL) {
-               DEBUG(0,("create_listen_fdset: malloc fail for socket array. size %d\n", count));
-               SAFE_FREE(pset);
-               return True;
+       attrs = talloc_zero_array(NULL, struct socket_attributes, count);
+       if (attrs == NULL) {
+               DEBUG(1, ("talloc fail for attrs. "
+                         "size %d\n", count));
+               return true;
        }
 
-       FD_ZERO(pset);
+       num = 0;
 
-       /* Add in the lp_socket_address() interface on 137. */
-       FD_SET(ClientNMB,pset);
-       sock_array[num++] = ClientNMB;
-       *maxfd = MAX( *maxfd, ClientNMB);
+       attrs[num].fd = ClientNMB;
+       attrs[num].type = NMB_PACKET;
+       attrs[num].broadcast = false;
+       num += 1;
 
-       /* the lp_socket_address() interface has only one socket */
-       sock_array[num++] = -1;
+       attrs[num].fd = ClientDGRAM;
+       attrs[num].type = DGRAM_PACKET;
+       attrs[num].broadcast = false;
+       num += 1;
 
-       /* Add in the 137 sockets on all the interfaces. */
        for (subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
-               FD_SET(subrec->nmb_sock,pset);
-               sock_array[num++] = subrec->nmb_sock;
-               *maxfd = MAX( *maxfd, subrec->nmb_sock);
 
-               sock_array[num++] = subrec->nmb_bcast;
-               if (subrec->nmb_bcast != -1) {
-                       FD_SET(subrec->nmb_bcast,pset);
-                       *maxfd = MAX( *maxfd, subrec->nmb_bcast);
+               if (subrec->nmb_sock != -1) {
+                       attrs[num].fd = subrec->nmb_sock;
+                       attrs[num].type = NMB_PACKET;
+                       attrs[num].broadcast = false;
+                       num += 1;
                }
-       }
 
-       /* Add in the lp_socket_address() interface on 138. */
-       FD_SET(ClientDGRAM,pset);
-       sock_array[num++] = ClientDGRAM;
-       *maxfd = MAX( *maxfd, ClientDGRAM);
-
-       /* the lp_socket_address() interface has only one socket */
-       sock_array[num++] = -1;
+               if (subrec->nmb_bcast != -1) {
+                       attrs[num].fd = subrec->nmb_bcast;
+                       attrs[num].type = NMB_PACKET;
+                       attrs[num].broadcast = true;
+                       num += 1;
+               }
 
-       /* Add in the 138 sockets on all the interfaces. */
-       for (subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
-               FD_SET(subrec->dgram_sock,pset);
-               sock_array[num++] = subrec->dgram_sock;
-               *maxfd = MAX( *maxfd, subrec->dgram_sock);
+               if (subrec->dgram_sock != -1) {
+                       attrs[num].fd = subrec->dgram_sock;
+                       attrs[num].type = DGRAM_PACKET;
+                       attrs[num].broadcast = false;
+                       num += 1;
+               }
 
-               sock_array[num++] = subrec->dgram_bcast;
                if (subrec->dgram_bcast != -1) {
-                       FD_SET(subrec->dgram_bcast,pset);
-                       *maxfd = MAX( *maxfd, subrec->dgram_bcast);
+                       attrs[num].fd = subrec->dgram_bcast;
+                       attrs[num].type = DGRAM_PACKET;
+                       attrs[num].broadcast = true;
+                       num += 1;
                }
        }
 
-       *listen_number = count;
-
-       SAFE_FREE(*ppset);
-       SAFE_FREE(*psock_array);
+       TALLOC_FREE(*pattrs);
+       *pattrs = attrs;
 
-       *ppset = pset;
-       *psock_array = sock_array;
+       *pnum_sockets = count;
 
        return False;
 }
@@ -1802,6 +1827,7 @@ static bool store_processed_packet(struct processed_packet **pp_processed_packet
        } else if (packet->packet_type == DGRAM_PACKET) {
                p->packet_id = packet->packet.dgram.header.dgm_id;
        } else {
+               SAFE_FREE(p);
                return false;
        }
 
@@ -1824,50 +1850,101 @@ static void free_processed_packet_list(struct processed_packet **pp_processed_pa
        }
 }
 
+/****************************************************************************
+ Timeout callback - just notice we timed out.
+***************************************************************************/
+
+static void nmbd_timeout_handler(struct tevent_context *ev,
+                       struct tevent_timer *te,
+                       struct timeval current_time,
+                       void *private_data)
+{
+       bool *got_timeout = private_data;
+       *got_timeout = true;
+}
+
+/****************************************************************************
+ fd callback - remember the fd that triggered.
+***************************************************************************/
+
+static void nmbd_fd_handler(struct tevent_context *ev,
+                               struct tevent_fd *fde,
+                               uint16_t flags,
+                               void *private_data)
+{
+       struct socket_attributes *attr = private_data;
+       attr->triggered = true;
+}
+
 /****************************************************************************
   Listens for NMB or DGRAM packets, and queues them.
   return True if the socket is dead
 ***************************************************************************/
 
-bool listen_for_packets(bool run_election)
+bool listen_for_packets(struct messaging_context *msg, bool run_election)
 {
-       static fd_set *listen_set = NULL;
+       static struct socket_attributes *attrs = NULL;
        static int listen_number = 0;
-       static int *sock_array = NULL;
+       int num_sockets;
        int i;
-       static int maxfd = 0;
+       int loop_rtn;
+       int timeout_secs;
 
-       fd_set r_fds;
-       fd_set w_fds;
-       int selrtn = 0;
-       struct timeval timeout;
 #ifndef SYNC_DNS
        int dns_fd;
+       int dns_pollidx = -1;
 #endif
        struct processed_packet *processed_packet_list = NULL;
+       struct tevent_timer *te = NULL;
+       bool got_timeout = false;
+       TALLOC_CTX *frame = talloc_stackframe();
 
-       if(listen_set == NULL || rescan_listen_set) {
-               if(create_listen_fdset(&listen_set, &sock_array, &listen_number, &maxfd)) {
+       if ((attrs == NULL) || rescan_listen_set) {
+               if (create_listen_array(&attrs, &listen_number)) {
                        DEBUG(0,("listen_for_packets: Fatal error. unable to create listen set. Exiting.\n"));
+                       TALLOC_FREE(frame);
                        return True;
                }
                rescan_listen_set = False;
        }
 
-       memcpy((char *)&r_fds, (char *)listen_set, sizeof(fd_set));
-       FD_ZERO(&w_fds);
+       num_sockets = listen_number;
 
 #ifndef SYNC_DNS
        dns_fd = asyncdns_fd();
        if (dns_fd != -1) {
-               FD_SET(dns_fd, &r_fds);
-               maxfd = MAX( maxfd, dns_fd);
+               attrs = talloc_realloc(NULL,
+                                       attrs,
+                                       struct socket_attributes,
+                                       num_sockets + 1);
+               if (attrs == NULL) {
+                       TALLOC_FREE(frame);
+                       return true;
+               }
+               dns_pollidx = num_sockets;
+               attrs[dns_pollidx].fd = dns_fd;
+               /*
+                * dummy values, we only need
+                * fd and triggered.
+                */
+               attrs[dns_pollidx].type = NMB_PACKET;
+               attrs[dns_pollidx].broadcast = false;
+               num_sockets += 1;
        }
 #endif
 
-       /* Process a signal and timer events now... */
-       if (run_events(nmbd_event_context(), &selrtn, NULL, NULL)) {
-               return False;
+       for (i=0; i<num_sockets; i++) {
+               struct tevent_fd *tfd = tevent_add_fd(nmbd_event_context(),
+                                                       frame,
+                                                       attrs[i].fd,
+                                                       TEVENT_FD_READ,
+                                                       nmbd_fd_handler,
+                                                       &attrs[i]);
+               if (tfd == NULL) {
+                       TALLOC_FREE(frame);
+                       return true;
+               }
+               attrs[i].triggered = false;
        }
 
        /*
@@ -1877,25 +1954,40 @@ bool listen_for_packets(bool run_election)
         * the time we are expecting the next netbios packet.
         */
 
-       timeout.tv_sec = (run_election||num_response_packets) ? 1 : NMBD_SELECT_LOOP;
-       timeout.tv_usec = 0;
+       if (run_election||num_response_packets) {
+               timeout_secs = 1;
+       } else {
+               timeout_secs = NMBD_SELECT_LOOP;
+       }
 
-       event_add_to_select_args(nmbd_event_context(),
-                                &r_fds, &w_fds, &timeout, &maxfd);
+       te = tevent_add_timer(nmbd_event_context(),
+                               frame,
+                               tevent_timeval_current_ofs(timeout_secs, 0),
+                               nmbd_timeout_handler,
+                               &got_timeout);
+       if (te == NULL) {
+               TALLOC_FREE(frame);
+               return true;
+       }
 
-       selrtn = sys_select(maxfd+1,&r_fds,&w_fds,NULL,&timeout);
+       loop_rtn = tevent_loop_once(nmbd_event_context());
 
-       if (run_events(nmbd_event_context(), &selrtn, &r_fds, &w_fds)) {
-               return False;
+       if (loop_rtn == -1) {
+               TALLOC_FREE(frame);
+               return true;
        }
 
-       if (selrtn == -1) {
-               return False;
+       if (got_timeout) {
+               TALLOC_FREE(frame);
+               return false;
        }
 
 #ifndef SYNC_DNS
-       if (dns_fd != -1 && FD_ISSET(dns_fd,&r_fds)) {
-               run_dns_queue();
+       if ((dns_fd != -1) && (dns_pollidx != -1) &&
+           attrs[dns_pollidx].triggered){
+               run_dns_queue(msg);
+               TALLOC_FREE(frame);
+               return false;
        }
 #endif
 
@@ -1905,17 +1997,12 @@ bool listen_for_packets(bool run_election)
                const char *packet_name;
                int client_fd;
                int client_port;
-               bool is_requested_send_reply = false;
-
-               if (sock_array[i] == -1) {
-                       continue;
-               }
 
-               if (!FD_ISSET(sock_array[i],&r_fds)) {
+               if (!attrs[i].triggered) {
                        continue;
                }
 
-               if (i < (listen_number/2)) {
+               if (attrs[i].type == NMB_PACKET) {
                        /* Port 137 */
                        packet_type = NMB_PACKET;
                        packet_name = "nmb";
@@ -1929,19 +2016,17 @@ bool listen_for_packets(bool run_election)
                        client_port = DGRAM_PORT;
                }
 
-               packet = read_packet(sock_array[i], packet_type);
+               packet = read_packet(attrs[i].fd, packet_type);
                if (!packet) {
                        continue;
                }
 
-               is_requested_send_reply = is_requested_send_packet(packet);
-
                /*
                 * If we got a packet on the broadcast socket and interfaces
                 * only is set then check it came from one of our local nets.
                 */
                if (lp_bind_interfaces_only() &&
-                   (sock_array[i] == client_fd) &&
+                   (attrs[i].fd == client_fd) &&
                    (!is_local_net_v4(packet->ip))) {
                        DEBUG(7,("discarding %s packet sent to broadcast socket from %s:%d\n",
                                packet_name, inet_ntoa(packet->ip), packet->port));
@@ -1949,22 +2034,23 @@ bool listen_for_packets(bool run_election)
                        continue;
                }
 
-               if (!is_requested_send_reply &&
-                   (is_loopback_ip_v4(packet->ip) || ismyip_v4(packet->ip)) &&
-                   packet->port == client_port)
-               {
-                       if (client_port == DGRAM_PORT) {
-                               DEBUG(7,("discarding own dgram packet from %s:%d\n",
-                                       inet_ntoa(packet->ip),packet->port));
-                               free_packet(packet);
-                               continue;
-                       }
-
-                       if (packet->packet.nmb.header.nm_flags.bcast) {
-                               DEBUG(7,("discarding own nmb bcast packet from %s:%d\n",
-                                       inet_ntoa(packet->ip),packet->port));
-                               free_packet(packet);
-                               continue;
+               if (!IS_DC) {
+                       if ((is_loopback_ip_v4(packet->ip) || ismyip_v4(packet->ip)) &&
+                       packet->port == client_port)
+                       {
+                               if (client_port == DGRAM_PORT) {
+                                       DEBUG(7,("discarding own dgram packet from %s:%d\n",
+                                               inet_ntoa(packet->ip),packet->port));
+                                       free_packet(packet);
+                                       continue;
+                               }
+
+                               if (packet->packet.nmb.header.nm_flags.bcast) {
+                                       DEBUG(7,("discarding own nmb bcast packet from %s:%d\n",
+                                               inet_ntoa(packet->ip),packet->port));
+                                       free_packet(packet);
+                                       continue;
+                               }
                        }
                }
 
@@ -1977,27 +2063,19 @@ bool listen_for_packets(bool run_election)
 
                store_processed_packet(&processed_packet_list, packet);
 
-               /*
-                * 0,2,4,... are unicast sockets
-                * 1,3,5,... are broadcast sockets
-                *
-                * on broadcast socket we only receive packets
-                * and send replies via the unicast socket.
-                *
-                * 0,1 and 2,3 and ... belong together.
-                */
-               if ((i % 2) != 0) {
+               if (attrs[i].broadcast) {
                        /* this is a broadcast socket */
-                       packet->send_fd = sock_array[i-1];
+                       packet->send_fd = attrs[i-1].fd;
                } else {
                        /* this is already a unicast socket */
-                       packet->send_fd = sock_array[i];
+                       packet->send_fd = attrs[i].fd;
                }
 
                queue_packet(packet);
        }
 
        free_processed_packet_list(&processed_packet_list);
+       TALLOC_FREE(frame);
        return False;
 }
 
@@ -2061,7 +2139,7 @@ bool send_mailslot(bool unique, const char *mailslot,char *buf, size_t len,
        SSVAL(ptr,smb_vwv15,1);
        SSVAL(ptr,smb_vwv16,2);
        p2 = smb_buf(ptr);
-       safe_strcpy_base(p2, mailslot, dgram->data, sizeof(dgram->data));
+       strlcpy_base(p2, mailslot, dgram->data, sizeof(dgram->data));
        p2 = skip_string(ptr,MAX_DGRAM_SIZE,p2);
 
        if (((p2+len) > dgram->data+sizeof(dgram->data)) || ((p2+len) < p2)) {