Example #1
0
SWITCH_DECLARE(uint32_t) switch_scheduler_del_task_group(const char *group)
{
	switch_scheduler_task_container_t *tp;
	switch_event_t *event;
	uint32_t delcnt = 0;

	switch_mutex_lock(globals.task_mutex);
	for (tp = globals.task_list; tp; tp = tp->next) {
		if (!zstr(group) && !strcmp(tp->task.group, group)) {
			if (switch_test_flag(tp, SSHF_NO_DEL)) {
				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Attempt made to delete undeletable task #%u (group %s)\n",
								  tp->task.task_id, group);
				continue;
			}
			if (switch_event_create(&event, SWITCH_EVENT_DEL_SCHEDULE) == SWITCH_STATUS_SUCCESS) {
				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Task-ID", "%u", tp->task.task_id);
				switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Task-Desc", tp->desc);
				switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Task-Group", switch_str_nil(tp->task.group));
				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Task-Runtime", "%" SWITCH_INT64_T_FMT, tp->task.runtime);
				switch_event_fire(&event);
			}
			tp->destroyed++;
			delcnt++;
		}
	}
	switch_mutex_unlock(globals.task_mutex);

	return delcnt;
}
Example #2
0
SWITCH_DECLARE(switch_odbc_status_t) switch_odbc_handle_exec(switch_odbc_handle_t *handle, const char *sql, switch_odbc_statement_handle_t *rstmt,
															 char **err)
{
#ifdef SWITCH_HAVE_ODBC
	SQLHSTMT stmt = NULL;
	int result;
	char *err_str = NULL;

	if (!db_is_up(handle)) {
		goto error;
	}

	if (SQLAllocHandle(SQL_HANDLE_STMT, handle->con, &stmt) != SQL_SUCCESS) {
		goto error;
	}

	if (SQLPrepare(stmt, (unsigned char *) sql, SQL_NTS) != SQL_SUCCESS) {
		goto error;
	}

	result = SQLExecute(stmt);

	if (result != SQL_SUCCESS && result != SQL_SUCCESS_WITH_INFO && result != SQL_NO_DATA) {
		goto error;
	}

	if (rstmt) {
		*rstmt = stmt;
	} else {
		SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	}

	return SWITCH_ODBC_SUCCESS;

  error:

	if (stmt) {
		err_str = switch_odbc_handle_get_error(handle, stmt);
	}

	if (err_str) {
		if (!switch_stristr("already exists", err_str) && !switch_stristr("duplicate key name", err_str)) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "ERR: [%s]\n[%s]\n", sql, switch_str_nil(err_str));
		}
		if (err) {
			*err = err_str;
		} else {
			free(err_str);
		}
	}

	if (rstmt) {
		*rstmt = stmt;
	} else if (stmt) {
		SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	}
#endif
	return SWITCH_ODBC_FAIL;
}
Example #3
0
void eventpipe_events_on_dtmf(switch_core_session_t *session, switch_event_t *event) {
	char args[8192];
	const char *dtmf_digit = switch_str_nil(switch_event_get_header(event, "dtmf-digit"));
	switch_channel_t *channel = switch_core_session_get_channel(session);
	const char *hangup_on_star = switch_str_nil(switch_channel_get_variable(channel, "eventpipe_conference_hangup_on_star"));
	const char *conf_room = switch_str_nil(switch_channel_get_variable(channel, "eventpipe_conference_room"));
	const char *conf_member_id = switch_str_nil(switch_channel_get_variable(channel, "eventpipe_conference_member_id"));

	/* handle conference kick if channel is in conference and digit '*' was pressed */
	if ((!strcmp(hangup_on_star, "true")) && (!strcmp(dtmf_digit, "*")) && (!zstr(conf_room)) && (!zstr(conf_member_id))) {
		switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, 
				"Conference, dtmf '*' pressed, kick member %s from room %s\n",
				conf_member_id, conf_room);
		switch_snprintf(args, sizeof(args), "%s kick %s", conf_room, conf_member_id);
		eventpipe_execute_api(session, "conference", args);
	}
}
Example #4
0
/* Api helper */
switch_status_t eventpipe_execute_api(switch_core_session_t *session, char *cmd, char *args) {
	switch_status_t status;
	switch_stream_handle_t stream = { 0 };
	SWITCH_STANDARD_STREAM(stream);

	switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "api: cmd %s, args %s\n", 
			  cmd, switch_str_nil(args));
	status = switch_api_execute(cmd, args, session, &stream);
	if (status != SWITCH_STATUS_SUCCESS) {
		switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, 
				"api: %s(%s) failed\n", cmd, switch_str_nil(args));
	} else {
		switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, 
				"api: %s(%s) %s\n", cmd, switch_str_nil(args), (char *) stream.data);
	}
	free(stream.data);
	return status;
}
Example #5
0
SWITCH_DECLARE(uint32_t) switch_scheduler_add_task(time_t task_runtime,
												   switch_scheduler_func_t func,
												   const char *desc, const char *group, uint32_t cmd_id, void *cmd_arg, switch_scheduler_flag_t flags)
{
	switch_scheduler_task_container_t *container, *tp;
	switch_event_t *event;

	switch_mutex_lock(globals.task_mutex);
	switch_zmalloc(container, sizeof(*container));
	switch_assert(func);
	container->func = func;
	container->task.created = switch_epoch_time_now(NULL);
	container->task.runtime = task_runtime;
	container->task.group = strdup(group ? group : "none");
	container->task.cmd_id = cmd_id;
	container->task.cmd_arg = cmd_arg;
	container->flags = flags;
	container->desc = strdup(desc ? desc : "none");

	for (tp = globals.task_list; tp && tp->next; tp = tp->next);

	if (tp) {
		tp->next = container;
	} else {
		globals.task_list = container;
	}

	for (container->task.task_id = 0; !container->task.task_id; container->task.task_id = ++globals.task_id);

	switch_mutex_unlock(globals.task_mutex);

	tp = container;
	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Added task %u %s (%s) to run at %" SWITCH_INT64_T_FMT "\n",
					  tp->task.task_id, tp->desc, switch_str_nil(tp->task.group), tp->task.runtime);

	if (switch_event_create(&event, SWITCH_EVENT_ADD_SCHEDULE) == SWITCH_STATUS_SUCCESS) {
		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Task-ID", "%u", tp->task.task_id);
		switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Task-Desc", tp->desc);
		switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Task-Group", switch_str_nil(tp->task.group));
		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Task-Runtime", "%" SWITCH_INT64_T_FMT, tp->task.runtime);
		switch_event_fire(&event);
	}
	return container->task.task_id;
}
Example #6
0
static switch_status_t load_profile(switch_xml_t xml)
{
	switch_xml_t param, settings;
	char *name = (char *) switch_xml_attr_soft(xml, "name");
	logfile_profile_t *new_profile;

	new_profile = switch_core_alloc(module_pool, sizeof(*new_profile));
	memset(new_profile, 0, sizeof(*new_profile));
	switch_core_hash_init(&(new_profile->log_hash));
	new_profile->name = switch_core_strdup(module_pool, switch_str_nil(name));

	new_profile->suffix = 1;
	new_profile->log_uuid = SWITCH_TRUE;

	if ((settings = switch_xml_child(xml, "settings"))) {
		for (param = switch_xml_child(settings, "param"); param; param = param->next) {
			char *var = (char *) switch_xml_attr_soft(param, "name");
			char *val = (char *) switch_xml_attr_soft(param, "value");
			if (!strcmp(var, "logfile")) {
				new_profile->logfile = strdup(val);
			} else if (!strcmp(var, "rollover")) {
				new_profile->roll_size = switch_atoui(val);
			} else if (!strcmp(var, "maximum-rotate")) {
				new_profile->max_rot = switch_atoui(val);
				if (new_profile->max_rot == 0) {
					new_profile->max_rot = MAX_ROT;
				}
			} else if (!strcmp(var, "uuid")) {
				new_profile->log_uuid = switch_true(val);
			}
		}
	}

	if ((settings = switch_xml_child(xml, "mappings"))) {
		for (param = switch_xml_child(settings, "map"); param; param = param->next) {
			char *var = (char *) switch_xml_attr_soft(param, "name");
			char *val = (char *) switch_xml_attr_soft(param, "value");

			add_mapping(new_profile, var, val);
		}
	}

	if (zstr(new_profile->logfile)) {
		char logfile[512];
		switch_snprintf(logfile, sizeof(logfile), "%s%s%s", SWITCH_GLOBAL_dirs.log_dir, SWITCH_PATH_SEPARATOR, "freeswitch.log");
		new_profile->logfile = strdup(logfile);
	}

	if (mod_logfile_openlogfile(new_profile, SWITCH_TRUE) != SWITCH_STATUS_SUCCESS) {
		return SWITCH_STATUS_GENERR;
	}

	switch_core_hash_insert_destructor(profile_hash, new_profile->name, (void *) new_profile, cleanup_profile);
	return SWITCH_STATUS_SUCCESS;
}
Example #7
0
SWITCH_DECLARE(void) console_log(char *level_str, char *msg)
{
    switch_log_level_t level = SWITCH_LOG_DEBUG;
    if (level_str) {
        level = switch_log_str2level(level_str);
		if (level == SWITCH_LOG_INVALID) {
			level = SWITCH_LOG_DEBUG;
		}
    }
    switch_log_printf(SWITCH_CHANNEL_LOG, level, "%s", switch_str_nil(msg));
}
Example #8
0
SWITCH_DECLARE(switch_pgsql_status_t) switch_pgsql_handle_exec_base(switch_pgsql_handle_t *handle, const char *sql, char **err)
{
#ifdef SWITCH_HAVE_PGSQL
	char *err_str = NULL;

	handle->affected_rows = 0;

	if (!db_is_up(handle)) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Database is not up!\n");
		goto error;
	}

	if (handle->auto_commit == SWITCH_FALSE && handle->in_txn == SWITCH_FALSE) {
		if (switch_pgsql_send_query(handle, "BEGIN") != SWITCH_PGSQL_SUCCESS) {
			switch_pgsql_finish_results(handle);
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error sending BEGIN!\n");
			goto error;
		}

		if (switch_pgsql_finish_results(handle) != SWITCH_PGSQL_SUCCESS) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error sending BEGIN!\n");
			goto error;
		}
		handle->in_txn = SWITCH_TRUE;
	}

	if (switch_pgsql_send_query(handle, sql) != SWITCH_PGSQL_SUCCESS) {
		switch_pgsql_finish_results(handle);
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error sending query!\n");
		goto error;
	}

	return SWITCH_PGSQL_SUCCESS;

  error:
	err_str = switch_pgsql_handle_get_error(handle);

	if (zstr(err_str)) {
		err_str = strdup((char *)"SQL ERROR!");
	}
	
	if (err_str) {
		if (!switch_stristr("already exists", err_str) && !switch_stristr("duplicate key name", err_str)) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "ERR: [%s]\n[%s]\n", sql, switch_str_nil(err_str));
		}
		if (err) {
			*err = err_str;
		} else {
			free(err_str);
		}
	}
#endif
	return SWITCH_PGSQL_FAIL;
}
Example #9
0
SWITCH_DECLARE(void) CoreSession::consoleLog(char *level_str, char *msg)
{
	switch_log_level_t level = SWITCH_LOG_DEBUG;
	if (level_str) {
		level = switch_log_str2level(level_str);
		if (level == SWITCH_LOG_INVALID) {
			level = SWITCH_LOG_DEBUG;
		}
	}
	switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), level, "%s", switch_str_nil(msg));
}
Example #10
0
SWITCH_DECLARE(void) console_log2(char *level_str, char *file, char *func, int line, char *msg)
{
    switch_log_level_t level = SWITCH_LOG_DEBUG;
    if (level_str) {
        level = switch_log_str2level(level_str);
        if (level == SWITCH_LOG_INVALID) {
            level = SWITCH_LOG_DEBUG;
        }
    }
    switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, NULL, level, "%s", switch_str_nil(msg));
}
Example #11
0
switch_status_t FSHost::sendCmd(const char *cmd, const char *args, QString *res)
{
    switch_status_t status = SWITCH_STATUS_FALSE;
    switch_stream_handle_t stream = { 0 };
    SWITCH_STANDARD_STREAM(stream);
    //qDebug() << "Sending command: " << cmd << args << endl;
    status = switch_api_execute(cmd, args, NULL, &stream);
    *res = switch_str_nil((char *) stream.data);
    switch_safe_free(stream.data);

    return status;
}
Example #12
0
SWITCH_DECLARE(void) CoreSession::consoleLog2(char *level_str, char *file, char *func, int line, char *msg)
{
	switch_log_level_t level = SWITCH_LOG_DEBUG;
	if (level_str) {
		level = switch_log_str2level(level_str);
		if (level == SWITCH_LOG_INVALID) {
			level = SWITCH_LOG_DEBUG;
		}
	}
    switch_log_printf(SWITCH_CHANNEL_ID_SESSION, file, func, line, (const char*)session,
					  level, "%s", switch_str_nil(msg));
}
Example #13
0
static void api_hook(switch_core_session_t *session, const char *hook_var, int use_session)
{
	if (!zstr(hook_var)) {
		switch_stream_handle_t stream = { 0 };
		char *cmd = strdup(hook_var);
		char *arg = NULL;
		char *expanded = NULL;

		if ((arg = strchr(cmd, ':')) && *(arg + 1) == ':') {
			*arg++ = '\0';
			*arg++ = '\0';
		} else {
			if ((arg = strchr(cmd, ' '))) {
				*arg++ = '\0';
			}
		}

		SWITCH_STANDARD_STREAM(stream);

		switch_channel_get_variables(session->channel, &stream.param_event);
		switch_channel_event_set_data(session->channel, stream.param_event);
		expanded = switch_event_expand_headers(stream.param_event, arg);

		switch_api_execute(cmd, expanded, use_session ? session : NULL, &stream);

		switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Hangup Command %s %s(%s):\n%s\n",
						  use_session ? "with Session" : "with no Session", cmd, switch_str_nil(expanded),
						  switch_str_nil((char *) stream.data) );

		if (expanded != arg) {
			switch_safe_free(expanded);
		}

		switch_safe_free(cmd);
		
		switch_safe_free(stream.data);
	}
}
Example #14
0
void eventpipe_events_handler(switch_event_t *event)
{
	struct eventpipe_call *current = NULL;
	const char *uuid1 = "";
	const char *uuid2 = "";

        switch_assert(event != NULL);

	if ((event->event_id != SWITCH_EVENT_CUSTOM) && (event->event_id != SWITCH_EVENT_DTMF)) {
		return;
	}

	uuid1 = switch_event_get_header(event, "unique-id");
	if (zstr(uuid1)) {
		return;
	}
	switch_mutex_lock(globals.eventpipe_call_list_mutex);

	if (!head) {
		goto eventpipe_events_handler_done;
	}
	if (!head->session) {
		goto eventpipe_events_handler_done;
	}
	current = head;
	while (current) {
		if (current->session) {
			uuid2 = "";
			uuid2 = switch_core_session_get_uuid(current->session);	

			/* check if event unique-id is matching a call uuid in eventpipe */
			if ((uuid2) && (!zstr(uuid2) && (!strcmp(uuid1, uuid2)))) {
				/* conference event case */
				if (event->event_id == SWITCH_EVENT_CUSTOM) {
					const char *event_subclass = switch_str_nil(switch_event_get_header(event, "event-subclass"));
					if (!strcmp(event_subclass, PLIVO_EVENT_CONFERENCE)) {
						eventpipe_events_on_conference(current->session, event);
					}
				/* dtmf event case */
				} else if (event->event_id == SWITCH_EVENT_DTMF) {
					eventpipe_events_on_dtmf(current->session, event);
				}
				goto eventpipe_events_handler_done;
			}
		}
		current = current->next;
	}
eventpipe_events_handler_done:
	switch_mutex_unlock(globals.eventpipe_call_list_mutex);
}
static int cidlookup_callback(void *pArg, int argc, char **argv, char **columnNames)
{
	callback_t *cbt = (callback_t *) pArg;
	switch_memory_pool_t *pool = cbt->pool;

	if (argc < 1) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unexpected number of columns returned for SQL.  Returned column count: %d. ", argc);
		return SWITCH_STATUS_GENERR;
	}
	cbt->name = switch_core_strdup(pool, switch_str_nil(argv[0]));
	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG10, "Name: %s\n", cbt->name);

	return SWITCH_STATUS_SUCCESS;
}
Example #16
0
void eventpipe_events_on_conference(switch_core_session_t *session, switch_event_t *event) {
	char args[8192];
	char record_args[8192];
	const char *action = switch_str_nil(switch_event_get_header(event, "action"));
	const char *member_id = switch_str_nil(switch_event_get_header(event, "member-id"));
	const char *conf_room = switch_str_nil(switch_event_get_header(event, "conference-name"));
	const char *calluuid = switch_core_session_get_uuid(session);
	switch_channel_t *channel = switch_core_session_get_channel(session);
	if (!channel) {
		return;
	}

	switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, 
				"Event-Name: %s, Event-Subclass: %s, Conference-Name: %s, Action: %s, Member-ID: %s, Unique-ID: %s\n", 
				switch_str_nil(switch_event_get_header(event, "event-name")), 
				switch_str_nil(switch_event_get_header(event, "event-subclass")), 
				conf_room, action, member_id, calluuid);

	if (!strcmp(action, "add-member")) {
		const char *enter_sound = switch_str_nil(switch_channel_get_variable(channel, "eventpipe_conference_enter_sound"));
		const char *record_file = switch_str_nil(switch_channel_get_variable(channel, "eventpipe_conference_record_file"));
		switch_channel_set_variable(channel, "eventpipe_conference_member_id", member_id);
		switch_channel_set_variable(channel, "eventpipe_conference_room", conf_room);
		if (!zstr(enter_sound)) {
			switch_snprintf(args, sizeof(args), "%s play %s async",
					conf_room, enter_sound);
			eventpipe_execute_api(session, "conference", args);
		}
		if (!zstr(record_file)) {
			switch_snprintf(record_args, sizeof(record_args), "%s record %s",
					conf_room, record_file);
			eventpipe_execute_api(session, "conference", record_args);
		}
	} else if (!strcmp(action, "del-member")) {
		const char *exit_sound = switch_str_nil(switch_channel_get_variable(channel, "eventpipe_conference_exit_sound"));
		switch_channel_set_variable(channel, "eventpipe_conference_member_id", "");
		switch_channel_set_variable(channel, "eventpipe_conference_room", "");
		switch_channel_set_variable(channel, "eventpipe_conference_record_file", "");
		if (!zstr(exit_sound)) {
			switch_snprintf(args, sizeof(args), "conference %s play %s async",
					conf_room, exit_sound);
			eventpipe_execute_api(session, "conference", args);
		}
	}
}
Example #17
0
/* At this time, billing never succeeds if you don't have a database. */
static switch_status_t bill_event(double billamount, const char *billaccount, switch_channel_t *channel)
{
	char *sql = NULL, *dsql = NULL;
	switch_odbc_statement_handle_t stmt = NULL;
	switch_status_t status = SWITCH_STATUS_FALSE;

	if (!switch_odbc_available()) {
		return status;
	}

	if (globals.custom_sql_save) {
		if (switch_string_var_check_const(globals.custom_sql_save) || switch_string_has_escaped_data(globals.custom_sql_save)) {
			switch_channel_set_variable_printf(channel, "nibble_bill", "%f", billamount, SWITCH_FALSE);
			sql = switch_channel_expand_variables(channel, globals.custom_sql_save);
			if (sql != globals.custom_sql_save) dsql = sql;
		} else {
			sql = globals.custom_sql_save;
		}
	} else {
		sql = dsql = switch_mprintf("UPDATE %s SET %s=%s-%f WHERE %s='%s'", globals.db_table, globals.db_column_cash, 
									globals.db_column_cash, billamount, globals.db_column_account, billaccount);
		
	}

	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Doing update query\n[%s]\n", sql);

	if (switch_odbc_handle_exec(globals.master_odbc, sql, &stmt, NULL) != SWITCH_ODBC_SUCCESS) {
		char *err_str;
		err_str = switch_odbc_handle_get_error(globals.master_odbc, stmt);
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "ERR: [%s]\n[%s]\n", sql, switch_str_nil(err_str));
		switch_safe_free(err_str);
	} else {
		status = SWITCH_STATUS_SUCCESS;
	}

	if (stmt) {
		switch_odbc_statement_handle_free(&stmt);
	}
	
	switch_safe_free(dsql);

	return status;
}
Example #18
0
static switch_bool_t is_valid_action(const char *action)
{
	int i;

	if (!zstr(action)) {
		for (i = 0;; i++) {
			if (!iam[i].name) {
				break;
			}

			if (!strcmp(iam[i].name, action)) {
				return SWITCH_TRUE;
			}
		}
	}

	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid Action [%s]\n", switch_str_nil(action));
	return SWITCH_FALSE;
}
Example #19
0
static int db_is_up(switch_odbc_handle_t *handle)
{
	int ret = 0;
	SQLHSTMT stmt = NULL;
	SQLLEN m = 0;
	int result;
	switch_event_t *event;
	switch_odbc_status_t recon = 0;
	char *err_str = NULL;
	SQLCHAR sql[255] = "";
	int max_tries = DEFAULT_ODBC_RETRIES;
	int code = 0;
	SQLRETURN rc;
	SQLSMALLINT nresultcols;


	if (handle) {
		max_tries = handle->num_retries;
		if (max_tries < 1)
			max_tries = DEFAULT_ODBC_RETRIES;
	}

  top:

	if (!handle) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "No DB Handle\n");
		goto done;
	}

	if (handle->is_oracle) {
		strcpy((char *) sql, "select 1 from dual");
	} else if (handle->is_firebird) {
		strcpy((char *) sql, "select first 1 * from RDB$RELATIONS");
	} else {
		strcpy((char *) sql, "select 1");
	}

	if (SQLAllocHandle(SQL_HANDLE_STMT, handle->con, &stmt) != SQL_SUCCESS) {
		code = __LINE__;
		goto error;
	}

	SQLSetStmtAttr(stmt, SQL_ATTR_QUERY_TIMEOUT, (SQLPOINTER)30, 0);

	if (SQLPrepare(stmt, sql, SQL_NTS) != SQL_SUCCESS) {
		code = __LINE__;
		goto error;
	}

	result = SQLExecute(stmt);

	if (result != SQL_SUCCESS && result != SQL_SUCCESS_WITH_INFO) {
		code = __LINE__;
		goto error;
	}

	SQLRowCount(stmt, &m);
	rc = SQLNumResultCols(stmt, &nresultcols);
	if (rc != SQL_SUCCESS) {
		code = __LINE__;
		goto error;
	}
	ret = (int) nresultcols;
	/* determine statement type */
	if (nresultcols <= 0) {
		/* statement is not a select statement */
		code = __LINE__;
		goto error;
	}

	goto done;

  error:
	err_str = switch_odbc_handle_get_error(handle, stmt);

	/* Make sure to free the handle before we try to reconnect */
	if (stmt) {
		SQLFreeHandle(SQL_HANDLE_STMT, stmt);
		stmt = NULL;
	}

	recon = switch_odbc_handle_connect(handle);

	max_tries--;

	if (switch_event_create(&event, SWITCH_EVENT_TRAP) == SWITCH_STATUS_SUCCESS) {
		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Failure-Message", "The sql server is not responding for DSN %s [%s][%d]",
								switch_str_nil(handle->dsn), switch_str_nil(err_str), code);
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "The sql server is not responding for DSN %s [%s][%d]\n",
						  switch_str_nil(handle->dsn), switch_str_nil(err_str), code);

		if (recon == SWITCH_ODBC_SUCCESS) {
			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Additional-Info", "The connection has been re-established");
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "The connection has been re-established\n");
		} else {
			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Additional-Info", "The connection could not be re-established");
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "The connection could not be re-established\n");
		}
		if (!max_tries) {
			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Additional-Info", "Giving up!");
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Giving up!\n");
		}

		switch_event_fire(&event);
	}

	if (!max_tries) {
		goto done;
	}

	switch_safe_free(err_str);
	switch_yield(1000000);
	goto top;

  done:

	switch_safe_free(err_str);

	if (stmt) {
		SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	}

	return ret;
}
Example #20
0
SWITCH_DECLARE_CONSTRUCTOR EventConsumer::EventConsumer(const char *event_name, const char *subclass_name)
{
	switch_name_event(event_name, &e_event_id);
	switch_core_new_memory_pool(&pool);
	
	if (!zstr(subclass_name)) {
		e_subclass_name = switch_core_strdup(pool, subclass_name);
	} else {
		e_subclass_name = NULL;
	}

	switch_queue_create(&events, 5000, pool);
	
	if (switch_event_bind_removable(__FILE__, e_event_id, e_subclass_name, event_handler, this, &node) == SWITCH_STATUS_SUCCESS) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "bound to %s %s\n", event_name, switch_str_nil(e_subclass_name));
	} else {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot bind to %s %s\n", event_name, switch_str_nil(e_subclass_name));
	}

}
static JSBool curl_run(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
{
	struct curl_obj *co = JS_GetPrivate(cx, obj);
	char *method = NULL, *url, *cred = NULL;
	char *url_p = NULL, *data = NULL, *durl = NULL;
	long httpRes = 0;
	struct curl_slist *headers = NULL;
	int32 timeout = 0;
	char ct[80] = "Content-Type: application/x-www-form-urlencoded";

	if (argc < 2 || !co) {
		return JS_FALSE;
	}


	method = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
	url = JS_GetStringBytes(JS_ValueToString(cx, argv[1]));

	co->curl_handle = switch_curl_easy_init();
	if (!strncasecmp(url, "https", 5)) {
		switch_curl_easy_setopt(co->curl_handle, CURLOPT_SSL_VERIFYPEER, 0);
		switch_curl_easy_setopt(co->curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
	}


	if (argc > 2) {
		data = JS_GetStringBytes(JS_ValueToString(cx, argv[2]));
	}

	if (argc > 3) {
		co->function = JS_ValueToFunction(cx, argv[3]);
	}

	if (argc > 4) {
		JS_ValueToObject(cx, argv[4], &co->user_data);
	}

	if (argc > 5) {
		cred = JS_GetStringBytes(JS_ValueToString(cx, argv[5]));
		if (!zstr(cred)) {
			switch_curl_easy_setopt(co->curl_handle, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
			switch_curl_easy_setopt(co->curl_handle, CURLOPT_USERPWD, cred);
		}
	}

	if (argc > 6) {
		JS_ValueToInt32(cx, argv[6], &timeout);
		if (timeout > 0) {
			switch_curl_easy_setopt(co->curl_handle, CURLOPT_TIMEOUT, timeout);
		}
	}

	if (argc > 7) {
		char *content_type = JS_GetStringBytes(JS_ValueToString(cx, argv[7]));
		switch_snprintf(ct, sizeof(ct), "Content-Type: %s", content_type);
	}

	headers = curl_slist_append(headers, ct);

	switch_curl_easy_setopt(co->curl_handle, CURLOPT_HTTPHEADER, headers);

	url_p = url;

	if (!strcasecmp(method, "post")) {
		switch_curl_easy_setopt(co->curl_handle, CURLOPT_POST, 1);
		if (!data) {
			data = "";
		}
		switch_curl_easy_setopt(co->curl_handle, CURLOPT_POSTFIELDS, data);
	} else if (!zstr(data)) {
		durl = switch_mprintf("%s?%s", url, data);
		url_p = durl;
	}

	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Running: method: [%s] url: [%s] data: [%s] cred=[%s] cb: [%s]\n",
					  method, url_p, data, switch_str_nil(cred), co->function ? "yes" : "no");

	switch_curl_easy_setopt(co->curl_handle, CURLOPT_URL, url_p);
	switch_curl_easy_setopt(co->curl_handle, CURLOPT_NOSIGNAL, 1);
	switch_curl_easy_setopt(co->curl_handle, CURLOPT_WRITEFUNCTION, file_callback);
	switch_curl_easy_setopt(co->curl_handle, CURLOPT_WRITEDATA, (void *) co);

	switch_curl_easy_setopt(co->curl_handle, CURLOPT_USERAGENT, "freeswitch-spidermonkey-curl/1.0");

	co->saveDepth = JS_SuspendRequest(cx);
	switch_curl_easy_perform(co->curl_handle);

	switch_curl_easy_getinfo(co->curl_handle, CURLINFO_RESPONSE_CODE, &httpRes);
	switch_curl_easy_cleanup(co->curl_handle);
	curl_slist_free_all(headers);
	co->curl_handle = NULL;
	co->function = NULL;
	JS_ResumeRequest(cx, co->saveDepth);
	switch_safe_free(durl);


	return JS_TRUE;
}
Example #22
0
SWITCH_DECLARE(switch_pgsql_status_t) switch_pgsql_handle_callback_exec_detailed(const char *file, const char *func, int line,
        switch_pgsql_handle_t *handle,
        const char *sql, switch_core_db_callback_func_t callback, void *pdata,
        char **err)
{
#ifdef SWITCH_HAVE_PGSQL
    char *err_str = NULL;
    int row = 0, col = 0, err_cnt = 0;
    switch_pgsql_result_t *result = NULL;

    handle->affected_rows = 0;

    switch_assert(callback != NULL);

    if (switch_pgsql_handle_exec_base(handle, sql, err) == SWITCH_PGSQL_FAIL) {
        goto error;
    }

    if (switch_pgsql_next_result(handle, &result) == SWITCH_PGSQL_FAIL) {
        err_cnt++;
        err_str = switch_pgsql_handle_get_error(handle);
        if (result && !zstr(result->err)) {
            switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, NULL, SWITCH_LOG_ERROR, "ERR: [%s]\n[%s]\n", sql, switch_str_nil(result->err));
        }
        if (!zstr(err_str)) {
            switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, NULL, SWITCH_LOG_ERROR, "ERR: [%s]\n[%s]\n", sql, switch_str_nil(err_str));
        }
        switch_safe_free(err_str);
        err_str = NULL;
    }

    while (result != NULL) {
        /*switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Processing result with %d rows and %d columns.\n", result->rows, result->cols);*/
        for (row = 0; row < result->rows; ++row) {
            char **names;
            char **vals;

            names = calloc(result->cols, sizeof(*names));
            vals = calloc(result->cols, sizeof(*vals));

            switch_assert(names && vals);

            for (col = 0; col < result->cols; ++col) {
                char * tmp;
                int len;

                tmp = PQfname(result->result, col);
                if (tmp) {
                    len = strlen(tmp);
                    names[col] = malloc(len+1);
                    names[col][len] = '\0';
                    strncpy(names[col], tmp, len);

                    len = PQgetlength(result->result, row, col);
                    vals[col] = malloc(len+1);
                    vals[col][len] = '\0';
                    tmp = PQgetvalue(result->result, row, col);
                    strncpy(vals[col], tmp, len);
                    /*switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Processing result row %d, col %d: %s => %s\n", row, col, names[col], vals[col]);*/
                } else {
                    /*switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Processing result row %d, col %d.\n", row, col);*/
                    switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, NULL, SWITCH_LOG_ERROR, "ERR: Column number %d out of range\n", col);
                }
            }

            /*switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Executing callback for row %d...\n", row);*/
            if (callback(pdata, result->cols, vals, names)) {
                switch_pgsql_finish_results(handle); /* Makes sure next call to switch_pgsql_next_result will return NULL */
                row = result->rows;                  /* Makes us exit the for loop */
            }

            for (col = 0; col < result->cols; ++col) {
                free(names[col]);
                free(vals[col]);
            }
            free(names);
            free(vals);
        }
        switch_pgsql_free_result(&result);
        if (switch_pgsql_next_result(handle, &result) == SWITCH_PGSQL_FAIL) {
            err_cnt++;
            err_str = switch_pgsql_handle_get_error(handle);
            if (result && !zstr(result->err)) {
                switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, NULL, SWITCH_LOG_ERROR, "ERR: [%s]\n[%s]\n", sql, switch_str_nil(result->err));
            }
            if (!zstr(err_str)) {
                switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, NULL, SWITCH_LOG_ERROR, "ERR: [%s]\n[%s]\n", sql, switch_str_nil(err_str));
            }
            switch_safe_free(err_str);
            err_str = NULL;
        }
    }
    if (err_cnt) {
        goto error;
    }

    return SWITCH_PGSQL_SUCCESS;
error:
#endif
    return SWITCH_PGSQL_FAIL;
}
Example #23
0
static int db_is_up(switch_pgsql_handle_t *handle)
{
    int ret = 0;
    switch_event_t *event;
    char *err_str = NULL;
    int max_tries = DEFAULT_PGSQL_RETRIES;
    int code = 0, recon = 0;

    if (handle) {
        max_tries = handle->num_retries;
        if (max_tries < 1)
            max_tries = DEFAULT_PGSQL_RETRIES;
    }

top:

    if (!handle) {
        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "No DB Handle\n");
        goto done;
    }
    if (!handle->con) {
        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "No DB Connection\n");
        goto done;
    }

    /* Try a non-blocking read on the connection to gobble up any EOF from a closed connection and mark the connection BAD if it is closed. */
    PQconsumeInput(handle->con);

    if (PQstatus(handle->con) == CONNECTION_BAD) {
        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "PQstatus returned bad connection; reconnecting...\n");
        handle->state = SWITCH_PGSQL_STATE_ERROR;
        PQreset(handle->con);
        if (PQstatus(handle->con) == CONNECTION_BAD) {
            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "PQstatus returned bad connection -- reconnection failed!\n");
            goto error;
        }
        handle->state = SWITCH_PGSQL_STATE_CONNECTED;
        handle->sock = PQsocket(handle->con);
    }

    /*	if (!PQsendQuery(handle->con, "SELECT 1")) {
    		code = __LINE__;
    		goto error;
    	}

    	if(switch_pgsql_next_result(handle, &result) == SWITCH_PGSQL_FAIL) {
    		code = __LINE__;
    		goto error;
    	}

    	if (!result || result->status != PGRES_COMMAND_OK) {
    		code = __LINE__;
    		goto error;
    	}

    	switch_pgsql_free_result(&result);
    	switch_pgsql_finish_results(handle);
    */
    ret = 1;
    goto done;

error:
    err_str = switch_pgsql_handle_get_error(handle);

    if (PQstatus(handle->con) == CONNECTION_BAD) {
        handle->state = SWITCH_PGSQL_STATE_ERROR;
        PQreset(handle->con);
        if (PQstatus(handle->con) == CONNECTION_OK) {
            handle->state = SWITCH_PGSQL_STATE_CONNECTED;
            recon = SWITCH_PGSQL_SUCCESS;
            handle->sock = PQsocket(handle->con);
        }
    }

    max_tries--;

    if (switch_event_create(&event, SWITCH_EVENT_TRAP) == SWITCH_STATUS_SUCCESS) {
        switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Failure-Message", "The sql server is not responding for DSN %s [%s][%d]",
                                switch_str_nil(handle->dsn), switch_str_nil(err_str), code);
        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "The sql server is not responding for DSN %s [%s][%d]\n",
                          switch_str_nil(handle->dsn), switch_str_nil(err_str), code);

        if (recon == SWITCH_PGSQL_SUCCESS) {
            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Additional-Info", "The connection has been re-established");
            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "The connection has been re-established\n");
        } else {
            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Additional-Info", "The connection could not be re-established");
            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "The connection could not be re-established\n");
        }
        if (!max_tries) {
            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Additional-Info", "Giving up!");
            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Giving up!\n");
        }

        switch_event_fire(&event);
    }

    if (!max_tries) {
        goto done;
    }

    switch_safe_free(err_str);
    switch_yield(1000000);
    goto top;

done:

    switch_safe_free(err_str);

    return ret;
}
Example #24
0
SWITCH_DECLARE(switch_odbc_status_t) switch_odbc_handle_callback_exec_detailed(const char *file, const char *func, int line,
																			   switch_odbc_handle_t *handle,
																			   const char *sql, switch_core_db_callback_func_t callback, void *pdata,
																			   char **err)
{
#ifdef SWITCH_HAVE_ODBC
	SQLHSTMT stmt = NULL;
	SQLSMALLINT c = 0, x = 0;
	SQLLEN m = 0;
	char *x_err = NULL, *err_str = NULL;
	int result;
	int err_cnt = 0;
	int done = 0;

	handle->affected_rows = 0;

	switch_assert(callback != NULL);

	if (!db_is_up(handle)) {
		x_err = "DB is not up!";
		goto error;
	}

	if (SQLAllocHandle(SQL_HANDLE_STMT, handle->con, &stmt) != SQL_SUCCESS) {
		x_err = "Unable to SQL allocate handle!";
		goto error;
	}

	if (SQLPrepare(stmt, (unsigned char *) sql, SQL_NTS) != SQL_SUCCESS) {
		x_err = "Unable to prepare SQL statement!";
		goto error;
	}

	result = SQLExecute(stmt);

	if (result != SQL_SUCCESS && result != SQL_SUCCESS_WITH_INFO && result != SQL_NO_DATA) {
		x_err = "execute error!";
		goto error;
	}

	SQLNumResultCols(stmt, &c);
	SQLRowCount(stmt, &m);
	handle->affected_rows = (int) m;


	while (!done) {
		int name_len = 256;
		char **names;
		char **vals;
		int y = 0;

		result = SQLFetch(stmt);

		if (result != SQL_SUCCESS) {
			if (result != SQL_NO_DATA) {
				err_cnt++;
			}
			break;
		}

		names = calloc(c, sizeof(*names));
		vals = calloc(c, sizeof(*vals));

		switch_assert(names && vals);

		for (x = 1; x <= c; x++) {
			SQLSMALLINT NameLength = 0, DataType = 0, DecimalDigits = 0, Nullable = 0;
			SQLULEN ColumnSize = 0;
			names[y] = malloc(name_len);
			memset(names[y], 0, name_len);

			SQLDescribeCol(stmt, x, (SQLCHAR *) names[y], (SQLSMALLINT) name_len, &NameLength, &DataType, &ColumnSize, &DecimalDigits, &Nullable);

			if (!ColumnSize) {
				ColumnSize = 255;
			}
			ColumnSize++;

			vals[y] = malloc(ColumnSize);
			memset(vals[y], 0, ColumnSize);
			SQLGetData(stmt, x, SQL_C_CHAR, (SQLCHAR *) vals[y], ColumnSize, NULL);
			y++;
		}

		if (callback(pdata, y, vals, names)) {
			done = 1;
		}

		for (x = 0; x < y; x++) {
			free(names[x]);
			free(vals[x]);
		}
		free(names);
		free(vals);
	}

	SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	stmt = NULL; /* Make sure we don't try to free this handle again */
	
	if (!err_cnt) {
		return SWITCH_ODBC_SUCCESS;
	}

  error:

	if (stmt) {
		err_str = switch_odbc_handle_get_error(handle, stmt);
	}

	if (zstr(err_str) && !zstr(x_err)) {
		err_str = strdup(x_err);
	}

	if (err_str) {
		switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, NULL, SWITCH_LOG_ERROR, "ERR: [%s]\n[%s]\n", sql, switch_str_nil(err_str));
		if (err) {
			*err = err_str;
		} else {
			free(err_str);
		}
	}

	if (stmt) {
		SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	}


#endif
	return SWITCH_ODBC_FAIL;
}
Example #25
0
void vmivr_menu_navigator(switch_core_session_t *session, vmivr_profile_t *profile) {
	switch_channel_t *channel = switch_core_session_get_channel(session);
	switch_event_t *msg_list_params = NULL;
	size_t msg_count = 0;
	size_t current_msg = 1;
	size_t next_msg = current_msg;
	size_t previous_msg = current_msg;
	char *cmd = NULL;
	int retry;

	/* Different switch to control playback of phrases */
	switch_bool_t initial_count_played = SWITCH_FALSE;
	switch_bool_t skip_header = SWITCH_FALSE;
	switch_bool_t skip_playback = SWITCH_FALSE;
	switch_bool_t msg_deleted = SWITCH_FALSE;
	switch_bool_t msg_undeleted = SWITCH_FALSE;
	switch_bool_t msg_saved = SWITCH_FALSE;

	vmivr_menu_t menu = { "std_navigator" };

	/* Initialize Menu Configs */
	menu_init(profile, &menu);

	if (!menu.event_keys_dtmf || !menu.event_phrases) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Missing Menu Phrases or Keys in menu '%s'\n", menu.name);
		goto done;
	}

	/* Get VoiceMail List And update msg count */
	cmd = switch_core_session_sprintf(session, "json %s %s %s %s %s", profile->api_profile, profile->domain, profile->id, profile->folder_name, profile->folder_filter);
	msg_list_params = jsonapi2event(session, profile->api_msg_list, cmd);
	if (msg_list_params) {
		msg_count = atol(switch_event_get_header(msg_list_params,"VM-List-Count"));
		if (msg_count == 0) {
			goto done;
		}
	} else {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "API message list return invalid result : %s(%s)\n", profile->api_msg_list, cmd); 
		goto done;
	}


	/* TODO Add Detection of new message and notify the user */

	for (retry = menu.ivr_maximum_attempts; switch_channel_ready(channel) && retry > 0; retry--) {
		switch_core_session_message_t msg = { 0 };
		char cid_buf[1024] = "";

		menu_instance_init(&menu);

		switch_event_add_header(menu.phrase_params, SWITCH_STACK_BOTTOM, "IVR-Retry-Left", "%d", retry);

		previous_msg = current_msg;

		ivre_init(&menu.ivre_d, menu.dtmfa);

		/* Prompt related to previous Message here */
		append_event_message(session, profile, menu.phrase_params, msg_list_params, previous_msg);
		if (msg_deleted) {
			msg_deleted = SWITCH_FALSE;
			ivre_playback(session, &menu.ivre_d, switch_event_get_header(menu.event_phrases, "ack"), "deleted", menu.phrase_params, NULL, 0);
		}
		if (msg_undeleted) {
			msg_undeleted = SWITCH_FALSE;
			ivre_playback(session, &menu.ivre_d, switch_event_get_header(menu.event_phrases, "ack"), "undeleted", menu.phrase_params, NULL, 0);
		} 
		if (msg_saved) {
			msg_saved = SWITCH_FALSE;
			ivre_playback(session, &menu.ivre_d, switch_event_get_header(menu.event_phrases, "ack"), "saved", menu.phrase_params, NULL, 0);
		}
		switch_event_del_header(menu.phrase_params, "VM-Message-Flags");

		/* Simple Protection to not go out of msg list scope */
		if (next_msg == 0) {
			next_msg = 1;
		} else if (next_msg > msg_count) {
			next_msg = msg_count;
			ivre_playback_dtmf_buffered(session, switch_event_get_header(menu.event_phrases, "no_more_messages"), NULL, NULL, NULL, 0);
		}

		current_msg = next_msg;

		/* Prompt related the current message */
		append_event_message(session, profile, menu.phrase_params, msg_list_params, current_msg);

		/* Used for extra control in phrases */
		switch_event_add_header(menu.phrase_params, SWITCH_STACK_BOTTOM, "VM-List-Count", "%"SWITCH_SIZE_T_FMT, msg_count);

		/* Display MSG CID/Name to caller */
		switch_snprintf(cid_buf, sizeof(cid_buf), "%s|%s", switch_str_nil(switch_event_get_header(menu.phrase_params, "VM-Message-Caller-Number")), switch_str_nil(switch_event_get_header(menu.phrase_params, "VM-Message-Caller-Name")));

		msg.from = __FILE__;
		msg.string_arg = cid_buf;
		msg.message_id = SWITCH_MESSAGE_INDICATE_DISPLAY;
		switch_core_session_receive_message(session, &msg);

		/* Save in profile the current msg info for other menu processing AND restoration of our current position */
		profile->current_msg = current_msg;
		profile->current_msg_uuid = switch_core_session_strdup(session, switch_event_get_header(menu.phrase_params, "VM-Message-UUID"));

		/* TODO check if msg is gone (purged by another session, notify user and auto jump to next message or something) */
		if (!skip_header) {
			if (!initial_count_played) {
				cmd = switch_core_session_sprintf(session, "json %s %s %s", profile->api_profile, profile->domain, profile->id);
				jsonapi_populate_event(session, menu.phrase_params, profile->api_msg_count, cmd);
				initial_count_played = SWITCH_TRUE;
				// TODO ivre_playback(session, &menu.ivre_d, switch_event_get_header(menu.event_phrases, "msg_count"), NULL, menu.phrase_params, NULL, 0);
			}
			if (msg_count > 0) {
				ivre_playback(session, &menu.ivre_d, switch_event_get_header(menu.event_phrases, "say_msg_number"), NULL, menu.phrase_params, NULL, 0);
				ivre_playback(session, &menu.ivre_d, switch_event_get_header(menu.event_phrases, "say_date"), NULL, menu.phrase_params, NULL, 0);
			}
		}
		if (msg_count > 0 && !skip_playback) {
			/* TODO Update the Read date of a message (When msg start, or when it listen compleatly ??? To be determined */
			ivre_playback(session, &menu.ivre_d, switch_event_get_header(menu.event_phrases, "play_message"), NULL, menu.phrase_params, NULL, 0);
		}
		skip_header = SWITCH_FALSE;
		skip_playback = SWITCH_FALSE;

		ivre_playback(session, &menu.ivre_d, switch_event_get_header(menu.event_phrases, "menu_options"), NULL, menu.phrase_params, NULL, menu.ivr_entry_timeout);

		if (menu.ivre_d.result == RES_TIMEOUT) {
			ivre_playback_dtmf_buffered(session, switch_event_get_header(menu.event_phrases, "timeout"), NULL, NULL, NULL, 0);
		} else if (menu.ivre_d.result == RES_INVALID) {
			ivre_playback_dtmf_buffered(session, switch_event_get_header(menu.event_phrases, "invalid"), NULL, NULL, NULL, 0);
		} else if (menu.ivre_d.result == RES_FOUND) {  /* Matching DTMF Key Pressed */
			const char *action = switch_event_get_header(menu.event_keys_dtmf, menu.ivre_d.dtmf_stored);

			/* Reset the try count */
			retry = menu.ivr_maximum_attempts;
action:
			if (action) {
				if (!strcasecmp(action, "skip_intro")) { /* Skip Header / Play the recording again */
					skip_header = SWITCH_TRUE;
				} else if (!strcasecmp(action, "next_msg")) { /* Next Message */
					next_msg++;
				} else if (!strcasecmp(action, "prev_msg")) { /* Previous Message */
					next_msg--;
				} else if (!strcasecmp(action, "delete_msg")) { /* Delete / Undelete Message */
					const char *msg_flags = switch_event_get_header(menu.phrase_params, "VM-Message-Flags");
					if (!msg_flags || strncasecmp(msg_flags, "delete", 6)) {
						const char *action_on_delete = switch_event_get_header(menu.event_settings, "Nav-Action-On-Delete");
						cmd = switch_core_session_sprintf(session, "%s %s %s %s", profile->api_profile, profile->domain, profile->id, switch_event_get_header(menu.phrase_params, "VM-Message-UUID"));
						vmivr_api_execute(session, profile->api_msg_delete, cmd);

						msg_deleted = SWITCH_TRUE;
						
						if (action_on_delete) {
							action = action_on_delete;
							goto action;	
						} else {
							skip_header = skip_playback = SWITCH_TRUE;
						}
					} else { 
						cmd = switch_core_session_sprintf(session, "%s %s %s %s", profile->api_profile, profile->domain, profile->id, switch_event_get_header(menu.phrase_params, "VM-Message-UUID"));
						vmivr_api_execute(session, profile->api_msg_undelete, cmd);

						msg_undeleted = SWITCH_TRUE;
					}
				} else if (!strcasecmp(action, "save_msg")) { /* Save Message */
					cmd = switch_core_session_sprintf(session, "%s %s %s %s", profile->api_profile, profile->domain, profile->id, switch_event_get_header(menu.phrase_params, "VM-Message-UUID"));
					vmivr_api_execute(session, profile->api_msg_save, cmd);

					msg_saved = SWITCH_TRUE;
				} else if (!strcasecmp(action, "callback")) { /* CallBack caller */
					const char *cid_num = switch_event_get_header(menu.phrase_params, "VM-Message-Caller-Number");
					if (cid_num) {
						/* TODO add detection for private number */
						switch_core_session_execute_exten(session, cid_num, "XML", profile->domain);
					} else {
						/* TODO Some error msg that the msg doesn't contain a caller number */
					}
				} else if (!strncasecmp(action, "menu:", 5)) { /* Sub Menu */
					void (*fPtr)(switch_core_session_t *session, vmivr_profile_t *profile) = vmivr_get_menu_function(action+5);
					if (fPtr) {
						fPtr(session, profile);
					}
				} else if (!strcasecmp(action, "return")) { /* Return */
					retry = -1;
				}
			}
		}

		/* IF the API to get the message returned us a COPY of the file menu.ivre_dally (temp file create from a DB or from a web server), delete it */
		if (switch_true(switch_event_get_header(menu.phrase_params, "VM-Message-Private-Local-Copy"))) {
			const char *file_path = switch_event_get_header(menu.phrase_params, "VM-Message-File-Path");
			if (file_path && unlink(file_path) != 0) {
				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Failed to delete temp file [%s]\n", file_path);
			}
		}
		menu_instance_free(&menu);
	}
done:
	switch_event_destroy(&msg_list_params);

	menu_free(&menu);

	return;
}
Example #26
0
static switch_xml_t xml_url_fetch(const char *section, const char *tag_name, const char *key_name, const char *key_value, switch_event_t *params,
								  void *user_data)
{
	switch_xml_t xml = NULL;
	char *data = NULL;
	xml_binding_t *binding = (xml_binding_t *) user_data;
	char hostname[256] = "";
	char basic_data[512];
	unsigned char buf[16336] = "";
	ssize_t len = -1, bytes = 0;
	scgi_handle_t handle = { 0 };
	switch_stream_handle_t stream = { 0 };
	char *txt = NULL;

	strncpy(hostname, switch_core_get_switchname(), sizeof(hostname));

	if (!binding) {
		return NULL;
	}

	switch_snprintf(basic_data, sizeof(basic_data), "hostname=%s&section=%s&tag_name=%s&key_name=%s&key_value=%s",
					hostname, section, switch_str_nil(tag_name), switch_str_nil(key_name), switch_str_nil(key_value));

	data = switch_event_build_param_string(params, basic_data, binding->vars_map);
	switch_assert(data);

	scgi_add_param(&handle, "REQUEST_METHOD", "POST");
	scgi_add_param(&handle, "SERVER_PROTOCOL", "HTTP/1.0");
	scgi_add_param(&handle, "REQUEST_URI", binding->uri);
	scgi_add_body(&handle, data);

	if (scgi_connect(&handle, binding->host, binding->port, binding->timeout * 1000) == SCGI_SUCCESS) {
		scgi_send_request(&handle);

		SWITCH_STANDARD_STREAM(stream);
		txt = (char *) stream.data;

		while((len = scgi_recv(&handle, buf, sizeof(buf))) > 0) {
			char *expanded = switch_event_expand_headers(params, (char *)buf);
			
			bytes += len;

			if (bytes > XML_SCGI_MAX_BYTES) {
				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Data too big!\n");
				len = -1;
				break;
			}

			stream.write_function(&stream, "%s", expanded);
			txt = (char *) stream.data;

			if (expanded != (char *)buf) {
				free(expanded);
			}
			
			memset(buf, 0, sizeof(buf));
		}

		scgi_disconnect(&handle);

		if (len < 0 && (!txt || !strlen(txt))) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "DEBUG:\nURL: %s Connection Read Failed: [%s]\n", binding->url, handle.err);
			goto end;
		}

	} else {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "DEBUG:\nURL: %s Connection Failed: [%s]\n", binding->url, handle.err);
		goto end;
	}

	

	if (GLOBAL_DEBUG) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "DEBUG:\nURL: %s\nPOST_DATA:\n%s\n\nRESPONSE:\n-----\n%s\n-----\n", 
						  binding->url, data, switch_str_nil(txt));
	}

	

	if (bytes && txt) {
		if (!(xml = switch_xml_parse_str_dynamic(txt, FALSE))) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Parsing Result! [%s]\ndata: [%s] RESPONSE[%s]\n", 
							  binding->url, data, switch_str_nil(txt));
		}
		txt = NULL;
	} else {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Received error trying to fetch %s\ndata: [%s] RESPONSE [%s]\n", 
						  binding->url, data, switch_str_nil(txt));
	}


 end:
	
	switch_safe_free(data);
	switch_safe_free(txt);
	
	return xml;
}
WSChannel* WSClientParser::CreateCall(
		switch_core_session_t *session,
		const char *profileName,
		const char *profileContext,
		const char *profileDialplan,
		const char* ip
		) {
	WSChannel *wsChannel = NULL;

	switch_memory_pool_t *pool = NULL;
	switch_channel_t* channel = NULL;
	switch_caller_profile_t *caller_profile = NULL;

	char *user = mpUser;
	char *domain = mpDomain;
	const char *destNumber = mpDestNumber;
	const char *context = NULL;
	const char *dialplan = NULL;
	switch_status_t status = SWITCH_STATUS_SUCCESS;

	switch_log_printf(
			SWITCH_CHANNEL_UUID_LOG(this->GetUUID()),
			SWITCH_LOG_INFO,
			"WSClientParser::CreateCall( "
			"this : %p, "
			"profileName : '%s', "
			"profileContext : '%s', "
			"profileDialplan : '%s', "
			"ip : '%s' "
			") \n",
			this,
			profileName,
			profileContext,
			profileDialplan,
			ip
			);

	// 参数不能为空
	if ( !user || !domain || !destNumber ) {
		status = SWITCH_STATUS_FALSE;
	}

	// 不允许一个连接创建多个会话
	if( status == SWITCH_STATUS_SUCCESS && mpChannel ) {
		status = SWITCH_STATUS_FALSE;
	}

	if( status == SWITCH_STATUS_SUCCESS ) {
		pool = switch_core_session_get_pool(session);
		channel = switch_core_session_get_channel(session);
		switch_channel_set_name(
				channel,
				switch_core_session_sprintf(session, "ws/%s/%s/%s", profileName, user, destNumber)
				);
	}

//	if ( status == SWITCH_STATUS_SUCCESS && !zstr(user) && !zstr(domain)) {
//		// 拨号不做验证
//		const char *ivrUser = switch_core_session_sprintf(session, "%s@%s", user, domain);
//		status = switch_ivr_set_user(session, ivrUser);
//	}

	if( status == SWITCH_STATUS_SUCCESS ) {
		if (!(context = switch_channel_get_variable(channel, "user_context"))) {
			if (!(context = profileContext)) {
				context = "public";
			}
		}

		if (!(dialplan = switch_channel_get_variable(channel, "inbound_dialplan"))) {
			if (!(dialplan = profileDialplan)) {
				dialplan = "LUA";
			}
		}

		//	switch_log_printf(
		//			SWITCH_CHANNEL_SESSION_LOG(session),
		//			SWITCH_LOG_NOTICE,
		//			"WSClientParser::CreateCall( "
		//			"context : %s, "
		//			"dialplan : %s "
		//			") \n",
		//			context,
		//			dialplan
		//			);

		// 设置主叫
		caller_profile = switch_caller_profile_new(
				pool,
				switch_str_nil(user),
				dialplan,
				SWITCH_DEFAULT_CLID_NAME,
				!zstr(user) ? user : SWITCH_DEFAULT_CLID_NUMBER,
				ip /* net addr */,
				NULL /* ani   */,
				NULL /* anii  */,
				NULL /* rdnis */,
				"mod_ws",
				context,
				destNumber
				);
		switch_channel_set_caller_profile(channel, caller_profile);
		switch_core_session_add_stream(session, NULL);
		switch_channel_set_variable(channel, "caller", user);
		switch_channel_set_state(channel, CS_INIT);

		wsChannel = CreateChannel(session);
	}

	if( wsChannel ) {
		switch_log_printf(
				SWITCH_CHANNEL_UUID_LOG(this->GetUUID()),
				SWITCH_LOG_INFO,
				"WSClientParser::CreateCall( "
				"[Success], "
				"this : %p, "
				"wsChannel : %p, "
				"profileName : '%s', "
				"profileContext : '%s', "
				"profileDialplan : '%s', "
				"ip : '%s' "
				") \n",
				this,
				wsChannel,
				profileName,
				profileContext,
				profileDialplan,
				ip
				);
	} else {
		switch_log_printf(
				SWITCH_CHANNEL_UUID_LOG(this->GetUUID()),
				SWITCH_LOG_ERROR,
				"WSClientParser::CreateCall( "
				"[Fail], "
				"this : %p "
				") \n",
				this,
				profileName,
				profileContext,
				profileDialplan,
				ip
				);
	}

	return wsChannel;
}
static switch_xml_t xml_url_fetch(const char *section, const char *tag_name, const char *key_name, const char *key_value, switch_event_t *params,
								  void *user_data)
{
	char filename[512] = "";
	CURL *curl_handle = NULL;
	struct config_data config_data;
	switch_xml_t xml = NULL;
	char *data = NULL;
	switch_uuid_t uuid;
	char uuid_str[SWITCH_UUID_FORMATTED_LENGTH + 1];
	xml_binding_t *binding = (xml_binding_t *) user_data;
	char *file_url;
	struct curl_slist *slist = NULL;
	long httpRes = 0;
	struct curl_slist *headers = NULL;
	char hostname[256] = "";
	char basic_data[512];
	char *uri = NULL;
	char *dynamic_url = NULL;

    strncpy(hostname, switch_core_get_switchname(), sizeof(hostname));

	if (!binding) {
		return NULL;
	}

	if ((file_url = strstr(binding->url, "file:"))) {
		file_url += 5;

		if (!(xml = switch_xml_parse_file(file_url))) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Parsing Result!\n");
		}

		return xml;
	}

	switch_snprintf(basic_data, sizeof(basic_data), "hostname=%s&section=%s&tag_name=%s&key_name=%s&key_value=%s",
					hostname, section, switch_str_nil(tag_name), switch_str_nil(key_name), switch_str_nil(key_value));

	data = switch_event_build_param_string(params, basic_data, binding->vars_map);
	switch_assert(data);

	if (binding->use_dynamic_url) {
		if (!params) {
			switch_event_create(&params, SWITCH_EVENT_REQUEST_PARAMS);
			switch_assert(params);
		}

		switch_event_add_header_string(params, SWITCH_STACK_TOP, "hostname", hostname);
		switch_event_add_header_string(params, SWITCH_STACK_TOP, "section", switch_str_nil(section));
		switch_event_add_header_string(params, SWITCH_STACK_TOP, "tag_name", switch_str_nil(tag_name));
		switch_event_add_header_string(params, SWITCH_STACK_TOP, "key_name", switch_str_nil(key_name));
		switch_event_add_header_string(params, SWITCH_STACK_TOP, "key_value", switch_str_nil(key_value));
		dynamic_url = switch_event_expand_headers(params, binding->url);
		switch_assert(dynamic_url);
	} else {
		dynamic_url = binding->url;
	}

	if (binding->use_get_style == 1) {
		uri = malloc(strlen(data) + strlen(dynamic_url) + 16);
		switch_assert(uri);
		sprintf(uri, "%s%c%s", dynamic_url, strchr(dynamic_url, '?') != NULL ? '&' : '?', data);
	}

	switch_uuid_get(&uuid);
	switch_uuid_format(uuid_str, &uuid);

	switch_snprintf(filename, sizeof(filename), "%s%s.tmp.xml", SWITCH_GLOBAL_dirs.temp_dir, uuid_str);
	curl_handle = curl_easy_init();
	headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");

	if (!strncasecmp(binding->url, "https", 5)) {
		curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, 0);
		curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
	}

	memset(&config_data, 0, sizeof(config_data));

	config_data.name = filename;
	config_data.max_bytes = XML_CURL_MAX_BYTES;

	if ((config_data.fd = open(filename, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)) > -1) {
		if (!zstr(binding->cred)) {
			curl_easy_setopt(curl_handle, CURLOPT_HTTPAUTH, binding->auth_scheme);
			curl_easy_setopt(curl_handle, CURLOPT_USERPWD, binding->cred);
		}
		curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, headers);
		if (binding->method != NULL)
			curl_easy_setopt(curl_handle, CURLOPT_CUSTOMREQUEST, binding->method);
		curl_easy_setopt(curl_handle, CURLOPT_POST, !binding->use_get_style);
		curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1);
		curl_easy_setopt(curl_handle, CURLOPT_MAXREDIRS, 10);
		if (!binding->use_get_style)
			curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, data);
		curl_easy_setopt(curl_handle, CURLOPT_URL, binding->use_get_style ? uri : dynamic_url);
		curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, file_callback);
		curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *) &config_data);
		curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "freeswitch-xml/1.0");

		if (binding->timeout) {
			curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, binding->timeout);
			curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1);
		}

		if (binding->disable100continue) {
			slist = curl_slist_append(slist, "Expect:");
			curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, slist);
		}

		if (binding->enable_cacert_check) {
			curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, TRUE);
		}

		if (binding->ssl_cert_file) {
			curl_easy_setopt(curl_handle, CURLOPT_SSLCERT, binding->ssl_cert_file);
		}

		if (binding->ssl_key_file) {
			curl_easy_setopt(curl_handle, CURLOPT_SSLKEY, binding->ssl_key_file);
		}

		if (binding->ssl_key_password) {
			curl_easy_setopt(curl_handle, CURLOPT_SSLKEYPASSWD, binding->ssl_key_password);
		}

		if (binding->ssl_version) {
			if (!strcasecmp(binding->ssl_version, "SSLv3")) {
				curl_easy_setopt(curl_handle, CURLOPT_SSLVERSION, CURL_SSLVERSION_SSLv3);
			} else if (!strcasecmp(binding->ssl_version, "TLSv1")) {
				curl_easy_setopt(curl_handle, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
			}
		}

		if (binding->ssl_cacert_file) {
			curl_easy_setopt(curl_handle, CURLOPT_CAINFO, binding->ssl_cacert_file);
		}

		if (binding->enable_ssl_verifyhost) {
			curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 2);
		}

		if (binding->cookie_file) {
			curl_easy_setopt(curl_handle, CURLOPT_COOKIEJAR, binding->cookie_file);
			curl_easy_setopt(curl_handle, CURLOPT_COOKIEFILE, binding->cookie_file);
		}

		curl_easy_perform(curl_handle);
		curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &httpRes);
		curl_easy_cleanup(curl_handle);
		curl_slist_free_all(headers);
		curl_slist_free_all(slist);
		close(config_data.fd);
	} else {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening temp file!\n");
	}

	if (config_data.err) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error encountered! [%s]\ndata: [%s]\n", binding->url, data);
		xml = NULL;
	} else {
		if (httpRes == 200) {
			if (!(xml = switch_xml_parse_file(filename))) {
				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Parsing Result! [%s]\ndata: [%s]\n", binding->url, data);
			}
		} else {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Received HTTP error %ld trying to fetch %s\ndata: [%s]\n", httpRes, binding->url,
							  data);
			xml = NULL;
		}
	}

	/* Debug by leaving the file behind for review */
	if (keep_files_around) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "XML response is in %s\n", filename);
	} else {
		if (unlink(filename) != 0) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "XML response file [%s] delete failed\n", filename);
		}
	}

	switch_safe_free(data);
	if (binding->use_get_style == 1)
		switch_safe_free(uri);
	if (binding->use_dynamic_url && dynamic_url != binding->url)
		switch_safe_free(dynamic_url);
	return xml;
}
Example #29
0
static int task_thread_loop(int done)
{
	switch_scheduler_task_container_t *tofree, *tp, *last = NULL;


	switch_mutex_lock(globals.task_mutex);

	for (tp = globals.task_list; tp; tp = tp->next) {
		if (done) {
			tp->destroyed = 1;
		} else if (!tp->destroyed) {
			int64_t now = switch_epoch_time_now(NULL);
			if (now >= tp->task.runtime && !tp->in_thread) {
				int32_t diff = (int32_t) (now - tp->task.runtime);
				if (diff > 1) {
					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Task was executed late by %d seconds %u %s (%s)\n",
									  diff, tp->task.task_id, tp->desc, switch_str_nil(tp->task.group));
				}
				tp->executed = now;
				if (switch_test_flag(tp, SSHF_OWN_THREAD)) {
					switch_thread_t *thread;
					switch_threadattr_t *thd_attr;
					switch_core_new_memory_pool(&tp->pool);
					switch_threadattr_create(&thd_attr, tp->pool);
					switch_threadattr_detach_set(thd_attr, 1);
					tp->in_thread = 1;
					switch_thread_create(&thread, thd_attr, task_own_thread, tp, tp->pool);
				} else {
					tp->running = 1;
					switch_mutex_unlock(globals.task_mutex);
					switch_scheduler_execute(tp);
					switch_mutex_lock(globals.task_mutex);
					tp->running = 0;
				}
			}
		}
	}
	switch_mutex_unlock(globals.task_mutex);
	switch_mutex_lock(globals.task_mutex);
	for (tp = globals.task_list; tp;) {
		if (tp->destroyed && !tp->in_thread) {
			switch_event_t *event;

			tofree = tp;
			tp = tp->next;
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Deleting task %u %s (%s)\n",
							  tofree->task.task_id, tofree->desc, switch_str_nil(tofree->task.group));


			if (switch_event_create(&event, SWITCH_EVENT_DEL_SCHEDULE) == SWITCH_STATUS_SUCCESS) {
				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Task-ID", "%u", tofree->task.task_id);
				switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Task-Desc", tofree->desc);
				switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Task-Group", switch_str_nil(tofree->task.group));
				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Task-Runtime", "%" SWITCH_INT64_T_FMT, tofree->task.runtime);
				switch_queue_push(globals.event_queue, event);
				event = NULL;
			}

			if (last) {
				last->next = tofree->next;
			} else {
				globals.task_list = tofree->next;
			}
			switch_safe_free(tofree->task.group);
			if (tofree->task.cmd_arg && switch_test_flag(tofree, SSHF_FREE_ARG)) {
				free(tofree->task.cmd_arg);
			}
			switch_safe_free(tofree->desc);
			free(tofree);
		} else {
			last = tp;
			tp = tp->next;
		}
	}
	switch_mutex_unlock(globals.task_mutex);

	return done;
}
Example #30
0
SWITCH_DECLARE(switch_odbc_status_t) switch_odbc_handle_exec(switch_odbc_handle_t *handle, const char *sql, switch_odbc_statement_handle_t *rstmt,
															 char **err)
{
#ifdef SWITCH_HAVE_ODBC
	SQLHSTMT stmt = NULL;
	int result;
	char *err_str = NULL, *err2 = NULL;
	SQLLEN m = 0;

	handle->affected_rows = 0;

	if (!db_is_up(handle)) {
		goto error;
	}

	if (SQLAllocHandle(SQL_HANDLE_STMT, handle->con, &stmt) != SQL_SUCCESS) {
		err2 = "SQLAllocHandle failed.";
		goto error;
	}

	if (SQLPrepare(stmt, (unsigned char *) sql, SQL_NTS) != SQL_SUCCESS) {
		err2 = "SQLPrepare failed.";
		goto error;
	}

	result = SQLExecute(stmt);

	switch (result) {
	case SQL_SUCCESS:
	case SQL_SUCCESS_WITH_INFO:
	case SQL_NO_DATA:
		break;
	case SQL_ERROR:
		err2 = "SQLExecute returned SQL_ERROR.";
		goto error;
		break;
	case SQL_NEED_DATA:
		err2 = "SQLExecute returned SQL_NEED_DATA.";
		goto error;
		break;
	default:
		err2 = "SQLExecute returned unknown result code.";
		goto error;
	}

	SQLRowCount(stmt, &m);
	handle->affected_rows = (int) m;

	if (rstmt) {
		*rstmt = stmt;
	} else {
		SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	}

	return SWITCH_ODBC_SUCCESS;

  error:


	if (stmt) {
		err_str = switch_odbc_handle_get_error(handle, stmt);
	}

	if (zstr(err_str)) {
		if (err2) {
			err_str = strdup(err2);
		} else {
			err_str = strdup((char *)"SQL ERROR!");
		}
	}
	
	if (err_str) {
		if (!switch_stristr("already exists", err_str) && !switch_stristr("duplicate key name", err_str)) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "ERR: [%s]\n[%s]\n", sql, switch_str_nil(err_str));
		}
		if (err) {
			*err = err_str;
		} else {
			free(err_str);
		}
	}

	if (rstmt) {
		*rstmt = stmt;
	} else if (stmt) {
		SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	}
#endif
	return SWITCH_ODBC_FAIL;
}