app_dial: Allow macro/gosub pre-bridge execution to occur on priorities
[asterisk/asterisk.git] / main / utils.c
index 0ff33cb..3d8e4c2 100644 (file)
 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 
 #include <ctype.h>
-#include <sys/stat.h>
-#include <sys/stat.h>
-
-#ifdef HAVE_DEV_URANDOM
 #include <fcntl.h>
-#endif
-
+#include <sys/stat.h>
 #include <sys/syscall.h>
+#include <unistd.h>
 #if defined(__APPLE__)
 #include <mach/mach.h>
 #elif defined(HAVE_SYS_THR_H)
@@ -47,6 +43,7 @@ ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 #endif
 
 #include "asterisk/network.h"
+#include "asterisk/ast_version.h"
 
 #define AST_API_MODULE         /* ensure that inlinable API functions will be built in lock.h if required */
 #include "asterisk/lock.h"
@@ -485,6 +482,69 @@ char *ast_escape_quoted(const char *string, char *outbuf, int buflen)
 
        return outbuf;
 }
+int ast_xml_escape(const char *string, char * const outbuf, const size_t buflen)
+{
+       char *dst = outbuf;
+       char *end = outbuf + buflen - 1; /* save one for the null terminator */
+
+       /* Handle the case for the empty output buffer */
+       if (buflen == 0) {
+               return -1;
+       }
+
+       /* Escaping rules from http://www.w3.org/TR/REC-xml/#syntax */
+       /* This also prevents partial entities at the end of a string */
+       while (*string && dst < end) {
+               const char *entity = NULL;
+               int len = 0;
+
+               switch (*string) {
+               case '<':
+                       entity = "&lt;";
+                       len = 4;
+                       break;
+               case '&':
+                       entity = "&amp;";
+                       len = 5;
+                       break;
+               case '>':
+                       /* necessary if ]]> is in the string; easier to escape them all */
+                       entity = "&gt;";
+                       len = 4;
+                       break;
+               case '\'':
+                       /* necessary in single-quoted strings; easier to escape them all */
+                       entity = "&apos;";
+                       len = 6;
+                       break;
+               case '"':
+                       /* necessary in double-quoted strings; easier to escape them all */
+                       entity = "&quot;";
+                       len = 6;
+                       break;
+               default:
+                       *dst++ = *string++;
+                       break;
+               }
+
+               if (entity) {
+                       ast_assert(len == strlen(entity));
+                       if (end - dst < len) {
+                               /* no room for the entity; stop */
+                               break;
+                       }
+                       /* just checked for length; strcpy is fine */
+                       strcpy(dst, entity);
+                       dst += len;
+                       ++string;
+               }
+       }
+       /* Write null terminator */
+       *dst = '\0';
+       /* If any chars are left in string, return failure */
+       return *string == '\0' ? 0 : -1;
+}
+
 /*! \brief  ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa */
 const char *ast_inet_ntoa(struct in_addr ia)
 {
@@ -496,9 +556,7 @@ const char *ast_inet_ntoa(struct in_addr ia)
        return inet_ntop(AF_INET, &ia, buf, INET_ADDRSTRLEN);
 }
 
-#ifdef HAVE_DEV_URANDOM
 static int dev_urandom_fd;
-#endif
 
 #ifndef __linux__
 #undef pthread_create /* For ast_pthread_create function only */
@@ -531,14 +589,16 @@ struct thr_lock_info {
        /*! This is the actual container of info for what locks this thread holds */
        struct {
                const char *file;
-               int line_num;
                const char *func;
                const char *lock_name;
                void *lock_addr;
                int times_locked;
+               int line_num;
                enum ast_lock_type type;
                /*! This thread is waiting on this lock */
                int pending:2;
+               /*! A condition has suspended this lock */
+               int suspended:1;
 #ifdef HAVE_BKTR
                struct ast_bt *backtrace;
 #endif
@@ -547,6 +607,8 @@ struct thr_lock_info {
         *  The index (num_locks - 1) has the info on the last one in the
         *  locks member */
        unsigned int num_locks;
+       /*! The LWP id (which GDB prints) */
+       int lwp;
        /*! Protects the contents of the locks member
         * Intentionally not ast_mutex_t */
        pthread_mutex_t lock;
@@ -596,9 +658,10 @@ static void lock_info_destroy(void *data)
        }
 
        pthread_mutex_destroy(&lock_info->lock);
-       if (lock_info->thread_name)
-               free((void *) lock_info->thread_name);
-       free(lock_info);
+       if (lock_info->thread_name) {
+               ast_free((void *) lock_info->thread_name);
+       }
+       ast_free(lock_info);
 }
 
 /*!
@@ -725,6 +788,60 @@ int ast_find_lock_info(void *lock_addr, char *filename, size_t filename_size, in
        return 0;
 }
 
+void ast_suspend_lock_info(void *lock_addr)
+{
+       struct thr_lock_info *lock_info;
+       int i = 0;
+
+       if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info)))) {
+               return;
+       }
+
+       pthread_mutex_lock(&lock_info->lock);
+
+       for (i = lock_info->num_locks - 1; i >= 0; i--) {
+               if (lock_info->locks[i].lock_addr == lock_addr)
+                       break;
+       }
+
+       if (i == -1) {
+               /* Lock not found :( */
+               pthread_mutex_unlock(&lock_info->lock);
+               return;
+       }
+
+       lock_info->locks[i].suspended = 1;
+
+       pthread_mutex_unlock(&lock_info->lock);
+}
+
+void ast_restore_lock_info(void *lock_addr)
+{
+       struct thr_lock_info *lock_info;
+       int i = 0;
+
+       if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
+               return;
+
+       pthread_mutex_lock(&lock_info->lock);
+
+       for (i = lock_info->num_locks - 1; i >= 0; i--) {
+               if (lock_info->locks[i].lock_addr == lock_addr)
+                       break;
+       }
+
+       if (i == -1) {
+               /* Lock not found :( */
+               pthread_mutex_unlock(&lock_info->lock);
+               return;
+       }
+
+       lock_info->locks[i].suspended = 0;
+
+       pthread_mutex_unlock(&lock_info->lock);
+}
+
+
 #ifdef HAVE_BKTR
 void ast_remove_lock_info(void *lock_addr, struct ast_bt *bt)
 #else
@@ -805,7 +922,7 @@ static void append_backtrace_information(struct ast_str **str, struct ast_bt *bt
                        ast_str_append(str, 0, "\t%s\n", symbols[frame_iterator]);
                }
 
-               free(symbols);
+               ast_std_free(symbols);
        } else {
                ast_str_append(str, 0, "\tCouldn't retrieve backtrace symbols\n");
        }
@@ -818,7 +935,7 @@ static void append_lock_information(struct ast_str **str, struct thr_lock_info *
        ast_mutex_t *lock;
        struct ast_lock_track *lt;
 
-       ast_str_append(str, 0, "=== ---> %sLock #%d (%s): %s %d %s %s %p (%d)\n",
+       ast_str_append(str, 0, "=== ---> %sLock #%d (%s): %s %d %s %s %p (%d%s)\n",
                                   lock_info->locks[i].pending > 0 ? "Waiting for " :
                                   lock_info->locks[i].pending < 0 ? "Tried and failed to get " : "", i,
                                   lock_info->locks[i].file,
@@ -826,7 +943,8 @@ static void append_lock_information(struct ast_str **str, struct thr_lock_info *
                                   lock_info->locks[i].line_num,
                                   lock_info->locks[i].func, lock_info->locks[i].lock_name,
                                   lock_info->locks[i].lock_addr,
-                                  lock_info->locks[i].times_locked);
+                                  lock_info->locks[i].times_locked,
+                                  lock_info->locks[i].suspended ? " - suspended" : "");
 #ifdef HAVE_BKTR
        append_backtrace_information(str, lock_info->locks[i].backtrace);
 #endif
@@ -868,7 +986,7 @@ static void append_lock_information(struct ast_str **str, struct thr_lock_info *
        which will give a stack trace and continue. -- that aught to do the job!
 
 */
-void log_show_lock(void *this_lock_addr)
+void ast_log_show_lock(void *this_lock_addr)
 {
        struct thr_lock_info *lock_info;
        struct ast_str *str;
@@ -899,67 +1017,97 @@ void log_show_lock(void *this_lock_addr)
 }
 
 
-static char *handle_show_locks(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+struct ast_str *ast_dump_locks(void)
 {
        struct thr_lock_info *lock_info;
        struct ast_str *str;
 
-       if (!(str = ast_str_create(4096)))
-               return CLI_FAILURE;
-
-       switch (cmd) {
-       case CLI_INIT:
-               e->command = "core show locks";
-               e->usage =
-                       "Usage: core show locks\n"
-                       "       This command is for lock debugging.  It prints out which locks\n"
-                       "are owned by each active thread.\n";
-               return NULL;
-
-       case CLI_GENERATE:
+       if (!(str = ast_str_create(4096))) {
                return NULL;
        }
 
        ast_str_append(&str, 0, "\n"
                       "=======================================================================\n"
-                      "=== Currently Held Locks ==============================================\n"
+                      "=== %s\n"
+                      "=== Currently Held Locks\n"
                       "=======================================================================\n"
                       "===\n"
                       "=== <pending> <lock#> (<file>): <lock type> <line num> <function> <lock name> <lock addr> (times locked)\n"
-                      "===\n");
+                      "===\n", ast_get_version());
 
-       if (!str)
-               return CLI_FAILURE;
+       if (!str) {
+               return NULL;
+       }
 
        pthread_mutex_lock(&lock_infos_lock.mutex);
        AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
                int i;
-               if (lock_info->num_locks) {
-                       ast_str_append(&str, 0, "=== Thread ID: 0x%lx (%s)\n", (long) lock_info->thread_id,
-                               lock_info->thread_name);
-                       pthread_mutex_lock(&lock_info->lock);
-                       for (i = 0; str && i < lock_info->num_locks; i++) {
-                               append_lock_information(&str, lock_info, i);
+               int header_printed = 0;
+               pthread_mutex_lock(&lock_info->lock);
+               for (i = 0; str && i < lock_info->num_locks; i++) {
+                       /* Don't show suspended locks */
+                       if (lock_info->locks[i].suspended) {
+                               continue;
                        }
-                       pthread_mutex_unlock(&lock_info->lock);
-                       if (!str)
-                               break;
+
+                       if (!header_printed) {
+                               if (lock_info->lwp != -1) {
+                                       ast_str_append(&str, 0, "=== Thread ID: 0x%lx LWP:%d (%s)\n",
+                                               (long) lock_info->thread_id, lock_info->lwp, lock_info->thread_name);
+                               } else {
+                                       ast_str_append(&str, 0, "=== Thread ID: 0x%lx (%s)\n",
+                                               (long) lock_info->thread_id, lock_info->thread_name);
+                               }
+                               header_printed = 1;
+                       }
+
+                       append_lock_information(&str, lock_info, i);
+               }
+               pthread_mutex_unlock(&lock_info->lock);
+               if (!str) {
+                       break;
+               }
+               if (header_printed) {
                        ast_str_append(&str, 0, "=== -------------------------------------------------------------------\n"
-                                      "===\n");
-                       if (!str)
-                               break;
+                               "===\n");
+               }
+               if (!str) {
+                       break;
                }
        }
        pthread_mutex_unlock(&lock_infos_lock.mutex);
 
-       if (!str)
-               return CLI_FAILURE;
+       if (!str) {
+               return NULL;
+       }
 
        ast_str_append(&str, 0, "=======================================================================\n"
                       "\n");
 
-       if (!str)
+       return str;
+}
+
+static char *handle_show_locks(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+{
+       struct ast_str *str;
+
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "core show locks";
+               e->usage =
+                       "Usage: core show locks\n"
+                       "       This command is for lock debugging.  It prints out which locks\n"
+                       "are owned by each active thread.\n";
+               return NULL;
+
+       case CLI_GENERATE:
+               return NULL;
+       }
+
+       str = ast_dump_locks();
+       if (!str) {
                return CLI_FAILURE;
+       }
 
        ast_cli(a->fd, "%s", ast_str_buffer(str));
 
@@ -999,22 +1147,12 @@ static void *dummy_start(void *data)
 #ifdef DEBUG_THREADS
        struct thr_lock_info *lock_info;
        pthread_mutexattr_t mutex_attr;
-#endif
 
-       /* note that even though data->name is a pointer to allocated memory,
-          we are not freeing it here because ast_register_thread is going to
-          keep a copy of the pointer and then ast_unregister_thread will
-          free the memory
-       */
-       ast_free(data);
-       ast_register_thread(a.name);
-       pthread_cleanup_push(ast_unregister_thread, (void *) pthread_self());
-
-#ifdef DEBUG_THREADS
        if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
                return NULL;
 
        lock_info->thread_id = pthread_self();
+       lock_info->lwp = ast_get_tid();
        lock_info->thread_name = strdup(a.name);
 
        pthread_mutexattr_init(&mutex_attr);
@@ -1027,6 +1165,15 @@ static void *dummy_start(void *data)
        pthread_mutex_unlock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
 #endif /* DEBUG_THREADS */
 
+       /* note that even though data->name is a pointer to allocated memory,
+          we are not freeing it here because ast_register_thread is going to
+          keep a copy of the pointer and then ast_unregister_thread will
+          free the memory
+       */
+       ast_free(data);
+       ast_register_thread(a.name);
+       pthread_cleanup_push(ast_unregister_thread, (void *) pthread_self());
+
        ret = a.start_routine(a.data);
 
        pthread_cleanup_pop(1);
@@ -1470,10 +1617,33 @@ struct timeval ast_tvsub(struct timeval a, struct timeval b)
        }
        return a;
 }
-#undef ONE_MILLION
 
-/*! \brief glibc puts a lock inside random(3), so that the results are thread-safe.
- * BSD libc (and others) do not. */
+int ast_remaining_ms(struct timeval start, int max_ms)
+{
+       int ms;
+
+       if (max_ms < 0) {
+               ms = max_ms;
+       } else {
+               ms = max_ms - ast_tvdiff_ms(ast_tvnow(), start);
+               if (ms < 0) {
+                       ms = 0;
+               }
+       }
+
+       return ms;
+}
+
+void ast_format_duration_hh_mm_ss(int duration, char *buf, size_t length)
+{
+       int durh, durm, durs;
+       durh = duration / 3600;
+       durm = (duration % 3600) / 60;
+       durs = duration % 60;
+       snprintf(buf, length, "%02d:%02d:%02d", durh, durm, durs);
+}
+
+#undef ONE_MILLION
 
 #ifndef linux
 AST_MUTEX_DEFINE_STATIC(randomlock);
@@ -1482,7 +1652,7 @@ AST_MUTEX_DEFINE_STATIC(randomlock);
 long int ast_random(void)
 {
        long int res;
-#ifdef HAVE_DEV_URANDOM
+
        if (dev_urandom_fd >= 0) {
                int read_res = read(dev_urandom_fd, &res, sizeof(res));
                if (read_res > 0) {
@@ -1492,7 +1662,14 @@ long int ast_random(void)
                        return res % rm;
                }
        }
-#endif
+
+       /* XXX - Thread safety really depends on the libc, not the OS.
+        *
+        * But... popular Linux libc's (uClibc, glibc, eglibc), all have a
+        * somewhat thread safe random(3) (results are random, but not
+        * reproducible). The libc's for other systems (BSD, et al.), not so
+        * much.
+        */
 #ifdef linux
        res = random();
 #else
@@ -1538,7 +1715,7 @@ char *ast_process_quotes_and_slashes(char *start, char find, char replace_with)
        return dataPut;
 }
 
-void ast_join(char *s, size_t len, const char * const w[])
+void ast_join_delim(char *s, size_t len, const char * const w[], unsigned int size, char delim)
 {
        int x, ofs = 0;
        const char *src;
@@ -1546,9 +1723,9 @@ void ast_join(char *s, size_t len, const char * const w[])
        /* Join words into a string */
        if (!s)
                return;
-       for (x = 0; ofs < len && w[x]; x++) {
+       for (x = 0; ofs < len && w[x] && x < size; x++) {
                if (x > 0)
-                       s[ofs++] = ' ';
+                       s[ofs++] = delim;
                for (src = w[x]; *src && ofs < len; src++)
                        s[ofs++] = *src;
        }
@@ -1557,6 +1734,25 @@ void ast_join(char *s, size_t len, const char * const w[])
        s[ofs] = '\0';
 }
 
+char *ast_to_camel_case_delim(const char *s, const char *delim)
+{
+       char *res = ast_strdup(s);
+       char *front, *back, *buf = res;
+       int size;
+
+       front = strtok_r(buf, delim, &back);
+
+       while (front) {
+               size = strlen(front);
+               *front = toupper(*front);
+               ast_copy_string(buf, front, size + 1);
+               buf += size;
+               front = strtok_r(NULL, delim, &back);
+       }
+
+       return res;
+}
+
 /*
  * stringfields support routines.
  */
@@ -2014,17 +2210,119 @@ int ast_mkdir(const char *path, int mode)
        return 0;
 }
 
+static int safe_mkdir(const char *base_path, char *path, int mode)
+{
+       RAII_VAR(char *, absolute_path, NULL, ast_std_free);
+
+       absolute_path = realpath(path, NULL);
+
+       if (absolute_path) {
+               /* Path exists, but is it in the right place? */
+               if (!ast_begins_with(absolute_path, base_path)) {
+                       return EPERM;
+               }
+
+               /* It is in the right place! */
+               return 0;
+       } else {
+               /* Path doesn't exist. */
+
+               /* The slash terminating the subpath we're checking */
+               char *path_term = strchr(path, '/');
+               /* True indicates the parent path is within base_path */
+               int parent_is_safe = 0;
+               int res;
+
+               while (path_term) {
+                       RAII_VAR(char *, absolute_subpath, NULL, ast_std_free);
+
+                       /* Truncate the path one past the slash */
+                       char c = *(path_term + 1);
+                       *(path_term + 1) = '\0';
+                       absolute_subpath = realpath(path, NULL);
+
+                       if (absolute_subpath) {
+                               /* Subpath exists, but is it safe? */
+                               parent_is_safe = ast_begins_with(
+                                       absolute_subpath, base_path);
+                       } else if (parent_is_safe) {
+                               /* Subpath does not exist, but parent is safe
+                                * Create it */
+                               res = mkdir(path, mode);
+                               if (res != 0) {
+                                       ast_assert(errno != EEXIST);
+                                       return errno;
+                               }
+                       } else {
+                               /* Subpath did not exist, parent was not safe
+                                * Fail! */
+                               errno = EPERM;
+                               return errno;
+                       }
+                       /* Restore the path */
+                       *(path_term + 1) = c;
+                       /* Move on to the next slash */
+                       path_term = strchr(path_term + 1, '/');
+               }
+
+               /* Now to build the final path, but only if it's safe */
+               if (!parent_is_safe) {
+                       errno = EPERM;
+                       return errno;
+               }
+
+               res = mkdir(path, mode);
+               if (res != 0 && errno != EEXIST) {
+                       return errno;
+               }
+
+               return 0;
+       }
+}
+
+int ast_safe_mkdir(const char *base_path, const char *path, int mode)
+{
+       RAII_VAR(char *, absolute_base_path, NULL, ast_std_free);
+       RAII_VAR(char *, p, NULL, ast_free);
+
+       if (base_path == NULL || path == NULL) {
+               errno = EFAULT;
+               return errno;
+       }
+
+       p = ast_strdup(path);
+       if (p == NULL) {
+               errno = ENOMEM;
+               return errno;
+       }
+
+       absolute_base_path = realpath(base_path, NULL);
+       if (absolute_base_path == NULL) {
+               return errno;
+       }
+
+       return safe_mkdir(absolute_base_path, p, mode);
+}
+
+static void utils_shutdown(void)
+{
+       close(dev_urandom_fd);
+       dev_urandom_fd = -1;
+#if defined(DEBUG_THREADS) && !defined(LOW_MEMORY)
+       ast_cli_unregister_multiple(utils_cli, ARRAY_LEN(utils_cli));
+#endif
+}
+
 int ast_utils_init(void)
 {
-#ifdef HAVE_DEV_URANDOM
        dev_urandom_fd = open("/dev/urandom", O_RDONLY);
-#endif
        base64_init();
 #ifdef DEBUG_THREADS
 #if !defined(LOW_MEMORY)
        ast_cli_register_multiple(utils_cli, ARRAY_LEN(utils_cli));
 #endif
 #endif
+       ast_register_atexit(utils_shutdown);
        return 0;
 }
 
@@ -2202,3 +2500,35 @@ char *ast_utils_which(const char *binary, char *fullpath, size_t fullpath_size)
        return NULL;
 }
 
+void ast_do_crash(void)
+{
+#if defined(DO_CRASH)
+       abort();
+       /*
+        * Just in case abort() doesn't work or something else super
+        * silly, and for Qwell's amusement.
+        */
+       *((int *) 0) = 0;
+#endif /* defined(DO_CRASH) */
+}
+
+#if defined(AST_DEVMODE)
+void __ast_assert_failed(int condition, const char *condition_str, const char *file, int line, const char *function)
+{
+       /*
+        * Attempt to put it into the logger, but hope that at least
+        * someone saw the message on stderr ...
+        */
+       ast_log(__LOG_ERROR, file, line, function, "FRACK!, Failed assertion %s (%d)\n",
+               condition_str, condition);
+       fprintf(stderr, "FRACK!, Failed assertion %s (%d) at line %d in %s of %s\n",
+               condition_str, condition, line, function, file);
+       /*
+        * Give the logger a chance to get the message out, just in case
+        * we abort(), or Asterisk crashes due to whatever problem just
+        * happened after we exit ast_assert().
+        */
+       usleep(1);
+       ast_do_crash();
+}
+#endif /* defined(AST_DEVMODE) */