Asterisk.org: Developer Documentation (28 Oct 2009)

Wed Oct 28 15:49:20 2009

## Asterisk developer's documentation

# strings.h File Reference

String manipulation functions. More...

`#include <string.h>`
`#include <stdarg.h>`
`#include "asterisk/inline_api.h"`
`#include "asterisk/compiler.h"`
`#include "asterisk/compat.h"`

Include dependency graph for strings.h:

This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

## Data Structures

struct | ast_realloca

## Defines

#define | ast_restrdupa(ra, s)

## Functions

size_t const char | __attribute__ ((format(printf, 3, 4)))
int | ast_build_string_va (char **buffer, size_t *space, const char *fmt, va_list ap)
| Build a string in a buffer, designed to be called repeatedly.
int | ast_false (const char *val)
| AST_INLINE_API (void ast_copy_string(char *dst, const char *src, size_t size),{while(*src &&size){*dst++=*src++;size--;}if(__builtin_expect(!size, 0)) dst--;*dst= '\0';}) int ast_build_string(char **buffer
| Size-limited null-terminating string copy.
| AST_INLINE_API (char *ast_skip_blanks(char *str),{while(*str &&*str< 33) str++;return str;}) AST_INLINE_API(char *ast_trim_blanks(char *str)
| Gets a pointer to the first non-whitespace character in a string.
static force_inline int | ast_strlen_zero (const char *s)
int | ast_true (const char *val)
char * | strcasestr (const char *, const char *)
char * | strndup (const char *, size_t)
size_t | strnlen (const char *, size_t)
uint64_t | strtoq (const char *nptr, char **endptr, int base)
int | vasprintf (char **strp, const char *fmt, va_list ap)

## Variables

size_t const char * | fmt
size_t * | space

## Detailed Description

String manipulation functions.

Definition in file strings.h.

## Define Documentation

#define ast_restrdupa | ( | ra,
|  | s |  | ) |

Definition at line 220 of file strings.h.

## Function Documentation

size_t const char __attribute__ | ( | (format(printf, 3, 4)) |  | ) |

Type Constraints

Referenced by get_unaligned_uint16(), get_unaligned_uint32(), put_unaligned_uint16(), and put_unaligned_uint32().

int ast_build_string_va | ( | char ** | buffer,
|  | size_t * | space,
|  | const char * | fmt,
|  | va_list | ap |
| ) |  |  |

Build a string in a buffer, designed to be called repeatedly.

This is a wrapper for snprintf, that properly handles the buffer pointer and buffer space available.

Returns:
  0 on success, non-zero on failure.

Parameters:

  | buffer | current position in buffer to place string into (will be updated on return)
  | space | remaining space in buffer (will be updated on return)
  | fmt | printf-style format string
  | ap | varargs list of arguments for format

Definition at line 555 of file utils.c.

Referenced by ast_build_string(), and manager_event().

    00556 {
    00557    int result;
    00558
    00559    if (!buffer || !*buffer || !space || !*space)
    00560       return -1;
    00561
    00562    result = vsnprintf(*buffer, *space, fmt, ap);
    00563
    00564    if (result < 0)
    00565       return -1;
    00566    else if (result > *space)
    00567       result = *space;
    00568
    00569    *buffer += result;
    00570    *space -= result;
    00571    return 0;
    00572 }

int ast_false | ( | const char * | val | ) |

Make sure something is false

Determine if a string containing a boolean value is "false". This function checks to see whether a string passed to it is an indication of an "false" value. It checks to see if the string is "no", "false", "n", "f", "off" or "0".

Returns 0 if val is a NULL pointer, -1 if "false", and 0 otherwise.

Definition at line 603 of file utils.c.

References ast_strlen_zero().

Referenced by ast_rtp_reload(), ast_strings_to_mask(), build_peer(), build_user(), handle_common_options(), and pbx_load_module().

    00604 {
    00605    if (ast_strlen_zero(s))
    00606       return 0;
    00607
    00608    /* Determine if this is a false value */
    00609    if (!strcasecmp(s, "no") ||
    00610        !strcasecmp(s, "false") ||
    00611        !strcasecmp(s, "n") ||
    00612        !strcasecmp(s, "f") ||
    00613        !strcasecmp(s, "0") ||
    00614        !strcasecmp(s, "off"))
    00615       return -1;
    00616
    00617    return 0;
    00618 }

AST_INLINE_API | ( | void | ast_copy_stringchar *dst, const char *src, size_t size | ) |

Size-limited null-terminating string copy.

Parameters:

  | ast_copy_string | function being used
  | dst | The destination buffer.
  | src | The source string
  | size | The size of the destination buffer

Returns:
  Nothing.

This is similar to strncpy, with two important differences:

- the destination buffer will always be null-terminated
- the destination buffer is not filled with zeros past the copied string length These differences make it slightly more efficient, and safer to use since it will not leave the destination buffer unterminated. There is no need to pass an artificially reduced buffer size to this function (unlike strncpy), and the buffer does not need to be initialized to zeroes prior to calling this function.

Build a string in a buffer, designed to be called repeatedly This is a wrapper for snprintf, that properly handles the buffer pointer and buffer space available.

Parameters:

  | buffer | current position in buffer to place string into (will be updated on return)
  | space | remaining space in buffer (will be updated on return)
  | fmt | printf-style format string

Returns:
  0 on success, non-zero on failure.

AST_INLINE_API | ( | char * | ast_skip_blankschar *str | ) |

Gets a pointer to the first non-whitespace character in a string.

Parameters:

  | ast_skip_blanks | function being used
  | str | the input string

Returns:
  a pointer to the first non-whitespace character

Trims trailing whitespace characters from a string.

Parameters:

  | ast_trim_blanks | function being used
  | str | the input string

Returns:
  a pointer to the modified string

static force_inline int ast_strlen_zero | ( | const char * | s | ) | `[static]`

Definition at line 33 of file strings.h.

Referenced by __ast_callerid_generate(), __ast_cli_generator(), __ast_pbx_run(), __build_step(), __iax2_show_peers(), __login_exec(), __oh323_new(), __sip_show_channels(), _sip_show_peer(), _sip_show_peers(), _while_exec(), acf_curl_exec(), acf_strftime(), action_agent_callback_login(), action_agent_logoff(), action_agents(), action_command(), action_extensionstate(), action_getvar(), action_hangup(), action_listcommands(), action_mailboxcount(), action_mailboxstatus(), action_originate(), action_redirect(), action_setcdruserfield(), action_setvar(), action_status(), action_timeout(), action_transfer(), action_transferhangup(), action_zapdialoffhook(), action_zapdndoff(), action_zapdndon(), action_zapshowchannels(), add_calltoken_ignore(), add_realm_authentication(), add_sip_domain(), admin_exec(), adsi_exec(), adsi_message(), advanced_options(), agent_call(), agent_devicestate(), agent_hangup(), agent_new(), agent_read(), agent_request(), agents_show(), agi_exec_full(), alarmreceiver_exec(), alsa_new(), app_exec(), append_transaction(), apply_outgoing(), apply_peer(), aqm_exec(), ast_app_group_get_count(), ast_app_group_match_get_count(), ast_app_group_set_channel(), ast_app_group_split_group(), ast_async_goto(), ast_bridge_call(), ast_build_timing(), ast_callerid_parse(), ast_cdr_answer(), ast_cdr_busy(), ast_cdr_copy_vars(), ast_cdr_end(), ast_cdr_failed(), ast_cdr_free(), ast_cdr_getvar(), ast_cdr_getvar_internal(), ast_cdr_init(), ast_cdr_noanswer(), ast_cdr_serialize_variables(), ast_cdr_setapp(), ast_cdr_setdestchan(), ast_cdr_start(), ast_cdr_update(), ast_channel_bridge(), ast_db_gettree(), ast_dnsmgr_get(), ast_dnsmgr_lookup(), ast_explicit_goto(), ast_extension_close(), ast_false(), ast_feature_interpret(), ast_fileexists(), ast_frame_dump(), ast_iax2_new(), ast_isphonenumber(), ast_linear_stream(), ast_localtime(), ast_log(), ast_makesocket(), ast_mktime(), ast_modem_new(), ast_monitor_change_fname(), ast_monitor_start(), ast_monitor_stop(), ast_openstream_full(), ast_openvstream(), ast_park_call(), ast_parseable_goto(), ast_pbx_outgoing_app(), ast_pbx_outgoing_exten(), ast_privacy_set(), ast_read(), ast_remotecontrol(), ast_serialize_showchan(), ast_set_callerid(), ast_strings_to_mask(), ast_true(), astman_get_variables(), astman_send_error(), astman_send_response(), async_wait(), attempt_thread(), auth_exec(), authenticate(), authenticate_reply(), authenticate_verify(), authority_to_str(), autoanswer_complete(), background_detect_exec(), build_callid(), build_contact(), build_device(), build_gateway(), build_mapping(), build_peer(), build_reply_digest(), build_route(), build_rpid(), build_user(), builtin_atxfer(), builtin_automonitor(), builtin_blindtransfer(), builtin_function_cdr_read(), builtin_function_cdr_write(), builtin_function_checkmd5(), builtin_function_env_write(), builtin_function_if(), builtin_function_iftime(), builtin_function_math(), builtin_function_md5(), builtin_function_set(), builtin_function_uridecode(), builtin_function_uriencode(), callerid_feed(), callerid_genmsg(), callerid_write(), calltoken_required(), cb_events(), chan_misdn_log(), chanavail_exec(), change_monitor_action(), change_password_realtime(), channel_spy(), chanspy_exec(), check_access(), check_auth(), check_goto_on_transfer(), check_sip_domain(), check_user_full(), compile_script(), complete_show_applications(), conf_exec(), conf_run(), config_text_file_load(), console_dial(), console_sendtext(), controlplayback_exec(), copy_all_header(), copy_header(), copy_via_headers(), count_exec(), create_addr(), create_addr_from_peer(), csv_log(), curl_exec(), custom_log(), database_increment(), deltree_exec(), destroy_endpoint(), destroy_trans(), dial_exec_full(), dialout(), dictate_exec(), directory_exec(), disa_exec(), do_directory(), do_immediate_setup(), do_monitor(), dump_agents(), dumpchan_exec(), dundi_exec(), dundi_flags2str(), dundi_helper(), dundi_hint2str(), dundi_lookup_exec(), dundi_lookup_local(), dundi_query_thread(), dundi_show_mappings(), dundi_show_peer(), dundifunc_read(), enum_callback(), enumlookup_exec(), extract_uri(), fast_originate(), festival_exec(), find_call(), find_sdp(), find_sip_method(), forkcdr_exec(), forward_message(), func_check_sipdomain(), func_header_read(), function_db_exists(), function_db_read(), function_db_write(), function_enum(), function_eval(), function_fieldqty(), function_txtcidname(), get_callerid_ast(), get_cid_name(), get_day(), get_destination(), get_dow(), get_month(), get_rdnis(), get_refer_info(), get_timerange(), gosub_exec(), gosubif_exec(), group_check_exec(), group_count_exec(), group_function_read(), group_function_write(), group_list_function_read(), group_match_count_exec(), group_match_count_function_read(), group_show_channels(), handle_chanlist(), handle_command_response(), handle_controlstreamfile(), handle_getvariable(), handle_request(), handle_request_bye(), handle_request_info(), handle_request_invite(), handle_request_options(), handle_request_refer(), handle_request_subscribe(), handle_response(), handle_response_register(), handle_saydatetime(), handle_show_dialplan(), handle_show_voicemail_users(), handle_showchan(), has_voicemail(), hasvoicemail_exec(), hasvoicemail_internal(), i4l_dial(), i4l_init(), i4l_read(), iax2_call(), iax2_datetime(), iax2_devicestate(), iax2_prov_app(), iax2_show_cache(), iax2_show_channels(), iax2_show_peer(), iax2_show_users(), iax_check_version(), iax_firmware_append(), ices_exec(), initreqprep(), join(), launch_monitor_thread(), launch_netscript(), leave_voicemail(), load_config(), load_moh_classes(), local_ast_moh_start(), log_events(), lookupblacklist_exec(), loopback_subst(), macro_exec(), main(), make_logchannel(), manager_add_queue_member(), manager_dbget(), manager_event(), manager_iax2_show_peers(), manager_parking_status(), manager_pause_queue_member(), manager_queues_status(), manager_remove_queue_member(), manager_sip_show_peer(), manager_sip_show_peers(), matchcid(), math_exec(), md5_exec(), md5check_exec(), messagecount(), mgcp_call(), mgcp_hangup(), mgcp_new(), mgcp_request(), mgcp_ss(), mgcpsock_read(), misdn_answer(), misdn_call(), misdn_check_l2l1(), misdn_facility_exec(), misdn_new(), misdn_request(), misdn_set_opt_exec(), mixmonitor_exec(), mkintf(), moh2_exec(), moh_classes_show(), monitor_handle_owned(), mp3_exec(), nbs_alloc(), notify_new_message(), oh323_call(), oh323_request(), onedigit_goto(), ospfinished_exec(), osplookup_exec(), ospnext_exec(), oss_new(), page_exec(), park_exec(), parkandannounce_exec(), parse(), parse_dial_string(), parse_register_contact(), parse_request(), parse_sip_options(), pbx_builtin_answer(), pbx_builtin_execiftime(), pbx_builtin_gotoif(), pbx_builtin_gotoiftime(), pbx_builtin_importvar(), pbx_builtin_resetcdr(), pbx_builtin_saynumber(), pbx_builtin_setglobalvar(), pbx_builtin_setlanguage(), pbx_builtin_setvar(), pbx_extension_helper(), pbx_substitute_variables_helper_full(), PGSQL_exec(), phone_call(), phone_new(), pickup_exec(), play_mailbox_owner(), play_message_callerid(), play_message_category(), play_message_datetime(), playback_exec(), post_cdr(), pqm_exec(), privacy_exec(), process_ast_dsp(), process_message(), process_sdp(), process_text_line(), process_token(), queue_exec(), queue_function_qac(), quit_handler(), random_exec(), read_agent_config(), read_config(), read_exec(), readfile_exec(), realtime_exec(), realtime_multi_odbc(), realtime_odbc(), realtime_update_exec(), receive_ademco_contact_id(), record_exec(), register_peer_exten(), register_verify(), registry_rerequest(), reload_config(), reload_queue_members(), reply_digest(), reqprep(), requirecalltoken_mark_auto(), respprep(), retrydial_exec(), return_exec(), rpt_exec(), rqm_exec(), run_externnotify(), senddtmf_exec(), sendimage_exec(), sendmail(), sendpage(), sendtext_exec(), sendurl_exec(), session_do(), set_agentbycallerid(), set_member_paused(), setcallerid_exec(), setup_incoming_call(), setup_zap(), sip_addheader(), sip_getheader(), sip_hangup(), sip_new(), sip_poke_peer(), sip_register(), sip_request_call(), sip_sendtext(), sip_show_channel(), sip_show_domains(), sip_show_settings(), sip_show_user(), sip_sipredirect(), skel_exec(), skinny_new(), skinny_register(), skinny_request(), skinny_ss(), socket_read(), softhangup_exec(), spawn_mp3(), srv_callback(), ss_thread(), start_monitor_action(), start_monitor_exec(), stop_monitor_action(), store_config(), system_exec_helper(), testclient_exec(), testserver_exec(), transfer_exec(), transmit_fake_auth_response(), transmit_invite(), transmit_modify_request(), transmit_modify_with_sdp(), transmit_notify_request(), transmit_notify_request_with_callerid(), transmit_notify_with_mwi(), transmit_refer(), transmit_register(), try_calling(), try_firmware(), txtcidname_exec(), unalloc_sub(), update_registry(), upqm_exec(), userevent_exec(), valid_exit(), vm_authenticate(), vm_box_exists(), vm_change_password(), vm_exec(), vm_execmain(), vm_newuser(), vm_options(), vmauthenticate(), vpb_new(), wait_for_answer(), wait_for_hangup(), zapateller_exec(), zt_call(), zt_handle_dtmfup(), zt_handle_event(), zt_new(), and zt_read().

    00034 {
    00035    return (!s || (*s == '\0'));
    00036 }

int ast_true | ( | const char * | val | ) |

Make sure something is true

Determine if a string containing a boolean value is "true". This function checks to see whether a string passed to it is an indication of an "true" value. It checks to see if the string is "yes", "true", "y", "t", "on" or "1".

Returns 0 if val is a NULL pointer, -1 if "true", and 0 otherwise.

Definition at line 586 of file utils.c.

References ast_strlen_zero().

Referenced by __load_resource(), __login_exec(), _parse(), action_agent_callback_login(), action_agent_logoff(), action_originate(), action_setcdruserfield(), apply_option(), ast_readconfig(), ast_strings_to_mask(), build_device(), build_gateway(), build_peer(), build_user(), config_load(), dial_exec_full(), do_reload(), festival_exec(), function_ilink(), get_encrypt_methods(), handle_common_options(), init_logger_chain(), init_manager(), load_config(), load_module(), load_modules(), load_moh_classes(), load_odbc_config(), loadconfigurationfile(), manager_add_queue_member(), manager_pause_queue_member(), odbc_load_module(), parse_config(), pbx_load_module(), queue_set_param(), read_agent_config(), reload_config(), reload_queues(), rpt_master(), set_config(), setup_zap(), start_monitor_action(), and update_common_options().

    00587 {
    00588    if (ast_strlen_zero(s))
    00589       return 0;
    00590
    00591    /* Determine if this is a true value */
    00592    if (!strcasecmp(s, "yes") ||
    00593        !strcasecmp(s, "true") ||
    00594        !strcasecmp(s, "y") ||
    00595        !strcasecmp(s, "t") ||
    00596        !strcasecmp(s, "1") ||
    00597        !strcasecmp(s, "on"))
    00598       return -1;
    00599
    00600    return 0;
    00601 }

char* strcasestr | ( | const char * | ,
|  | const char * |  |
| ) |  |  |

Definition at line 684 of file utils.c.

References ast_log(), LOG_ERROR, offset, and upper().

Referenced by anti_injection(), do_directory(), find_sdp(), gettag(), handle_response_register(), handle_show_applications(), modlist_modentry(), parse_register_contact(), playback_exec(), realtime_multi_odbc(), realtime_odbc(), reqprep(), respprep(), and sip_sipredirect().

    00685 {
    00686    char *u1, *u2;
    00687    int u1len = strlen(haystack) + 1, u2len = strlen(needle) + 1;
    00688
    00689    u1 = alloca(u1len);
    00690    u2 = alloca(u2len);
    00691    if (u1 && u2) {
    00692       char *offset;
    00693       if (u2len > u1len) {
    00694          /* Needle bigger than haystack */
    00695          return NULL;
    00696       }
    00697       offset = strstr(upper(haystack, u1, u1len), upper(needle, u2, u2len));
    00698       if (offset) {
    00699          /* Return the offset into the original string */
    00700          return ((char *)((unsigned long)haystack + (unsigned long)(offset - u1)));
    00701       } else {
    00702          return NULL;
    00703       }
    00704    } else {
    00705       ast_log(LOG_ERROR, "Out of memory\n");
    00706       return NULL;
    00707    }
    00708 }

char* strndup | ( | const char * | ,
|  | size_t |  |
| ) |  |  |

Definition at line 725 of file utils.c.

References malloc, and strnlen().

    00726 {
    00727    size_t len = strnlen(s, n);
    00728    char *new = malloc(len + 1);
    00729
    00730    if (!new)
    00731       return NULL;
    00732
    00733    new[len] = '\0';
    00734    return memcpy(new, s, len);
    00735 }

size_t strnlen | ( | const char * | ,
|  | size_t |  |
| ) |  |  |

Definition at line 712 of file utils.c.

Referenced by strndup().

    00713 {
    00714    size_t len;
    00715
    00716    for (len=0; len < n; len++)
    00717       if (s[len] == '\0')
    00718          break;
    00719
    00720    return len;
    00721 }

uint64_t strtoq | ( | const char * | nptr,
|  | char ** | endptr,
|  | int | base |
| ) |  |  |

Definition at line 774 of file utils.c.

References LONG_MAX, LONG_MIN, and s.

    00775 {
    00776     const char *s;
    00777     uint64_t acc;
    00778     unsigned char c;
    00779     uint64_t qbase, cutoff;
    00780     int neg, any, cutlim;
    00781
    00782     /*
    00783      * Skip white space and pick up leading +/- sign if any.
    00784      * If base is 0, allow 0x for hex and 0 for octal, else
    00785      * assume decimal; if base is already 16, allow 0x.
    00786      */
    00787     s = nptr;
    00788     do {
    00789             c = *s++;
    00790     } while (isspace(c));
    00791     if (c == '-') {
    00792             neg = 1;
    00793             c = *s++;
    00794     } else {
    00795             neg = 0;
    00796             if (c == '+')
    00797                     c = *s++;
    00798     }
    00799     if ((base == 0 || base == 16) &&
    00800         c == '\0' && (*s == 'x' || *s == 'X')) {
    00801             c = s[1];
    00802             s += 2;
    00803             base = 16;
    00804     }
    00805     if (base == 0)
    00806             base = c == '\0' ? 8 : 10;
    00807
    00808     /*
    00809      * Compute the cutoff value between legal numbers and illegal
    00810      * numbers.  That is the largest legal value, divided by the
    00811      * base.  An input number that is greater than this value, if
    00812      * followed by a legal input character, is too big.  One that
    00813      * is equal to this value may be valid or not; the limit
    00814      * between valid and invalid numbers is then based on the last
    00815      * digit.  For instance, if the range for quads is
    00816      * [-9223372036854775808..9223372036854775807] and the input base
    00817      * is 10, cutoff will be set to 922337203685477580 and cutlim to
    00818      * either 7 (neg==0) or 8 (neg==1), meaning that if we have
    00819      * accumulated a value > 922337203685477580, or equal but the
    00820      * next digit is > 7 (or 8), the number is too big, and we will
    00821      * return a range error.
    00822      *
    00823      * Set any if any `digits' consumed; make it negative to indicate
    00824      * overflow.
    00825      */
    00826     qbase = (unsigned)base;
    00827     cutoff = neg ? (uint64_t)-(LONG_MIN + LONG_MAX) + LONG_MAX : LONG_MAX;
    00828     cutlim = cutoff % qbase;
    00829     cutoff /= qbase;
    00830     for (acc = 0, any = 0;; c = *s++) {
    00831             if (!isascii(c))
    00832                     break;
    00833             if (isdigit(c))
    00834                     c -= '\0';
    00835             else if (isalpha(c))
    00836                     c -= isupper(c) ? 'A' - 10 : 'a' - 10;
    00837             else
    00838                     break;
    00839             if (c >= base)
    00840                     break;
    00841             if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
    00842                     any = -1;
    00843             else {
    00844                     any = 1;
    00845                     acc *= qbase;
    00846                     acc += c;
    00847             }
    00848     }
    00849     if (any < 0) {
    00850             acc = neg ? LONG_MIN : LONG_MAX;
    00851     } else if (neg)
    00852             acc = -acc;
    00853     if (endptr != 0)
    00854             *((const char **)endptr) = any ? s - 1 : nptr;
    00855     return acc;
    00856 }

int vasprintf | ( | char ** | strp,
|  | const char * | fmt,
|  | va_list | ap |
| ) |  |  |

Definition at line 739 of file utils.c.

References malloc, and s.

    00740 {
    00741    int size;
    00742    va_list ap2;
    00743    char s;
    00744
    00745    *strp = NULL;
    00746    va_copy(ap2, ap);
    00747    size = vsnprintf(&s, 1, fmt, ap2);
    00748    va_end(ap2);
    00749    *strp = malloc(size + 1);
    00750    if (!*strp)
    00751       return -1;
    00752    vsnprintf(*strp, size + 1, fmt, ap);
    00753
    00754    return size;
    00755 }

## Variable Documentation

size_t const char* fmt

Definition at line 179 of file strings.h.

Referenced by __oh323_new(), ast_cdr_getvar(), ast_cli_netstats(), ast_openvstream(), ast_request(), check_header(), do_chanreads(), iax2_request(), local_new(), mgcp_new(), setformat(), sip_new(), skinny_new(), try_suggested_sip_codec(), vpb_write(), and write_header().

size_t* space

Definition at line 179 of file strings.h.

Referenced by dundi_decrypt(), and phone_write_buf().