r23784: use the GPLv3 boilerplate as recommended by the FSF and the license text
[tprouty/samba.git] / source / lib / messages.c
index 18f9d0c1d50be2c53a370b1604865766b268bd54..a7925ace7ae053dba62dc0d4a47e592f027339a3 100644 (file)
@@ -1,12 +1,14 @@
 /* 
-   Unix SMB/Netbios implementation.
-   Version 3.0
+   Unix SMB/CIFS implementation.
    Samba internal messaging functions
    Copyright (C) Andrew Tridgell 2000
+   Copyright (C) 2001 by Martin Pool
+   Copyright (C) 2002 by Jeremy Allison
+   Copyright (C) 2007 by Volker Lendecke
    
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2 of the License, or
+   the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    GNU General Public License for more details.
    
    You should have received a copy of the GNU General Public License
-   along with this program; if not, write to the Free Software
-   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
-/* this module is used for internal messaging between Samba daemons. 
+/**
+  @defgroup messages Internal messaging framework
+  @{
+  @file messages.c
+  
+  @brief  Module for internal messaging between Samba daemons. 
 
    The idea is that if a part of Samba wants to do communication with
    another Samba process then it will do a message_register() of a
    dispatch function, and use message_send_pid() to send messages to
    that process.
 
+   The dispatch function is given the pid of the sender, and it can
+   use that to reply by message_send_pid().  See ping_message() for a
+   simple example.
+
+   @caution Dispatch functions must be able to cope with incoming
+   messages on an *odd* byte boundary.
+
    This system doesn't have any inherent size limitations but is not
    very efficient for large messages or when messages are sent in very
    quick succession.
 */
 
 #include "includes.h"
-
-/* the locking database handle */
-static TDB_CONTEXT *tdb;
-static int received_signal;
-
-/* change the message version with any incompatible changes in the protocol */
-#define MESSAGE_VERSION 1
-
-struct message_rec {
-       int msg_version;
-       int msg_type;
-       pid_t dest;
-       pid_t src;
-       size_t len;
+#include "librpc/gen_ndr/messaging.h"
+#include "librpc/gen_ndr/ndr_messaging.h"
+
+struct messaging_callback {
+       struct messaging_callback *prev, *next;
+       uint32 msg_type;
+       void (*fn)(struct messaging_context *msg, void *private_data, 
+                  uint32_t msg_type, 
+                  struct server_id server_id, DATA_BLOB *data);
+       void *private_data;
 };
 
-/* we have a linked list of dispatch handlers */
-static struct dispatch_fns {
-       struct dispatch_fns *next, *prev;
-       int msg_type;
-       void (*fn)(int msg_type, pid_t pid, void *buf, size_t len);
-} *dispatch_fns;
-
 /****************************************************************************
-notifications come in as signals
+ A useful function for testing the message system.
 ****************************************************************************/
-static void sig_usr1(void)
-{
-       received_signal = 1;
-       sys_select_signal();
-}
 
-/****************************************************************************
-a useful function for testing the message system
-****************************************************************************/
-void ping_message(int msg_type, pid_t src, void *buf, size_t len)
+static void ping_message(struct messaging_context *msg_ctx,
+                        void *private_data,
+                        uint32_t msg_type,
+                        struct server_id src,
+                        DATA_BLOB *data)
 {
-       DEBUG(1,("INFO: Received PING message from PID %u\n",(unsigned int)src));
-       message_send_pid(src, MSG_PONG, buf, len, True);
+       const char *msg = data->data ? (const char *)data->data : "none";
+
+       DEBUG(1,("INFO: Received PING message from PID %s [%s]\n",
+                procid_str_static(&src), msg));
+       messaging_send(msg_ctx, src, MSG_PONG, data);
 }
+
 /****************************************************************************
-return current debug level
+ Register/replace a dispatch function for a particular message type.
+ JRA changed Dec 13 2006. Only one message handler now permitted per type.
+ *NOTE*: Dispatch functions must be able to cope with incoming
+ messages on an *odd* byte boundary.
 ****************************************************************************/
-void debuglevel_message(int msg_type, pid_t src, void *buf, size_t len)
-{
-       DEBUG(1,("INFO: Received REQ_DEBUGLEVEL message from PID %u\n",(unsigned int)src));
-       message_send_pid(src, MSG_DEBUGLEVEL, DEBUGLEVEL_CLASS, sizeof(DEBUGLEVEL_CLASS), True);
-}
+
+struct msg_all {
+       struct messaging_context *msg_ctx;
+       int msg_type;
+       uint32 msg_flag;
+       const void *buf;
+       size_t len;
+       int n_sent;
+};
 
 /****************************************************************************
- Initialise the messaging functions. 
+ Send one of the messages for the broadcast.
 ****************************************************************************/
-BOOL message_init(void)
-{
-       if (tdb) return True;
 
-       tdb = tdb_open_log(lock_path("messages.tdb"), 
-                      0, TDB_CLEAR_IF_FIRST|TDB_DEFAULT,
-                      O_RDWR|O_CREAT,0600);
+static int traverse_fn(struct db_record *rec,
+                      const struct connections_key *ckey,
+                      const struct connections_data *crec,
+                      void *state)
+{
+       struct msg_all *msg_all = (struct msg_all *)state;
+       NTSTATUS status;
 
-       if (!tdb) {
-               DEBUG(0,("ERROR: Failed to initialise messages database\n"));
-               return False;
-       }
+       if (crec->cnum != -1)
+               return 0;
 
-       CatchSignal(SIGUSR1, SIGNAL_CAST sig_usr1);
+       /* Don't send if the receiver hasn't registered an interest. */
 
-       message_register(MSG_PING, ping_message);
-       message_register(MSG_REQ_DEBUGLEVEL, debuglevel_message);
+       if(!(crec->bcast_msg_flags & msg_all->msg_flag))
+               return 0;
 
-       return True;
-}
+       /* If the msg send fails because the pid was not found (i.e. smbd died), 
+        * the msg has already been deleted from the messages.tdb.*/
 
+       status = messaging_send_buf(msg_all->msg_ctx,
+                                   crec->pid, msg_all->msg_type,
+                                   (uint8 *)msg_all->buf, msg_all->len);
 
-/*******************************************************************
- form a static tdb key from a pid
-******************************************************************/
-static TDB_DATA message_key_pid(pid_t pid)
-{
-       static char key[20];
-       TDB_DATA kbuf;
-
-       slprintf(key, sizeof(key)-1, "PID/%d", (int)pid);
-       
-       kbuf.dptr = (char *)key;
-       kbuf.dsize = strlen(key)+1;
-       return kbuf;
-}
+       if (NT_STATUS_EQUAL(status, NT_STATUS_INVALID_HANDLE)) {
+               
+               /* If the pid was not found delete the entry from connections.tdb */
 
+               DEBUG(2,("pid %s doesn't exist - deleting connections %d [%s]\n",
+                        procid_str_static(&crec->pid), crec->cnum,
+                        crec->servicename));
 
-/****************************************************************************
-notify a process that it has a message. If the process doesn't exist 
-then delete its record in the database
-****************************************************************************/
-static BOOL message_notify(pid_t pid)
-{
-       if (kill(pid, SIGUSR1) == -1) {
-               if (errno == ESRCH) {
-                       DEBUG(2,("pid %d doesn't exist - deleting messages record\n", (int)pid));
-                       tdb_delete(tdb, message_key_pid(pid));
-               } else {
-                       DEBUG(2,("message to process %d failed - %s\n", (int)pid, strerror(errno)));
-               }
-               return False;
+               rec->delete_rec(rec);
        }
-       return True;
+       msg_all->n_sent++;
+       return 0;
 }
 
-/****************************************************************************
-send a message to a particular pid
-****************************************************************************/
-BOOL message_send_pid(pid_t pid, int msg_type, void *buf, size_t len, BOOL duplicates_allowed)
+/**
+ * Send a message to all smbd processes.
+ *
+ * It isn't very efficient, but should be OK for the sorts of
+ * applications that use it. When we need efficient broadcast we can add
+ * it.
+ *
+ * @param n_sent Set to the number of messages sent.  This should be
+ * equal to the number of processes, but be careful for races.
+ *
+ * @retval True for success.
+ **/
+BOOL message_send_all(struct messaging_context *msg_ctx,
+                     int msg_type,
+                     const void *buf, size_t len,
+                     int *n_sent)
 {
-       TDB_DATA kbuf;
-       TDB_DATA dbuf;
-       struct message_rec rec;
-       void *p;
-
-       rec.msg_version = MESSAGE_VERSION;
-       rec.msg_type = msg_type;
-       rec.dest = pid;
-       rec.src = sys_getpid();
-       rec.len = len;
-
-       kbuf = message_key_pid(pid);
-
-       /* lock the record for the destination */
-       tdb_chainlock(tdb, kbuf);
-
-       dbuf = tdb_fetch(tdb, kbuf);
-
-       if (!dbuf.dptr) {
-               /* its a new record */
-               p = (void *)malloc(len + sizeof(rec));
-               if (!p) goto failed;
-
-               memcpy(p, &rec, sizeof(rec));
-               if (len > 0) memcpy((void *)((char*)p+sizeof(rec)), buf, len);
+       struct msg_all msg_all;
 
-               dbuf.dptr = p;
-               dbuf.dsize = len + sizeof(rec);
-               tdb_store(tdb, kbuf, dbuf, TDB_REPLACE);
-               free(p);
-               goto ok;
-       }
+       msg_all.msg_type = msg_type;
+       if (msg_type < 1000)
+               msg_all.msg_flag = FLAG_MSG_GENERAL;
+       else if (msg_type > 1000 && msg_type < 2000)
+               msg_all.msg_flag = FLAG_MSG_NMBD;
+       else if (msg_type > 2000 && msg_type < 2100)
+               msg_all.msg_flag = FLAG_MSG_PRINT_NOTIFY;
+       else if (msg_type > 2100 && msg_type < 3000)
+               msg_all.msg_flag = FLAG_MSG_PRINT_GENERAL;
+       else if (msg_type > 3000 && msg_type < 4000)
+               msg_all.msg_flag = FLAG_MSG_SMBD;
+       else
+               return False;
 
-       if (!duplicates_allowed) {
-               char *ptr;
-               struct message_rec prec;
-               
-               for(ptr = (char *)dbuf.dptr; ptr < dbuf.dptr + dbuf.dsize; ) {
-                       /*
-                        * First check if the message header matches, then, if it's a non-zero
-                        * sized message, check if the data matches. If so it's a duplicate and
-                        * we can discard it. JRA.
-                        */
-
-                       if (!memcmp(ptr, &rec, sizeof(rec))) {
-                               if (!len || (len && !memcmp( ptr + sizeof(rec), (char *)buf, len))) {
-                                       DEBUG(10,("message_send_pid: discarding duplicate message.\n"));
-                                       free(dbuf.dptr);
-                                       tdb_chainunlock(tdb, kbuf);
-                                       return True;
-                               }
-                       }
-                       memcpy(&prec, ptr, sizeof(prec));
-                       ptr += sizeof(rec) + prec.len;
-               }
-       }
+       msg_all.buf = buf;
+       msg_all.len = len;
+       msg_all.n_sent = 0;
+       msg_all.msg_ctx = msg_ctx;
 
-       /* we're adding to an existing entry */
-       p = (void *)malloc(dbuf.dsize + len + sizeof(rec));
-       if (!p) goto failed;
-
-       memcpy(p, dbuf.dptr, dbuf.dsize);
-       memcpy((void *)((char*)p+dbuf.dsize), &rec, sizeof(rec));
-       if (len > 0) memcpy((void *)((char*)p+dbuf.dsize+sizeof(rec)), buf, len);
-
-       free(dbuf.dptr);
-       dbuf.dptr = p;
-       dbuf.dsize += len + sizeof(rec);
-       tdb_store(tdb, kbuf, dbuf, TDB_REPLACE);
-       free(dbuf.dptr);
-
- ok:
-       tdb_chainunlock(tdb, kbuf);
-       errno = 0;                    /* paranoia */
-       return message_notify(pid);
-
- failed:
-       tdb_chainunlock(tdb, kbuf);
-       errno = 0;                    /* paranoia */
-       return False;
+       connections_forall(traverse_fn, &msg_all);
+       if (n_sent)
+               *n_sent = msg_all.n_sent;
+       return True;
 }
 
+struct event_context *messaging_event_context(struct messaging_context *msg_ctx)
+{
+       return msg_ctx->event_ctx;
+}
 
-
-/****************************************************************************
-retrieve the next message for the current process
-****************************************************************************/
-static BOOL message_recv(int *msg_type, pid_t *src, void **buf, size_t *len)
+struct messaging_context *messaging_init(TALLOC_CTX *mem_ctx, 
+                                        struct server_id server_id, 
+                                        struct event_context *ev)
 {
-       TDB_DATA kbuf;
-       TDB_DATA dbuf;
-       struct message_rec rec;
+       struct messaging_context *ctx;
+       NTSTATUS status;
 
-       kbuf = message_key_pid(sys_getpid());
+       if (!(ctx = TALLOC_ZERO_P(mem_ctx, struct messaging_context))) {
+               return NULL;
+       }
 
-       tdb_chainlock(tdb, kbuf);
-       
-       dbuf = tdb_fetch(tdb, kbuf);
-       if (dbuf.dptr == NULL || dbuf.dsize == 0) goto failed;
+       ctx->id = server_id;
+       ctx->event_ctx = ev;
 
-       memcpy(&rec, dbuf.dptr, sizeof(rec));
+       status = messaging_tdb_init(ctx, ctx, &ctx->local);
 
-       if (rec.msg_version != MESSAGE_VERSION) {
-               DEBUG(0,("message version %d received (expected %d)\n", rec.msg_version, MESSAGE_VERSION));
-               goto failed;
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(0, ("messaging_tdb_init failed: %s\n",
+                         nt_errstr(status)));
+               TALLOC_FREE(ctx);
+               return NULL;
        }
 
-       if (rec.len > 0) {
-               (*buf) = (void *)malloc(rec.len);
-               if (!(*buf)) goto failed;
+#ifdef CLUSTER_SUPPORT
+       if (lp_clustering()) {
+               status = messaging_ctdbd_init(ctx, ctx, &ctx->remote);
 
-               memcpy(*buf, dbuf.dptr+sizeof(rec), rec.len);
-       } else {
-               *buf = NULL;
+               if (!NT_STATUS_IS_OK(status)) {
+                       DEBUG(0, ("messaging_ctdb_init failed: %s\n",
+                                 nt_errstr(status)));
+                       TALLOC_FREE(ctx);
+                       return NULL;
+               }
        }
+#endif
 
-       *len = rec.len;
-       *msg_type = rec.msg_type;
-       *src = rec.src;
-
-       if (dbuf.dsize - (sizeof(rec)+rec.len) > 0)
-               memmove(dbuf.dptr, dbuf.dptr+sizeof(rec)+rec.len, dbuf.dsize - (sizeof(rec)+rec.len));
-       dbuf.dsize -= sizeof(rec)+rec.len;
+       messaging_register(ctx, NULL, MSG_PING, ping_message);
 
-       if (dbuf.dsize == 0)
-               tdb_delete(tdb, kbuf);
-       else
-               tdb_store(tdb, kbuf, dbuf, TDB_REPLACE);
+       /* Register some debugging related messages */
 
-       free(dbuf.dptr);
-       tdb_chainunlock(tdb, kbuf);
-       return True;
+       register_msg_pool_usage(ctx);
+       register_dmalloc_msgs(ctx);
+       debug_register_msgs(ctx);
 
- failed:
-       tdb_chainunlock(tdb, kbuf);
-       return False;
+       return ctx;
 }
 
-
-/****************************************************************************
-receive and dispatch any messages pending for this process
-notice that all dispatch handlers for a particular msg_type get called,
-so you can register multiple handlers for a message
-****************************************************************************/
-void message_dispatch(void)
+/*
+ * re-init after a fork
+ */
+NTSTATUS messaging_reinit(struct messaging_context *msg_ctx)
 {
-       int msg_type;
-       pid_t src;
-       void *buf;
-       size_t len;
-       struct dispatch_fns *dfn;
+#ifdef CLUSTER_SUPPORT
+
+       TALLOC_FREE(msg_ctx->remote);
 
-       if (!received_signal) return;
-       received_signal = 0;
+       if (lp_clustering()) {
+               NTSTATUS status;
 
-       while (message_recv(&msg_type, &src, &buf, &len)) {
-               for (dfn = dispatch_fns; dfn; dfn = dfn->next) {
-                       if (dfn->msg_type == msg_type) {
-                               dfn->fn(msg_type, src, buf, len);
-                       }
+               status = messaging_ctdbd_init(msg_ctx, msg_ctx,
+                                             &msg_ctx->remote);
+
+               if (!NT_STATUS_IS_OK(status)) {
+                       DEBUG(0, ("messaging_ctdb_init failed: %s\n",
+                                 nt_errstr(status)));
+                       return status;
                }
-               if (buf) free(buf);
        }
+
+#endif
+
+       return NT_STATUS_OK;
 }
 
 
-/****************************************************************************
-register a dispatch function for a particular message type
-****************************************************************************/
-void message_register(int msg_type, 
-                     void (*fn)(int msg_type, pid_t pid, void *buf, size_t len))
+/*
+ * Register a dispatch function for a particular message type. Allow multiple
+ * registrants
+*/
+NTSTATUS messaging_register(struct messaging_context *msg_ctx,
+                           void *private_data,
+                           uint32_t msg_type,
+                           void (*fn)(struct messaging_context *msg,
+                                      void *private_data, 
+                                      uint32_t msg_type, 
+                                      struct server_id server_id,
+                                      DATA_BLOB *data))
 {
-       struct dispatch_fns *dfn;
+       struct messaging_callback *cb;
 
-       dfn = (struct dispatch_fns *)malloc(sizeof(*dfn));
+       /*
+        * Only one callback per type
+        */
 
-       if (dfn != NULL) {
+       for (cb = msg_ctx->callbacks; cb != NULL; cb = cb->next) {
+               if (cb->msg_type == msg_type) {
+                       cb->fn = fn;
+                       cb->private_data = private_data;
+                       return NT_STATUS_OK;
+               }
+       }
 
-               ZERO_STRUCTPN(dfn);
+       if (!(cb = talloc(msg_ctx, struct messaging_callback))) {
+               return NT_STATUS_NO_MEMORY;
+       }
 
-               dfn->msg_type = msg_type;
-               dfn->fn = fn;
+       cb->msg_type = msg_type;
+       cb->fn = fn;
+       cb->private_data = private_data;
 
-               DLIST_ADD(dispatch_fns, dfn);
-       }
-       else {
-       
-               DEBUG(0,("message_register: Not enough memory. malloc failed!\n"));
-       }
+       DLIST_ADD(msg_ctx->callbacks, cb);
+       return NT_STATUS_OK;
 }
 
-/****************************************************************************
-de-register the function for a particular message type
-****************************************************************************/
-void message_deregister(int msg_type)
+/*
+  De-register the function for a particular message type.
+*/
+void messaging_deregister(struct messaging_context *ctx, uint32_t msg_type,
+                         void *private_data)
 {
-       struct dispatch_fns *dfn, *next;
-
-       for (dfn = dispatch_fns; dfn; dfn = next) {
-               next = dfn->next;
-               if (dfn->msg_type == msg_type) {
-                       DLIST_REMOVE(dispatch_fns, dfn);
-                       free(dfn);
+       struct messaging_callback *cb, *next;
+
+       for (cb = ctx->callbacks; cb; cb = next) {
+               next = cb->next;
+               if ((cb->msg_type == msg_type)
+                   && (cb->private_data == private_data)) {
+                       DLIST_REMOVE(ctx->callbacks, cb);
+                       TALLOC_FREE(cb);
                }
-       }       
+       }
 }
 
-struct msg_all {
-       int msg_type;
-       void *buf;
-       size_t len;
-       BOOL duplicates;
-};
-
-/****************************************************************************
-send one of the messages for the broadcast
-****************************************************************************/
-static int traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DATA dbuf, void *state)
+/*
+  Send a message to a particular server
+*/
+NTSTATUS messaging_send(struct messaging_context *msg_ctx,
+                       struct server_id server, uint32_t msg_type,
+                       const DATA_BLOB *data)
 {
-       struct connections_data crec;
-       struct msg_all *msg_all = (struct msg_all *)state;
-
-       if (dbuf.dsize != sizeof(crec))
-               return 0;
-
-       memcpy(&crec, dbuf.dptr, sizeof(crec));
+       return msg_ctx->local->send_fn(msg_ctx, server, msg_type, data,
+                                      msg_ctx->local);
+}
 
-       if (crec.cnum != -1)
-               return 0;
+NTSTATUS messaging_send_buf(struct messaging_context *msg_ctx,
+                           struct server_id server, uint32_t msg_type,
+                           const uint8 *buf, size_t len)
+{
+       DATA_BLOB blob = data_blob_const(buf, len);
+       return messaging_send(msg_ctx, server, msg_type, &blob);
+}
 
-       /* if the msg send fails because the pid was not found (i.e. smbd died), 
-        * the msg has already been deleted from the messages.tdb.*/
-       if (!message_send_pid(crec.pid, msg_all->msg_type, msg_all->buf, msg_all->len,
-                                                       msg_all->duplicates)) {
-               
-               /* if the pid was not found delete the entry from connections.tdb */
-               if (errno == ESRCH) {
-                       DEBUG(2,("pid %u doesn't exist - deleting connections %d [%s]\n",
-                                       (unsigned int)crec.pid, crec.cnum, crec.name));
-                       tdb_delete(the_tdb, kbuf);
+/*
+  Dispatch one messsaging_rec
+*/
+void messaging_dispatch_rec(struct messaging_context *msg_ctx,
+                           struct messaging_rec *rec)
+{
+       struct messaging_callback *cb, *next;
+
+       for (cb = msg_ctx->callbacks; cb != NULL; cb = next) {
+               next = cb->next;
+               if (cb->msg_type == rec->msg_type) {
+                       cb->fn(msg_ctx, cb->private_data, rec->msg_type,
+                              rec->src, &rec->buf);
+                       return;
                }
        }
-       return 0;
+       return;
 }
 
-/****************************************************************************
-this is a useful function for sending messages to all smbd processes.
-It isn't very efficient, but should be OK for the sorts of applications that 
-use it. When we need efficient broadcast we can add it.
-****************************************************************************/
-BOOL message_send_all(TDB_CONTEXT *conn_tdb, int msg_type, void *buf, size_t len, BOOL duplicates_allowed)
-{
-       struct msg_all msg_all;
-
-       msg_all.msg_type = msg_type;
-       msg_all.buf = buf;
-       msg_all.len = len;
-       msg_all.duplicates = duplicates_allowed;
-
-       tdb_traverse(conn_tdb, traverse_fn, &msg_all);
-       return True;
-}
+/** @} **/