Coverity Report: Fix issues for error type CHECKED_RETURN for core
[asterisk/asterisk.git] / funcs / func_lock.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2007, Tilghman Lesher
5  *
6  * Tilghman Lesher <func_lock_2007@the-tilghman.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Dialplan mutexes
22  *
23  * \author Tilghman Lesher <func_lock_2007@the-tilghman.com>
24  *
25  * \ingroup functions
26  * 
27  */
28
29 /*** MODULEINFO
30         <support_level>core</support_level>
31  ***/
32
33 #include "asterisk.h"
34
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
36
37 #include <signal.h>
38
39 #include "asterisk/lock.h"
40 #include "asterisk/file.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/pbx.h"
43 #include "asterisk/module.h"
44 #include "asterisk/linkedlists.h"
45 #include "asterisk/astobj2.h"
46 #include "asterisk/utils.h"
47
48 /*** DOCUMENTATION
49         <function name="LOCK" language="en_US">
50                 <synopsis>
51                         Attempt to obtain a named mutex.
52                 </synopsis>
53                 <syntax>
54                         <parameter name="lockname" required="true" />
55                 </syntax>
56                 <description>
57                         <para>Attempts to grab a named lock exclusively, and prevents other channels from
58                         obtaining the same lock.  LOCK will wait for the lock to become available.
59                         Returns <literal>1</literal> if the lock was obtained or <literal>0</literal> on error.</para>
60                         <note><para>To avoid the possibility of a deadlock, LOCK will only attempt to
61                         obtain the lock for 3 seconds if the channel already has another lock.</para></note>
62                 </description>
63         </function>
64         <function name="TRYLOCK" language="en_US">
65                 <synopsis>
66                         Attempt to obtain a named mutex.
67                 </synopsis>
68                 <syntax>
69                         <parameter name="lockname" required="true" />
70                 </syntax>
71                 <description>
72                         <para>Attempts to grab a named lock exclusively, and prevents other channels
73                         from obtaining the same lock.  Returns <literal>1</literal> if the lock was 
74                         available or <literal>0</literal> otherwise.</para>
75                 </description>
76         </function>
77         <function name="UNLOCK" language="en_US">
78                 <synopsis>
79                         Unlocks a named mutex.
80                 </synopsis>
81                 <syntax>
82                         <parameter name="lockname" required="true" />
83                 </syntax>
84                 <description>
85                         <para>Unlocks a previously locked mutex. Returns <literal>1</literal> if the channel 
86                         had a lock or <literal>0</literal> otherwise.</para>
87                         <note><para>It is generally unnecessary to unlock in a hangup routine, as any locks 
88                         held are automatically freed when the channel is destroyed.</para></note>
89                 </description>
90         </function>
91  ***/
92
93
94
95 static AST_LIST_HEAD_STATIC(locklist, lock_frame);
96
97 static void lock_free(void *data);
98 static void lock_fixup(void *data, struct ast_channel *oldchan, struct ast_channel *newchan);
99 static int unloading = 0;
100 static pthread_t broker_tid = AST_PTHREADT_NULL;
101
102 static struct ast_datastore_info lock_info = {
103         .type = "MUTEX",
104         .destroy = lock_free,
105         .chan_fixup = lock_fixup,
106 };
107
108 struct lock_frame {
109         AST_LIST_ENTRY(lock_frame) entries;
110         ast_mutex_t mutex;
111         ast_cond_t cond;
112         /*! count is needed so if a recursive mutex exits early, we know how many times to unlock it. */
113         unsigned int count;
114         /*! Container of requesters for the named lock */
115         struct ao2_container *requesters;
116         /*! who owns us */
117         struct ast_channel *owner;
118         /*! name of the lock */
119         char name[0];
120 };
121
122 struct channel_lock_frame {
123         AST_LIST_ENTRY(channel_lock_frame) list;
124         /*! Need to save channel pointer here, because during destruction, we won't have it. */
125         struct ast_channel *channel;
126         struct lock_frame *lock_frame;
127 };
128
129 static void lock_free(void *data)
130 {
131         AST_LIST_HEAD(, channel_lock_frame) *oldlist = data;
132         struct channel_lock_frame *clframe;
133         AST_LIST_LOCK(oldlist);
134         while ((clframe = AST_LIST_REMOVE_HEAD(oldlist, list))) {
135                 /* Only unlock if we own the lock */
136                 if (clframe->channel == clframe->lock_frame->owner) {
137                         clframe->lock_frame->count = 0;
138                         clframe->lock_frame->owner = NULL;
139                 }
140                 ast_free(clframe);
141         }
142         AST_LIST_UNLOCK(oldlist);
143         AST_LIST_HEAD_DESTROY(oldlist);
144         ast_free(oldlist);
145 }
146
147 static void lock_fixup(void *data, struct ast_channel *oldchan, struct ast_channel *newchan)
148 {
149         struct ast_datastore *lock_store = ast_channel_datastore_find(oldchan, &lock_info, NULL);
150         AST_LIST_HEAD(, channel_lock_frame) *list;
151         struct channel_lock_frame *clframe = NULL;
152
153         if (!lock_store) {
154                 return;
155         }
156         list = lock_store->data;
157
158         AST_LIST_LOCK(list);
159         AST_LIST_TRAVERSE(list, clframe, list) {
160                 if (clframe->lock_frame->owner == oldchan) {
161                         clframe->lock_frame->owner = newchan;
162                 }
163                 /* We don't move requesters, because the thread stack is different */
164                 clframe->channel = newchan;
165         }
166         AST_LIST_UNLOCK(list);
167 }
168
169 static void *lock_broker(void *unused)
170 {
171         struct lock_frame *frame;
172         struct timespec forever = { 1000000, 0 };
173         for (;;) {
174                 int found_requester = 0;
175
176                 /* Test for cancel outside of the lock */
177                 pthread_testcancel();
178                 AST_LIST_LOCK(&locklist);
179
180                 AST_LIST_TRAVERSE(&locklist, frame, entries) {
181                         if (ao2_container_count(frame->requesters)) {
182                                 found_requester++;
183                                 ast_mutex_lock(&frame->mutex);
184                                 if (!frame->owner) {
185                                         ast_cond_signal(&frame->cond);
186                                 }
187                                 ast_mutex_unlock(&frame->mutex);
188                         }
189                 }
190
191                 AST_LIST_UNLOCK(&locklist);
192                 pthread_testcancel();
193
194                 /* If there are no requesters, then wait for a signal */
195                 if (!found_requester) {
196                         nanosleep(&forever, NULL);
197                 } else {
198                         sched_yield();
199                 }
200         }
201         /* Not reached */
202         return NULL;
203 }
204
205 static int ast_channel_hash_cb(const void *obj, const int flags)
206 {
207         const struct ast_channel *chan = obj;
208         return ast_str_case_hash(ast_channel_name(chan));
209 }
210
211 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
212 {
213         struct ast_channel *chan = obj, *cmp_args = arg;
214         return strcasecmp(ast_channel_name(chan), ast_channel_name(cmp_args)) ? 0 : CMP_MATCH;
215 }
216
217 static int get_lock(struct ast_channel *chan, char *lockname, int trylock)
218 {
219         struct ast_datastore *lock_store = ast_channel_datastore_find(chan, &lock_info, NULL);
220         struct lock_frame *current;
221         struct channel_lock_frame *clframe = NULL;
222         AST_LIST_HEAD(, channel_lock_frame) *list;
223         int res = 0;
224         struct timespec timeout = { 0, };
225         struct timeval now;
226
227         if (!lock_store) {
228                 ast_debug(1, "Channel %s has no lock datastore, so we're allocating one.\n", ast_channel_name(chan));
229                 lock_store = ast_datastore_alloc(&lock_info, NULL);
230                 if (!lock_store) {
231                         ast_log(LOG_ERROR, "Unable to allocate new datastore.  No locks will be obtained.\n");
232                         return -1;
233                 }
234
235                 list = ast_calloc(1, sizeof(*list));
236                 if (!list) {
237                         ast_log(LOG_ERROR,
238                                 "Unable to allocate datastore list head.  %sLOCK will fail.\n",
239                                 trylock ? "TRY" : "");
240                         ast_datastore_free(lock_store);
241                         return -1;
242                 }
243
244                 lock_store->data = list;
245                 AST_LIST_HEAD_INIT(list);
246                 ast_channel_datastore_add(chan, lock_store);
247         } else
248                 list = lock_store->data;
249
250         /* Lock already exists? */
251         AST_LIST_LOCK(&locklist);
252         AST_LIST_TRAVERSE(&locklist, current, entries) {
253                 if (strcmp(current->name, lockname) == 0) {
254                         break;
255                 }
256         }
257
258         if (!current) {
259                 if (unloading) {
260                         /* Don't bother */
261                         AST_LIST_UNLOCK(&locklist);
262                         return -1;
263                 }
264
265                 /* Create new lock entry */
266                 current = ast_calloc(1, sizeof(*current) + strlen(lockname) + 1);
267                 if (!current) {
268                         AST_LIST_UNLOCK(&locklist);
269                         return -1;
270                 }
271
272                 strcpy(current->name, lockname); /* SAFE */
273                 if ((res = ast_mutex_init(&current->mutex))) {
274                         ast_log(LOG_ERROR, "Unable to initialize mutex: %s\n", strerror(res));
275                         ast_free(current);
276                         AST_LIST_UNLOCK(&locklist);
277                         return -1;
278                 }
279                 if ((res = ast_cond_init(&current->cond, NULL))) {
280                         ast_log(LOG_ERROR, "Unable to initialize condition variable: %s\n", strerror(res));
281                         ast_mutex_destroy(&current->mutex);
282                         ast_free(current);
283                         AST_LIST_UNLOCK(&locklist);
284                         return -1;
285                 }
286                 if (!(current->requesters = ao2_container_alloc(1, ast_channel_hash_cb, ast_channel_cmp_cb))) {
287                         ast_mutex_destroy(&current->mutex);
288                         ast_cond_destroy(&current->cond);
289                         ast_free(current);
290                         AST_LIST_UNLOCK(&locklist);
291                         return -1;
292                 }
293                 AST_LIST_INSERT_TAIL(&locklist, current, entries);
294         }
295         AST_LIST_UNLOCK(&locklist);
296
297         /* Found lock or created one - now find or create the corresponding link in the channel */
298         AST_LIST_LOCK(list);
299         AST_LIST_TRAVERSE(list, clframe, list) {
300                 if (clframe->lock_frame == current) {
301                         break;
302                 }
303         }
304
305         if (!clframe) {
306                 if (unloading) {
307                         /* Don't bother */
308                         AST_LIST_UNLOCK(list);
309                         return -1;
310                 }
311
312                 if (!(clframe = ast_calloc(1, sizeof(*clframe)))) {
313                         ast_log(LOG_ERROR,
314                                 "Unable to allocate channel lock frame.  %sLOCK will fail.\n",
315                                 trylock ? "TRY" : "");
316                         AST_LIST_UNLOCK(list);
317                         return -1;
318                 }
319
320                 clframe->lock_frame = current;
321                 clframe->channel = chan;
322                 AST_LIST_INSERT_TAIL(list, clframe, list);
323         }
324         AST_LIST_UNLOCK(list);
325
326         /* If we already own the lock, then we're being called recursively.
327          * Keep track of how many times that is, because we need to unlock
328          * the same amount, before we'll release this one.
329          */
330         if (current->owner == chan) {
331                 current->count++;
332                 return 0;
333         }
334
335         /* Okay, we have both frames, so now we need to try to lock.
336          *
337          * Locking order: always lock locklist first.  We need the
338          * locklist lock because the broker thread counts whether
339          * there are requesters with the locklist lock held, and we
340          * need to hold it, so that when we send our signal, below,
341          * to wake up the broker thread, it definitely will see that
342          * a requester exists at that point in time.  Otherwise, we
343          * could add to the requesters after it has already seen that
344          * that lock is unoccupied and wait forever for another signal.
345          */
346         AST_LIST_LOCK(&locklist);
347         ast_mutex_lock(&current->mutex);
348         /* Add to requester list */
349         ao2_link(current->requesters, chan);
350         pthread_kill(broker_tid, SIGURG);
351         AST_LIST_UNLOCK(&locklist);
352
353         /* Wait up to three seconds from now for LOCK. */
354         now = ast_tvnow();
355         timeout.tv_sec = now.tv_sec + 3;
356         timeout.tv_nsec = now.tv_usec * 1000;
357
358         if (!current->owner
359                 || (!trylock
360                         && !(res = ast_cond_timedwait(&current->cond, &current->mutex, &timeout)))) {
361                 res = 0;
362                 current->owner = chan;
363                 current->count++;
364         } else {
365                 res = -1;
366         }
367         /* Remove from requester list */
368         ao2_unlink(current->requesters, chan);
369         ast_mutex_unlock(&current->mutex);
370
371         return res;
372 }
373
374 static int unlock_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
375 {
376         struct ast_datastore *lock_store = ast_channel_datastore_find(chan, &lock_info, NULL);
377         struct channel_lock_frame *clframe;
378         AST_LIST_HEAD(, channel_lock_frame) *list;
379
380         if (!lock_store) {
381                 ast_log(LOG_WARNING, "No datastore for dialplan locks.  Nothing was ever locked!\n");
382                 ast_copy_string(buf, "0", len);
383                 return 0;
384         }
385
386         if (!(list = lock_store->data)) {
387                 ast_debug(1, "This should NEVER happen\n");
388                 ast_copy_string(buf, "0", len);
389                 return 0;
390         }
391
392         /* Find item in the channel list */
393         AST_LIST_LOCK(list);
394         AST_LIST_TRAVERSE(list, clframe, list) {
395                 if (clframe->lock_frame && clframe->lock_frame->owner == chan && strcmp(clframe->lock_frame->name, data) == 0) {
396                         break;
397                 }
398         }
399         /* We never destroy anything until channel destruction, which will never
400          * happen while this routine is executing, so we don't need to hold the
401          * lock beyond this point. */
402         AST_LIST_UNLOCK(list);
403
404         if (!clframe) {
405                 /* We didn't have this lock in the first place */
406                 ast_copy_string(buf, "0", len);
407                 return 0;
408         }
409
410         if (--clframe->lock_frame->count == 0) {
411                 clframe->lock_frame->owner = NULL;
412         }
413
414         ast_copy_string(buf, "1", len);
415         return 0;
416 }
417
418 static int lock_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
419 {
420         if (chan)
421                 ast_autoservice_start(chan);
422
423         ast_copy_string(buf, get_lock(chan, data, 0) ? "0" : "1", len);
424
425         if (chan)
426                 ast_autoservice_stop(chan);
427
428         return 0;
429 }
430
431 static int trylock_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
432 {
433         if (chan)
434                 ast_autoservice_start(chan);
435
436         ast_copy_string(buf, get_lock(chan, data, 1) ? "0" : "1", len);
437
438         if (chan)
439                 ast_autoservice_stop(chan);
440
441         return 0;
442 }
443
444 static struct ast_custom_function lock_function = {
445         .name = "LOCK",
446         .read = lock_read,
447         .read_max = 2,
448 };
449
450 static struct ast_custom_function trylock_function = {
451         .name = "TRYLOCK",
452         .read = trylock_read,
453         .read_max = 2,
454 };
455
456 static struct ast_custom_function unlock_function = {
457         .name = "UNLOCK",
458         .read = unlock_read,
459         .read_max = 2,
460 };
461
462 static int unload_module(void)
463 {
464         struct lock_frame *current;
465
466         /* Module flag */
467         unloading = 1;
468
469         AST_LIST_LOCK(&locklist);
470         while ((current = AST_LIST_REMOVE_HEAD(&locklist, entries))) {
471                 /* If any locks are currently in use, then we cannot unload this module */
472                 if (current->owner || ao2_container_count(current->requesters)) {
473                         /* Put it back */
474                         AST_LIST_INSERT_HEAD(&locklist, current, entries);
475                         AST_LIST_UNLOCK(&locklist);
476                         unloading = 0;
477                         return -1;
478                 }
479                 ast_mutex_destroy(&current->mutex);
480                 ao2_ref(current->requesters, -1);
481                 ast_free(current);
482         }
483
484         /* No locks left, unregister functions */
485         ast_custom_function_unregister(&lock_function);
486         ast_custom_function_unregister(&trylock_function);
487         ast_custom_function_unregister(&unlock_function);
488
489         if (broker_tid != AST_PTHREADT_NULL) {
490                 pthread_cancel(broker_tid);
491                 pthread_kill(broker_tid, SIGURG);
492                 pthread_join(broker_tid, NULL);
493         }
494
495         AST_LIST_UNLOCK(&locklist);
496
497         return 0;
498 }
499
500 static int load_module(void)
501 {
502         int res = ast_custom_function_register(&lock_function);
503         res |= ast_custom_function_register(&trylock_function);
504         res |= ast_custom_function_register(&unlock_function);
505
506         if (ast_pthread_create_background(&broker_tid, NULL, lock_broker, NULL)) {
507                 ast_log(LOG_ERROR, "Failed to start lock broker thread. Unloading func_lock module.\n");
508                 broker_tid = AST_PTHREADT_NULL;
509                 unload_module();
510                 return AST_MODULE_LOAD_DECLINE;
511         }
512
513         return res;
514 }
515
516 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Dialplan mutexes");