target
int64
0
1
func
stringlengths
7
484k
func_no_comments
stringlengths
7
484k
idx
int64
1
368k
0
TABLE_LIST* first_not_own_table() { return ( query_tables_own_last ? *query_tables_own_last : 0); }
TABLE_LIST* first_not_own_table() { return ( query_tables_own_last ? *query_tables_own_last : 0); }
367,366
0
bool add_key(Key::Keytype key_type, const LEX_CSTRING *key_name, ha_key_alg algorithm, DDL_options_st ddl) { if (check_add_key(ddl) || !(last_key= new Key(key_type, key_name, algorithm, false, ddl))) return true; alter_info.key_list.push_back(last_key); return false; }
bool add_key(Key::Keytype key_type, const LEX_CSTRING *key_name, ha_key_alg algorithm, DDL_options_st ddl) { if (check_add_key(ddl) || !(last_key= new Key(key_type, key_name, algorithm, false, ddl))) return true; alter_info.key_list.push_back(last_key); return false; }
367,367
0
bool LEX::sp_body_finalize_routine(THD *thd) { if (sphead->check_unresolved_goto()) return true; sphead->set_stmt_end(thd); sphead->restore_thd_mem_root(thd); return false; }
bool LEX::sp_body_finalize_routine(THD *thd) { if (sphead->check_unresolved_goto()) return true; sphead->set_stmt_end(thd); sphead->restore_thd_mem_root(thd); return false; }
367,368
0
void set_agg_func_used(bool val) { m_agg_func_used= val; }
void set_agg_func_used(bool val) { m_agg_func_used= val; }
367,370
0
void set_8bit(bool is_8bit) { m_is_8bit= is_8bit; }
void set_8bit(bool is_8bit) { m_is_8bit= is_8bit; }
367,371
0
sp_variable *LEX::sp_add_for_loop_variable(THD *thd, const LEX_CSTRING *name, Item *value) { sp_variable *spvar= spcont->add_variable(thd, name); spcont->declare_var_boundary(1); spvar->field_def.field_name= spvar->name; spvar->field_def.set_handler(&type_handler_longlong); type_handler_longlong.Column_definition_prepare_stage2(&spvar->field_def, NULL, HA_CAN_GEOMETRY); if (!value && unlikely(!(value= new (thd->mem_root) Item_null(thd)))) return NULL; spvar->default_value= value; sp_instr_set *is= new (this->thd->mem_root) sp_instr_set(sphead->instructions(), spcont, &sp_rcontext_handler_local, spvar->offset, value, this, true); if (unlikely(is == NULL || sphead->add_instr(is))) return NULL; spcont->declare_var_boundary(0); return spvar; }
sp_variable *LEX::sp_add_for_loop_variable(THD *thd, const LEX_CSTRING *name, Item *value) { sp_variable *spvar= spcont->add_variable(thd, name); spcont->declare_var_boundary(1); spvar->field_def.field_name= spvar->name; spvar->field_def.set_handler(&type_handler_longlong); type_handler_longlong.Column_definition_prepare_stage2(&spvar->field_def, NULL, HA_CAN_GEOMETRY); if (!value && unlikely(!(value= new (thd->mem_root) Item_null(thd)))) return NULL; spvar->default_value= value; sp_instr_set *is= new (this->thd->mem_root) sp_instr_set(sphead->instructions(), spcont, &sp_rcontext_handler_local, spvar->offset, value, this, true); if (unlikely(is == NULL || sphead->add_instr(is))) return NULL; spcont->declare_var_boundary(0); return spvar; }
367,372
0
inline bool is_prepared() { return prepared; }
inline bool is_prepared() { return prepared; }
367,373
0
SELECT_LEX *LEX::alloc_select(bool select) { SELECT_LEX *select_lex; DBUG_ENTER("LEX::alloc_select"); if (!(select_lex= new (thd->mem_root) SELECT_LEX())) DBUG_RETURN(NULL); DBUG_PRINT("info", ("Allocate select: %p #%u statement lex: %p", select_lex, thd->lex->stmt_lex->current_select_number, thd->lex->stmt_lex)); /* TODO: move following init to constructor when we get rid of builtin select */ select_lex->select_number= ++thd->lex->stmt_lex->current_select_number; select_lex->parent_lex= this; /* Used in init_query. */ select_lex->init_query(); if (select) select_lex->init_select(); select_lex->nest_level_base= &this->unit; select_lex->include_global((st_select_lex_node**)&all_selects_list); select_lex->context.resolve_in_select_list= TRUE; DBUG_RETURN(select_lex); }
SELECT_LEX *LEX::alloc_select(bool select) { SELECT_LEX *select_lex; DBUG_ENTER("LEX::alloc_select"); if (!(select_lex= new (thd->mem_root) SELECT_LEX())) DBUG_RETURN(NULL); DBUG_PRINT("info", ("Allocate select: %p #%u statement lex: %p", select_lex, thd->lex->stmt_lex->current_select_number, thd->lex->stmt_lex)); select_lex->select_number= ++thd->lex->stmt_lex->current_select_number; select_lex->parent_lex= this; select_lex->init_query(); if (select) select_lex->init_select(); select_lex->nest_level_base= &this->unit; select_lex->include_global((st_select_lex_node**)&all_selects_list); select_lex->context.resolve_in_select_list= TRUE; DBUG_RETURN(select_lex); }
367,374
0
bool LEX::sp_open_cursor(THD *thd, const LEX_CSTRING *name, List<sp_assignment_lex> *parameters) { uint offset; const sp_pcursor *pcursor; uint param_count= parameters ? parameters->elements : 0; return !(pcursor= spcont->find_cursor_with_error(name, &offset, false)) || pcursor->check_param_count_with_error(param_count) || sphead->add_open_cursor(thd, spcont, offset, pcursor->param_context(), parameters); }
bool LEX::sp_open_cursor(THD *thd, const LEX_CSTRING *name, List<sp_assignment_lex> *parameters) { uint offset; const sp_pcursor *pcursor; uint param_count= parameters ? parameters->elements : 0; return !(pcursor= spcont->find_cursor_with_error(name, &offset, false)) || pcursor->check_param_count_with_error(param_count) || sphead->add_open_cursor(thd, spcont, offset, pcursor->param_context(), parameters); }
367,375
0
static my_bool find_thread_callback(THD *thd, find_thread_callback_arg *arg) { if (arg->id == (arg->query_id ? thd->query_id : (longlong) thd->thread_id)) { mysql_mutex_lock(&thd->LOCK_thd_kill); // Lock from delete arg->thd= thd; return 1; } return 0; }
static my_bool find_thread_callback(THD *thd, find_thread_callback_arg *arg) { if (arg->id == (arg->query_id ? thd->query_id : (longlong) thd->thread_id)) { mysql_mutex_lock(&thd->LOCK_thd_kill); arg->thd= thd; return 1; } return 0; }
367,376
0
bool SELECT_LEX_UNIT::set_lock_to_the_last_select(Lex_select_lock l) { if (l.defined_lock) { SELECT_LEX *sel= first_select(); while (sel->next_select()) sel= sel->next_select(); if (sel->braces) { my_error(ER_WRONG_USAGE, MYF(0), "lock options", "SELECT in brackets"); return TRUE; } l.set_to(sel); } return FALSE; }
bool SELECT_LEX_UNIT::set_lock_to_the_last_select(Lex_select_lock l) { if (l.defined_lock) { SELECT_LEX *sel= first_select(); while (sel->next_select()) sel= sel->next_select(); if (sel->braces) { my_error(ER_WRONG_USAGE, MYF(0), "lock options", "SELECT in brackets"); return TRUE; } l.set_to(sel); } return FALSE; }
367,377
0
bool eof(int n) { return ((m_ptr + n) >= m_end_of_query); }
bool eof(int n) { return ((m_ptr + n) >= m_end_of_query); }
367,378
0
void set(const Lex_ident_sys_st &ident, Item *code, List<Item> *params) { DBUG_ASSERT(m_params.elements == 0); m_name= ident; m_code= code; if (params) m_params= *params; }
void set(const Lex_ident_sys_st &ident, Item *code, List<Item> *params) { DBUG_ASSERT(m_params.elements == 0); m_name= ident; m_code= code; if (params) m_params= *params; }
367,379
0
void set_query_tables_list(Query_tables_list *state) { *this= *state; }
void set_query_tables_list(Query_tables_list *state) { *this= *state; }
367,380
0
bool LEX::sp_exit_block(THD *thd, sp_label *lab) { /* When jumping to a BEGIN-END block end, the target jump points to the block hpop/cpop cleanup instructions, so we should exclude the block context here. When jumping to something else (i.e., SP_LAB_ITER), there are no hpop/cpop at the jump destination, so we should include the block context here for cleanup. */ bool exclusive= (lab->type == sp_label::BEGIN); return sp_change_context(thd, lab->ctx, exclusive) || sphead->add_instr_jump_forward_with_backpatch(thd, spcont, lab); }
bool LEX::sp_exit_block(THD *thd, sp_label *lab) { bool exclusive= (lab->type == sp_label::BEGIN); return sp_change_context(thd, lab->ctx, exclusive) || sphead->add_instr_jump_forward_with_backpatch(thd, spcont, lab); }
367,381
0
sp_name *LEX::make_sp_name(THD *thd, const LEX_CSTRING *name) { sp_name *res; LEX_CSTRING db; if (unlikely(check_routine_name(name)) || unlikely(copy_db_to(&db)) || unlikely((!(res= new (thd->mem_root) sp_name(&db, name, false))))) return NULL; return res; }
sp_name *LEX::make_sp_name(THD *thd, const LEX_CSTRING *name) { sp_name *res; LEX_CSTRING db; if (unlikely(check_routine_name(name)) || unlikely(copy_db_to(&db)) || unlikely((!(res= new (thd->mem_root) sp_name(&db, name, false))))) return NULL; return res; }
367,385
0
void LEX::restore_values_list_state() { many_values= current_select->save_many_values; insert_list= current_select->save_insert_list; }
void LEX::restore_values_list_state() { many_values= current_select->save_many_values; insert_list= current_select->save_insert_list; }
367,386
0
bool LEX::sp_for_loop_cursor_finalize(THD *thd, const Lex_for_loop_st &loop) { sp_instr_cfetch *instr= new (thd->mem_root) sp_instr_cfetch(sphead->instructions(), spcont, loop.m_cursor_offset, false); if (unlikely(instr == NULL) || unlikely(sphead->add_instr(instr))) return true; instr->add_to_varlist(loop.m_index); // Generate a jump to the beginning of the loop return sp_while_loop_finalize(thd); }
bool LEX::sp_for_loop_cursor_finalize(THD *thd, const Lex_for_loop_st &loop) { sp_instr_cfetch *instr= new (thd->mem_root) sp_instr_cfetch(sphead->instructions(), spcont, loop.m_cursor_offset, false); if (unlikely(instr == NULL) || unlikely(sphead->add_instr(instr))) return true; instr->add_to_varlist(loop.m_index); return sp_while_loop_finalize(thd); }
367,388
0
void cut_next() { next= NULL; }
void cut_next() { next= NULL; }
367,389
0
bool LEX::add_alter_view(THD *thd, uint16 algorithm, enum_view_suid suid, Table_ident *table_ident) { if (unlikely(sphead)) { my_error(ER_SP_BADSTATEMENT, MYF(0), "ALTER VIEW"); return true; } if (unlikely(!(create_view= new (thd->mem_root) Create_view_info(VIEW_ALTER, algorithm, suid)))) return true; return create_or_alter_view_finalize(thd, table_ident); }
bool LEX::add_alter_view(THD *thd, uint16 algorithm, enum_view_suid suid, Table_ident *table_ident) { if (unlikely(sphead)) { my_error(ER_SP_BADSTATEMENT, MYF(0), "ALTER VIEW"); return true; } if (unlikely(!(create_view= new (thd->mem_root) Create_view_info(VIEW_ALTER, algorithm, suid)))) return true; return create_or_alter_view_finalize(thd, table_ident); }
367,390
0
inline void set_stmt_unsafe(enum_binlog_stmt_unsafe unsafe_type) { DBUG_ENTER("set_stmt_unsafe"); DBUG_ASSERT(unsafe_type >= 0 && unsafe_type < BINLOG_STMT_UNSAFE_COUNT); binlog_stmt_flags|= (1U << unsafe_type); DBUG_VOID_RETURN; }
inline void set_stmt_unsafe(enum_binlog_stmt_unsafe unsafe_type) { DBUG_ENTER("set_stmt_unsafe"); DBUG_ASSERT(unsafe_type >= 0 && unsafe_type < BINLOG_STMT_UNSAFE_COUNT); binlog_stmt_flags|= (1U << unsafe_type); DBUG_VOID_RETURN; }
367,392
0
void st_select_lex_node::fast_exclude() { if (link_prev) { if ((*link_prev= link_next)) link_next->link_prev= link_prev; } // Remove slave structure for (; slave; slave= slave->next) slave->fast_exclude(); }
void st_select_lex_node::fast_exclude() { if (link_prev) { if ((*link_prev= link_next)) link_next->link_prev= link_prev; } for (; slave; slave= slave->next) slave->fast_exclude(); }
367,393
0
Item *LEX::create_item_ident_field(THD *thd, const char *db, const char *table, const Lex_ident_sys_st *name) { if (check_expr_allows_fields_or_error(thd, name->str)) return NULL; if (current_select->parsing_place != IN_HAVING || current_select->get_in_sum_expr() > 0) return new (thd->mem_root) Item_field(thd, current_context(), db, table, name); return new (thd->mem_root) Item_ref(thd, current_context(), db, table, name); }
Item *LEX::create_item_ident_field(THD *thd, const char *db, const char *table, const Lex_ident_sys_st *name) { if (check_expr_allows_fields_or_error(thd, name->str)) return NULL; if (current_select->parsing_place != IN_HAVING || current_select->get_in_sum_expr() > 0) return new (thd->mem_root) Item_field(thd, current_context(), db, table, name); return new (thd->mem_root) Item_ref(thd, current_context(), db, table, name); }
367,394
0
bool uses_stored_routines() const { return sroutines_list.elements != 0; }
bool uses_stored_routines() const { return sroutines_list.elements != 0; }
367,397
0
bool LEX::stmt_create_stored_function_start(const DDL_options_st &options, enum_sp_aggregate_type agg_type, const sp_name *spname) { if (stmt_create_function_start(options) || unlikely(!make_sp_head_no_recursive(thd, spname, &sp_handler_function, agg_type))) return true; return false; }
bool LEX::stmt_create_stored_function_start(const DDL_options_st &options, enum_sp_aggregate_type agg_type, const sp_name *spname) { if (stmt_create_function_start(options) || unlikely(!make_sp_head_no_recursive(thd, spname, &sp_handler_function, agg_type))) return true; return false; }
367,399
0
bool LEX::insert_select_hack(SELECT_LEX *sel) { DBUG_ENTER("LEX::insert_select_hack"); DBUG_ASSERT(first_select_lex() == &builtin_select); DBUG_ASSERT(sel != NULL); DBUG_ASSERT(builtin_select.first_inner_unit() == NULL); if (builtin_select.link_prev) { if ((*builtin_select.link_prev= builtin_select.link_next)) ((st_select_lex *)builtin_select.link_next)->link_prev= builtin_select.link_prev; builtin_select.link_prev= NULL; // indicator of removal } if (set_main_unit(sel->master_unit())) return true; DBUG_ASSERT(builtin_select.table_list.elements == 1); TABLE_LIST *insert_table= builtin_select.table_list.first; if (!(insert_table->next_local= sel->table_list.first)) { sel->table_list.next= &insert_table->next_local; } sel->table_list.first= insert_table; sel->table_list.elements++; insert_table->select_lex= sel; sel->context.first_name_resolution_table= insert_table; builtin_select.context= sel->context; change_item_list_context(&field_list, &sel->context); if (sel->tvc && !sel->next_select() && (sql_command == SQLCOM_INSERT_SELECT || sql_command == SQLCOM_REPLACE_SELECT)) { DBUG_PRINT("info", ("'Usual' INSERT detected")); many_values= sel->tvc->lists_of_values; sel->options= sel->tvc->select_options; sel->tvc= NULL; if (sql_command == SQLCOM_INSERT_SELECT) sql_command= SQLCOM_INSERT; else sql_command= SQLCOM_REPLACE; } for (SELECT_LEX *sel= all_selects_list; sel; sel= sel->next_select_in_list()) { if (sel->select_number != 1) sel->select_number--; }; DBUG_RETURN(FALSE); }
bool LEX::insert_select_hack(SELECT_LEX *sel) { DBUG_ENTER("LEX::insert_select_hack"); DBUG_ASSERT(first_select_lex() == &builtin_select); DBUG_ASSERT(sel != NULL); DBUG_ASSERT(builtin_select.first_inner_unit() == NULL); if (builtin_select.link_prev) { if ((*builtin_select.link_prev= builtin_select.link_next)) ((st_select_lex *)builtin_select.link_next)->link_prev= builtin_select.link_prev; builtin_select.link_prev= NULL; } if (set_main_unit(sel->master_unit())) return true; DBUG_ASSERT(builtin_select.table_list.elements == 1); TABLE_LIST *insert_table= builtin_select.table_list.first; if (!(insert_table->next_local= sel->table_list.first)) { sel->table_list.next= &insert_table->next_local; } sel->table_list.first= insert_table; sel->table_list.elements++; insert_table->select_lex= sel; sel->context.first_name_resolution_table= insert_table; builtin_select.context= sel->context; change_item_list_context(&field_list, &sel->context); if (sel->tvc && !sel->next_select() && (sql_command == SQLCOM_INSERT_SELECT || sql_command == SQLCOM_REPLACE_SELECT)) { DBUG_PRINT("info", ("'Usual' INSERT detected")); many_values= sel->tvc->lists_of_values; sel->options= sel->tvc->select_options; sel->tvc= NULL; if (sql_command == SQLCOM_INSERT_SELECT) sql_command= SQLCOM_INSERT; else sql_command= SQLCOM_REPLACE; } for (SELECT_LEX *sel= all_selects_list; sel; sel= sel->next_select_in_list()) { if (sel->select_number != 1) sel->select_number--; }; DBUG_RETURN(FALSE); }
367,400
0
void set(const st_sp_chistics &other) { *this= other; }
void set(const st_sp_chistics &other) { *this= other; }
367,401
0
void SELECT_LEX::mark_const_derived(bool empty) { TABLE_LIST *derived= master_unit()->derived; /* join == NULL in DELETE ... RETURNING */ if (!(join && join->thd->lex->describe) && derived) { if (!empty) increase_derived_records(1); if (!master_unit()->is_unit_op() && !derived->is_merged_derived() && !(join && join->with_two_phase_optimization)) derived->fill_me= TRUE; } }
void SELECT_LEX::mark_const_derived(bool empty) { TABLE_LIST *derived= master_unit()->derived; if (!(join && join->thd->lex->describe) && derived) { if (!empty) increase_derived_records(1); if (!master_unit()->is_unit_op() && !derived->is_merged_derived() && !(join && join->with_two_phase_optimization)) derived->fill_me= TRUE; } }
367,402
0
LEX::sp_add_for_loop_cursor_variable(THD *thd, const LEX_CSTRING *name, const sp_pcursor *pcursor, uint coffset, sp_assignment_lex *param_lex, Item_args *parameters) { sp_variable *spvar= spcont->add_variable(thd, name); if (!spvar) return NULL; spcont->declare_var_boundary(1); sphead->fill_spvar_definition(thd, &spvar->field_def, &spvar->name); if (unlikely(!(spvar->default_value= new (thd->mem_root) Item_null(thd)))) return NULL; spvar->field_def.set_cursor_rowtype_ref(coffset); if (unlikely(sphead->add_for_loop_open_cursor(thd, spcont, spvar, pcursor, coffset, param_lex, parameters))) return NULL; spcont->declare_var_boundary(0); return spvar; }
LEX::sp_add_for_loop_cursor_variable(THD *thd, const LEX_CSTRING *name, const sp_pcursor *pcursor, uint coffset, sp_assignment_lex *param_lex, Item_args *parameters) { sp_variable *spvar= spcont->add_variable(thd, name); if (!spvar) return NULL; spcont->declare_var_boundary(1); sphead->fill_spvar_definition(thd, &spvar->field_def, &spvar->name); if (unlikely(!(spvar->default_value= new (thd->mem_root) Item_null(thd)))) return NULL; spvar->field_def.set_cursor_rowtype_ref(coffset); if (unlikely(sphead->add_for_loop_open_cursor(thd, spcont, spvar, pcursor, coffset, param_lex, parameters))) return NULL; spcont->declare_var_boundary(0); return spvar; }
367,404
0
inline bool is_stmt_row_injection() const { return binlog_stmt_flags & (1U << (BINLOG_STMT_UNSAFE_COUNT + BINLOG_STMT_TYPE_ROW_INJECTION)); }
inline bool is_stmt_row_injection() const { return binlog_stmt_flags & (1U << (BINLOG_STMT_UNSAFE_COUNT + BINLOG_STMT_TYPE_ROW_INJECTION)); }
367,405
0
LEX::sp_variable_declarations_vartype_finalize(THD *thd, int nvars, const LEX_CSTRING &ref, Item *default_value) { sp_variable *t; if (!spcont || !(t= spcont->find_variable(&ref, false))) { my_error(ER_SP_UNDECLARED_VAR, MYF(0), ref.str); return true; } if (t->field_def.is_cursor_rowtype_ref()) { uint offset= t->field_def.cursor_rowtype_offset(); return sp_variable_declarations_cursor_rowtype_finalize(thd, nvars, offset, default_value); } if (t->field_def.is_column_type_ref()) { Qualified_column_ident *tmp= t->field_def.column_type_ref(); return sp_variable_declarations_column_type_finalize(thd, nvars, tmp, default_value); } if (t->field_def.is_table_rowtype_ref()) { const Table_ident *tmp= t->field_def.table_rowtype_ref(); return sp_variable_declarations_table_rowtype_finalize(thd, nvars, tmp->db, tmp->table, default_value); } // A reference to a scalar or a row variable with an explicit data type return sp_variable_declarations_copy_type_finalize(thd, nvars, t->field_def, t->field_def. row_field_definitions(), default_value); }
LEX::sp_variable_declarations_vartype_finalize(THD *thd, int nvars, const LEX_CSTRING &ref, Item *default_value) { sp_variable *t; if (!spcont || !(t= spcont->find_variable(&ref, false))) { my_error(ER_SP_UNDECLARED_VAR, MYF(0), ref.str); return true; } if (t->field_def.is_cursor_rowtype_ref()) { uint offset= t->field_def.cursor_rowtype_offset(); return sp_variable_declarations_cursor_rowtype_finalize(thd, nvars, offset, default_value); } if (t->field_def.is_column_type_ref()) { Qualified_column_ident *tmp= t->field_def.column_type_ref(); return sp_variable_declarations_column_type_finalize(thd, nvars, tmp, default_value); } if (t->field_def.is_table_rowtype_ref()) { const Table_ident *tmp= t->field_def.table_rowtype_ref(); return sp_variable_declarations_table_rowtype_finalize(thd, nvars, tmp->db, tmp->table, default_value); } return sp_variable_declarations_copy_type_finalize(thd, nvars, t->field_def, t->field_def. row_field_definitions(), default_value); }
367,407
0
bool check_host_name(LEX_CSTRING *str) { const char *name= str->str; const char *end= str->str + str->length; if (check_string_byte_length(str, ER_HOSTNAME, HOSTNAME_LENGTH)) return TRUE; while (name != end) { if (*name == '@') { my_printf_error(ER_UNKNOWN_ERROR, "Malformed hostname (illegal symbol: '%c')", MYF(0), *name); return TRUE; } name++; } return FALSE; }
bool check_host_name(LEX_CSTRING *str) { const char *name= str->str; const char *end= str->str + str->length; if (check_string_byte_length(str, ER_HOSTNAME, HOSTNAME_LENGTH)) return TRUE; while (name != end) { if (*name == '@') { my_printf_error(ER_UNKNOWN_ERROR, "Malformed hostname (illegal symbol: '%c')", MYF(0), *name); return TRUE; } name++; } return FALSE; }
367,408
0
void yyUnget() { m_ptr--; if (m_echo) m_cpp_ptr--; }
void yyUnget() { m_ptr--; if (m_echo) m_cpp_ptr--; }
367,409
0
static int pptp_echo_rply(struct pptp_conn_t *conn) { struct pptp_echo_rply *msg = (struct pptp_echo_rply *)conn->in_buf; if (conf_verbose) log_ppp_debug("recv [PPTP Echo-Reply <Identifier %x>]\n", msg->identifier); conn->echo_sent = 0; return 0; }
static int pptp_echo_rply(struct pptp_conn_t *conn) { struct pptp_echo_rply *msg = (struct pptp_echo_rply *)conn->in_buf; if (conf_verbose) log_ppp_debug("recv [PPTP Echo-Reply <Identifier %x>]\n", msg->identifier); conn->echo_sent = 0; return 0; }
367,410
0
static int send_pptp_stop_ctrl_conn_rply(struct pptp_conn_t *conn, int reason, int err_code) { struct pptp_stop_ctrl_conn msg = { .header = PPTP_HEADER_CTRL(PPTP_STOP_CTRL_CONN_RPLY), .reason_result = hton8(reason), .error_code = hton8(err_code), }; if (conf_verbose) log_ppp_info2("send [PPTP Stop-Ctrl-Conn-Reply <Result %i> <Error %i>]\n", msg.reason_result, msg.error_code); return post_msg(conn, &msg, sizeof(msg)); }
static int send_pptp_stop_ctrl_conn_rply(struct pptp_conn_t *conn, int reason, int err_code) { struct pptp_stop_ctrl_conn msg = { .header = PPTP_HEADER_CTRL(PPTP_STOP_CTRL_CONN_RPLY), .reason_result = hton8(reason), .error_code = hton8(err_code), }; if (conf_verbose) log_ppp_info2("send [PPTP Stop-Ctrl-Conn-Reply <Result %i> <Error %i>]\n", msg.reason_result, msg.error_code); return post_msg(conn, &msg, sizeof(msg)); }
367,411
0
static int post_msg(struct pptp_conn_t *conn, void *buf, int size) { int n; if (conn->out_size) { log_error("pptp: buffer is not empty\n"); return -1; } again: n=write(conn->hnd.fd, buf, size); if (n < 0) { if (errno == EINTR) goto again; else if (errno == EAGAIN) n = 0; else { if (errno != EPIPE) { if (conf_verbose) log_ppp_info2("pptp: write: %s\n", strerror(errno)); } return -1; } } if ( n<size ) { memcpy(conn->out_buf, (uint8_t *)buf + n, size - n); triton_md_enable_handler(&conn->hnd, MD_MODE_WRITE); } return 0; }
static int post_msg(struct pptp_conn_t *conn, void *buf, int size) { int n; if (conn->out_size) { log_error("pptp: buffer is not empty\n"); return -1; } again: n=write(conn->hnd.fd, buf, size); if (n < 0) { if (errno == EINTR) goto again; else if (errno == EAGAIN) n = 0; else { if (errno != EPIPE) { if (conf_verbose) log_ppp_info2("pptp: write: %s\n", strerror(errno)); } return -1; } } if ( n<size ) { memcpy(conn->out_buf, (uint8_t *)buf + n, size - n); triton_md_enable_handler(&conn->hnd, MD_MODE_WRITE); } return 0; }
367,412
0
static void pptp_serv_close(struct triton_context_t *ctx) { struct pptp_serv_t *s=container_of(ctx,typeof(*s),ctx); triton_md_unregister_handler(&s->hnd, 1); triton_context_unregister(ctx); }
static void pptp_serv_close(struct triton_context_t *ctx) { struct pptp_serv_t *s=container_of(ctx,typeof(*s),ctx); triton_md_unregister_handler(&s->hnd, 1); triton_context_unregister(ctx); }
367,415
0
static int send_pptp_stop_ctrl_conn_rqst(struct pptp_conn_t *conn, int reason) { struct pptp_stop_ctrl_conn msg = { .header = PPTP_HEADER_CTRL(PPTP_STOP_CTRL_CONN_RQST), .reason_result = hton8(reason), }; if (conf_verbose) log_ppp_info2("send [PPTP Stop-Ctrl-Conn-Request <Reason %i>]\n", reason); return post_msg(conn, &msg, sizeof(msg)); }
static int send_pptp_stop_ctrl_conn_rqst(struct pptp_conn_t *conn, int reason) { struct pptp_stop_ctrl_conn msg = { .header = PPTP_HEADER_CTRL(PPTP_STOP_CTRL_CONN_RQST), .reason_result = hton8(reason), }; if (conf_verbose) log_ppp_info2("send [PPTP Stop-Ctrl-Conn-Request <Reason %i>]\n", reason); return post_msg(conn, &msg, sizeof(msg)); }
367,416
0
static void pptp_init(void) { struct sockaddr_in addr; char *opt; int fd; fd = socket(AF_PPPOX, SOCK_STREAM, PX_PROTO_PPTP); if (fd >= 0) close(fd); else if (system("modprobe -q pptp")) log_warn("failed to load pptp kernel module\n"); serv.hnd.fd = socket(PF_INET, SOCK_STREAM, 0); if (serv.hnd.fd < 0) { log_emerg("pptp: failed to create server socket: %s\n", strerror(errno)); return; } fcntl(serv.hnd.fd, F_SETFD, fcntl(serv.hnd.fd, F_GETFD) | FD_CLOEXEC); addr.sin_family = AF_INET; opt = conf_get_opt("pptp", "bind"); if (opt) addr.sin_addr.s_addr = inet_addr(opt); else addr.sin_addr.s_addr = htonl(INADDR_ANY); opt = conf_get_opt("pptp", "port"); if (opt && atoi(opt) > 0) addr.sin_port = htons(atoi(opt)); else addr.sin_port = htons(PPTP_PORT); setsockopt(serv.hnd.fd, SOL_SOCKET, SO_REUSEADDR, &serv.hnd.fd, 4); if (bind (serv.hnd.fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) { log_emerg("pptp: failed to bind socket: %s\n", strerror(errno)); close(serv.hnd.fd); return; } if (listen (serv.hnd.fd, 100) < 0) { log_emerg("pptp: failed to listen socket: %s\n", strerror(errno)); close(serv.hnd.fd); return; } if (fcntl(serv.hnd.fd, F_SETFL, O_NONBLOCK)) { log_emerg("pptp: failed to set nonblocking mode: %s\n", strerror(errno)); close(serv.hnd.fd); return; } conn_pool = mempool_create(sizeof(struct pptp_conn_t)); load_config(); triton_context_register(&serv.ctx, NULL); triton_md_register_handler(&serv.ctx, &serv.hnd); triton_md_enable_handler(&serv.hnd, MD_MODE_READ); triton_context_wakeup(&serv.ctx); cli_register_simple_cmd2(show_stat_exec, NULL, 2, "show", "stat"); triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); }
static void pptp_init(void) { struct sockaddr_in addr; char *opt; int fd; fd = socket(AF_PPPOX, SOCK_STREAM, PX_PROTO_PPTP); if (fd >= 0) close(fd); else if (system("modprobe -q pptp")) log_warn("failed to load pptp kernel module\n"); serv.hnd.fd = socket(PF_INET, SOCK_STREAM, 0); if (serv.hnd.fd < 0) { log_emerg("pptp: failed to create server socket: %s\n", strerror(errno)); return; } fcntl(serv.hnd.fd, F_SETFD, fcntl(serv.hnd.fd, F_GETFD) | FD_CLOEXEC); addr.sin_family = AF_INET; opt = conf_get_opt("pptp", "bind"); if (opt) addr.sin_addr.s_addr = inet_addr(opt); else addr.sin_addr.s_addr = htonl(INADDR_ANY); opt = conf_get_opt("pptp", "port"); if (opt && atoi(opt) > 0) addr.sin_port = htons(atoi(opt)); else addr.sin_port = htons(PPTP_PORT); setsockopt(serv.hnd.fd, SOL_SOCKET, SO_REUSEADDR, &serv.hnd.fd, 4); if (bind (serv.hnd.fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) { log_emerg("pptp: failed to bind socket: %s\n", strerror(errno)); close(serv.hnd.fd); return; } if (listen (serv.hnd.fd, 100) < 0) { log_emerg("pptp: failed to listen socket: %s\n", strerror(errno)); close(serv.hnd.fd); return; } if (fcntl(serv.hnd.fd, F_SETFL, O_NONBLOCK)) { log_emerg("pptp: failed to set nonblocking mode: %s\n", strerror(errno)); close(serv.hnd.fd); return; } conn_pool = mempool_create(sizeof(struct pptp_conn_t)); load_config(); triton_context_register(&serv.ctx, NULL); triton_md_register_handler(&serv.ctx, &serv.hnd); triton_md_enable_handler(&serv.hnd, MD_MODE_READ); triton_context_wakeup(&serv.ctx); cli_register_simple_cmd2(show_stat_exec, NULL, 2, "show", "stat"); triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); }
367,418
0
static int send_pptp_start_ctrl_conn_rply(struct pptp_conn_t *conn, int res_code, int err_code) { struct pptp_start_ctrl_conn msg = { .header = PPTP_HEADER_CTRL(PPTP_START_CTRL_CONN_RPLY), .version = htons(PPTP_VERSION), .result_code = res_code, .error_code = err_code, .framing_cap = htonl(PPTP_FRAME_ANY), .bearer_cap = htonl(PPTP_BEARER_ANY), .max_channels = htons(1), .firmware_rev = htons(PPTP_FIRMWARE_VERSION), }; memset(msg.hostname, 0, sizeof(msg.hostname)); strcpy((char*)msg.hostname, PPTP_HOSTNAME); memset(msg.vendor, 0, sizeof(msg.vendor)); strcpy((char*)msg.vendor, PPTP_VENDOR); if (conf_verbose) log_ppp_info2("send [PPTP Start-Ctrl-Conn-Reply <Version %i> <Result %i> <Error %i> <Framing %x> <Bearer %x> <Max-Chan %i>]\n", msg.version, msg.result_code, msg.error_code, ntohl(msg.framing_cap), ntohl(msg.bearer_cap), ntohs(msg.max_channels)); return post_msg(conn, &msg, sizeof(msg)); }
static int send_pptp_start_ctrl_conn_rply(struct pptp_conn_t *conn, int res_code, int err_code) { struct pptp_start_ctrl_conn msg = { .header = PPTP_HEADER_CTRL(PPTP_START_CTRL_CONN_RPLY), .version = htons(PPTP_VERSION), .result_code = res_code, .error_code = err_code, .framing_cap = htonl(PPTP_FRAME_ANY), .bearer_cap = htonl(PPTP_BEARER_ANY), .max_channels = htons(1), .firmware_rev = htons(PPTP_FIRMWARE_VERSION), }; memset(msg.hostname, 0, sizeof(msg.hostname)); strcpy((char*)msg.hostname, PPTP_HOSTNAME); memset(msg.vendor, 0, sizeof(msg.vendor)); strcpy((char*)msg.vendor, PPTP_VENDOR); if (conf_verbose) log_ppp_info2("send [PPTP Start-Ctrl-Conn-Reply <Version %i> <Result %i> <Error %i> <Framing %x> <Bearer %x> <Max-Chan %i>]\n", msg.version, msg.result_code, msg.error_code, ntohl(msg.framing_cap), ntohl(msg.bearer_cap), ntohs(msg.max_channels)); return post_msg(conn, &msg, sizeof(msg)); }
367,419
0
static int pptp_stop_ctrl_conn_rply(struct pptp_conn_t *conn) { struct pptp_stop_ctrl_conn *msg = (struct pptp_stop_ctrl_conn*)conn->in_buf; if (conf_verbose) log_ppp_info2("recv [PPTP Stop-Ctrl-Conn-Reply <Result %i> <Error %i>]\n", msg->reason_result, msg->error_code); return -1; }
static int pptp_stop_ctrl_conn_rply(struct pptp_conn_t *conn) { struct pptp_stop_ctrl_conn *msg = (struct pptp_stop_ctrl_conn*)conn->in_buf; if (conf_verbose) log_ppp_info2("recv [PPTP Stop-Ctrl-Conn-Reply <Result %i> <Error %i>]\n", msg->reason_result, msg->error_code); return -1; }
367,420
0
static int pptp_out_call_rqst(struct pptp_conn_t *conn) { struct pptp_out_call_rqst *msg = (struct pptp_out_call_rqst *)conn->in_buf; struct sockaddr_pppox src_addr, dst_addr; struct sockaddr_in addr; socklen_t addrlen; int pptp_sock; if (conf_verbose) log_ppp_info2("recv [PPTP Outgoing-Call-Request <Call-ID %x> <Call-Serial %x> <Min-BPS %i> <Max-BPS %i> <Bearer %x> <Framing %x> <Window-Size %i> <Delay %i>]\n", ntohs(msg->call_id), ntohs(msg->call_sernum), ntohl(msg->bps_min), ntohl(msg->bps_max), ntohl(msg->bearer), ntohl(msg->framing), ntohs(msg->recv_size), ntohs(msg->delay)); if (conn->state != STATE_ESTB) { log_ppp_warn("unexpected PPTP_OUT_CALL_RQST\n"); if (send_pptp_out_call_rply(conn, msg, 0, PPTP_CALL_RES_GE, PPTP_GE_NOCONN)) return -1; return 0; } memset(&src_addr, 0, sizeof(src_addr)); src_addr.sa_family = AF_PPPOX; src_addr.sa_protocol = PX_PROTO_PPTP; src_addr.sa_addr.pptp.call_id = 0; addrlen = sizeof(addr); getsockname(conn->hnd.fd, (struct sockaddr*)&addr, &addrlen); src_addr.sa_addr.pptp.sin_addr = addr.sin_addr; memset(&dst_addr, 0, sizeof(dst_addr)); dst_addr.sa_family = AF_PPPOX; dst_addr.sa_protocol = PX_PROTO_PPTP; dst_addr.sa_addr.pptp.call_id = htons(msg->call_id); addrlen = sizeof(addr); getpeername(conn->hnd.fd, (struct sockaddr*)&addr, &addrlen); dst_addr.sa_addr.pptp.sin_addr = addr.sin_addr; pptp_sock = socket(AF_PPPOX, SOCK_STREAM, PX_PROTO_PPTP); if (pptp_sock < 0) { log_ppp_error("failed to create PPTP socket (%s)\n", strerror(errno)); return -1; } fcntl(pptp_sock, F_SETFD, fcntl(pptp_sock, F_GETFD) | FD_CLOEXEC); if (bind(pptp_sock, (struct sockaddr*)&src_addr, sizeof(src_addr))) { log_ppp_error("failed to bind PPTP socket (%s)\n", strerror(errno)); close(pptp_sock); return -1; } addrlen = sizeof(src_addr); getsockname(pptp_sock, (struct sockaddr*)&src_addr, &addrlen); if (connect(pptp_sock, (struct sockaddr*)&dst_addr, sizeof(dst_addr))) { log_ppp_error("failed to connect PPTP socket (%s)\n", strerror(errno)); close(pptp_sock); return -1; } if (send_pptp_out_call_rply(conn, msg, src_addr.sa_addr.pptp.call_id, PPTP_CALL_RES_OK, 0)) return -1; conn->call_id = src_addr.sa_addr.pptp.call_id; conn->peer_call_id = msg->call_id; conn->ppp.fd = pptp_sock; conn->ppp.ses.chan_name = _strdup(inet_ntoa(dst_addr.sa_addr.pptp.sin_addr)); triton_event_fire(EV_CTRL_STARTED, &conn->ppp.ses); if (establish_ppp(&conn->ppp)) { close(pptp_sock); //if (send_pptp_stop_ctrl_conn_rqst(conn, 0, 0)) conn->state = STATE_FIN; return -1; } conn->state = STATE_PPP; __sync_sub_and_fetch(&stat_starting, 1); __sync_add_and_fetch(&stat_active, 1); if (conn->timeout_timer.tpd) triton_timer_del(&conn->timeout_timer); if (conf_echo_interval) { conn->echo_timer.period = conf_echo_interval * 1000; triton_timer_add(&conn->ctx, &conn->echo_timer, 0); } return 0; }
static int pptp_out_call_rqst(struct pptp_conn_t *conn) { struct pptp_out_call_rqst *msg = (struct pptp_out_call_rqst *)conn->in_buf; struct sockaddr_pppox src_addr, dst_addr; struct sockaddr_in addr; socklen_t addrlen; int pptp_sock; if (conf_verbose) log_ppp_info2("recv [PPTP Outgoing-Call-Request <Call-ID %x> <Call-Serial %x> <Min-BPS %i> <Max-BPS %i> <Bearer %x> <Framing %x> <Window-Size %i> <Delay %i>]\n", ntohs(msg->call_id), ntohs(msg->call_sernum), ntohl(msg->bps_min), ntohl(msg->bps_max), ntohl(msg->bearer), ntohl(msg->framing), ntohs(msg->recv_size), ntohs(msg->delay)); if (conn->state != STATE_ESTB) { log_ppp_warn("unexpected PPTP_OUT_CALL_RQST\n"); if (send_pptp_out_call_rply(conn, msg, 0, PPTP_CALL_RES_GE, PPTP_GE_NOCONN)) return -1; return 0; } memset(&src_addr, 0, sizeof(src_addr)); src_addr.sa_family = AF_PPPOX; src_addr.sa_protocol = PX_PROTO_PPTP; src_addr.sa_addr.pptp.call_id = 0; addrlen = sizeof(addr); getsockname(conn->hnd.fd, (struct sockaddr*)&addr, &addrlen); src_addr.sa_addr.pptp.sin_addr = addr.sin_addr; memset(&dst_addr, 0, sizeof(dst_addr)); dst_addr.sa_family = AF_PPPOX; dst_addr.sa_protocol = PX_PROTO_PPTP; dst_addr.sa_addr.pptp.call_id = htons(msg->call_id); addrlen = sizeof(addr); getpeername(conn->hnd.fd, (struct sockaddr*)&addr, &addrlen); dst_addr.sa_addr.pptp.sin_addr = addr.sin_addr; pptp_sock = socket(AF_PPPOX, SOCK_STREAM, PX_PROTO_PPTP); if (pptp_sock < 0) { log_ppp_error("failed to create PPTP socket (%s)\n", strerror(errno)); return -1; } fcntl(pptp_sock, F_SETFD, fcntl(pptp_sock, F_GETFD) | FD_CLOEXEC); if (bind(pptp_sock, (struct sockaddr*)&src_addr, sizeof(src_addr))) { log_ppp_error("failed to bind PPTP socket (%s)\n", strerror(errno)); close(pptp_sock); return -1; } addrlen = sizeof(src_addr); getsockname(pptp_sock, (struct sockaddr*)&src_addr, &addrlen); if (connect(pptp_sock, (struct sockaddr*)&dst_addr, sizeof(dst_addr))) { log_ppp_error("failed to connect PPTP socket (%s)\n", strerror(errno)); close(pptp_sock); return -1; } if (send_pptp_out_call_rply(conn, msg, src_addr.sa_addr.pptp.call_id, PPTP_CALL_RES_OK, 0)) return -1; conn->call_id = src_addr.sa_addr.pptp.call_id; conn->peer_call_id = msg->call_id; conn->ppp.fd = pptp_sock; conn->ppp.ses.chan_name = _strdup(inet_ntoa(dst_addr.sa_addr.pptp.sin_addr)); triton_event_fire(EV_CTRL_STARTED, &conn->ppp.ses); if (establish_ppp(&conn->ppp)) { close(pptp_sock); conn->state = STATE_FIN; return -1; } conn->state = STATE_PPP; __sync_sub_and_fetch(&stat_starting, 1); __sync_add_and_fetch(&stat_active, 1); if (conn->timeout_timer.tpd) triton_timer_del(&conn->timeout_timer); if (conf_echo_interval) { conn->echo_timer.period = conf_echo_interval * 1000; triton_timer_add(&conn->ctx, &conn->echo_timer, 0); } return 0; }
367,421
0
static int pptp_write(struct triton_md_handler_t *h) { struct pptp_conn_t *conn = container_of(h, typeof(*conn), hnd); int n; while (1) { n = write(h->fd, conn->out_buf+conn->out_pos, conn->out_size-conn->out_pos); if (n < 0) { if (errno == EINTR) continue; if (errno == EAGAIN) n = 0; else { if (errno != EPIPE) { if (conf_verbose) log_ppp_info2("pptp: post_msg: %s\n", strerror(errno)); } disconnect(conn); return 1; } } conn->out_pos += n; if (conn->out_pos == conn->out_size) { conn->out_pos = 0; conn->out_size = 0; triton_md_disable_handler(h, MD_MODE_WRITE); return 0; } } }
static int pptp_write(struct triton_md_handler_t *h) { struct pptp_conn_t *conn = container_of(h, typeof(*conn), hnd); int n; while (1) { n = write(h->fd, conn->out_buf+conn->out_pos, conn->out_size-conn->out_pos); if (n < 0) { if (errno == EINTR) continue; if (errno == EAGAIN) n = 0; else { if (errno != EPIPE) { if (conf_verbose) log_ppp_info2("pptp: post_msg: %s\n", strerror(errno)); } disconnect(conn); return 1; } } conn->out_pos += n; if (conn->out_pos == conn->out_size) { conn->out_pos = 0; conn->out_size = 0; triton_md_disable_handler(h, MD_MODE_WRITE); return 0; } } }
367,422
0
static int pptp_read(struct triton_md_handler_t *h) { struct pptp_conn_t *conn=container_of(h,typeof(*conn),hnd); struct pptp_header *hdr=(struct pptp_header *)conn->in_buf; int n; while(1) { n = read(h->fd, conn->in_buf + conn->in_size, PPTP_CTRL_SIZE_MAX - conn->in_size); if (n < 0) { if (errno == EINTR) continue; if (errno == EAGAIN) return 0; log_ppp_error("pptp: read: %s\n",strerror(errno)); goto drop; } if (n == 0) { if (conf_verbose) log_ppp_info2("pptp: disconnect by peer\n"); goto drop; } conn->in_size += n; if (conn->in_size >= sizeof(*hdr)) { if (hdr->magic != htonl(PPTP_MAGIC)) { log_ppp_error("pptp: invalid magic\n"); goto drop; } if (ntohs(hdr->length) >= PPTP_CTRL_SIZE_MAX) { log_ppp_error("pptp: message is too long\n"); goto drop; } if (ntohs(hdr->length) > conn->in_size) continue; if (ntohs(hdr->length) <= conn->in_size) { if (ntohs(hdr->length) != PPTP_CTRL_SIZE(ntohs(hdr->ctrl_type))) { log_ppp_error("pptp: invalid message length\n"); goto drop; } if (process_packet(conn)) goto drop; conn->in_size -= ntohs(hdr->length); if (conn->in_size) memmove(conn->in_buf, conn->in_buf + ntohs(hdr->length), conn->in_size); } } } drop: disconnect(conn); return 1; }
static int pptp_read(struct triton_md_handler_t *h) { struct pptp_conn_t *conn=container_of(h,typeof(*conn),hnd); struct pptp_header *hdr=(struct pptp_header *)conn->in_buf; int n; while(1) { n = read(h->fd, conn->in_buf + conn->in_size, PPTP_CTRL_SIZE_MAX - conn->in_size); if (n < 0) { if (errno == EINTR) continue; if (errno == EAGAIN) return 0; log_ppp_error("pptp: read: %s\n",strerror(errno)); goto drop; } if (n == 0) { if (conf_verbose) log_ppp_info2("pptp: disconnect by peer\n"); goto drop; } conn->in_size += n; if (conn->in_size >= sizeof(*hdr)) { if (hdr->magic != htonl(PPTP_MAGIC)) { log_ppp_error("pptp: invalid magic\n"); goto drop; } if (ntohs(hdr->length) >= PPTP_CTRL_SIZE_MAX) { log_ppp_error("pptp: message is too long\n"); goto drop; } if (ntohs(hdr->length) > conn->in_size) continue; if (ntohs(hdr->length) <= conn->in_size) { if (ntohs(hdr->length) != PPTP_CTRL_SIZE(ntohs(hdr->ctrl_type))) { log_ppp_error("pptp: invalid message length\n"); goto drop; } if (process_packet(conn)) goto drop; conn->in_size -= ntohs(hdr->length); if (conn->in_size) memmove(conn->in_buf, conn->in_buf + ntohs(hdr->length), conn->in_size); } } } drop: disconnect(conn); return 1; }
367,423
0
static int process_packet(struct pptp_conn_t *conn) { struct pptp_header *hdr = (struct pptp_header *)conn->in_buf; switch(ntohs(hdr->ctrl_type)) { case PPTP_START_CTRL_CONN_RQST: return pptp_start_ctrl_conn_rqst(conn); case PPTP_STOP_CTRL_CONN_RQST: return pptp_stop_ctrl_conn_rqst(conn); case PPTP_STOP_CTRL_CONN_RPLY: return pptp_stop_ctrl_conn_rply(conn); case PPTP_OUT_CALL_RQST: return pptp_out_call_rqst(conn); case PPTP_ECHO_RQST: return pptp_echo_rqst(conn); case PPTP_ECHO_RPLY: return pptp_echo_rply(conn); case PPTP_CALL_CLEAR_RQST: return pptp_call_clear_rqst(conn); case PPTP_SET_LINK_INFO: if (conf_verbose) log_ppp_info2("recv [PPTP Set-Link-Info]\n"); return 0; default: log_ppp_warn("recv [PPTP Unknown (%x)]\n", ntohs(hdr->ctrl_type)); } return 0; }
static int process_packet(struct pptp_conn_t *conn) { struct pptp_header *hdr = (struct pptp_header *)conn->in_buf; switch(ntohs(hdr->ctrl_type)) { case PPTP_START_CTRL_CONN_RQST: return pptp_start_ctrl_conn_rqst(conn); case PPTP_STOP_CTRL_CONN_RQST: return pptp_stop_ctrl_conn_rqst(conn); case PPTP_STOP_CTRL_CONN_RPLY: return pptp_stop_ctrl_conn_rply(conn); case PPTP_OUT_CALL_RQST: return pptp_out_call_rqst(conn); case PPTP_ECHO_RQST: return pptp_echo_rqst(conn); case PPTP_ECHO_RPLY: return pptp_echo_rply(conn); case PPTP_CALL_CLEAR_RQST: return pptp_call_clear_rqst(conn); case PPTP_SET_LINK_INFO: if (conf_verbose) log_ppp_info2("recv [PPTP Set-Link-Info]\n"); return 0; default: log_ppp_warn("recv [PPTP Unknown (%x)]\n", ntohs(hdr->ctrl_type)); } return 0; }
367,424
0
static int send_pptp_out_call_rply(struct pptp_conn_t *conn, struct pptp_out_call_rqst *rqst, int call_id, int res_code, int err_code) { struct pptp_out_call_rply msg = { .header = PPTP_HEADER_CTRL(PPTP_OUT_CALL_RPLY), .call_id = htons(call_id), .call_id_peer = rqst->call_id, .result_code = res_code, .error_code = err_code, .cause_code = 0, .speed = rqst->bps_max, .recv_size = rqst->recv_size, .delay = 0, .channel = 0, }; if (conf_verbose) log_ppp_info2("send [PPTP Outgoing-Call-Reply <Call-ID %x> <Peer-Call-ID %x> <Result %i> <Error %i> <Cause %i> <Speed %i> <Window-Size %i> <Delay %i> <Channel %x>]\n", ntohs(msg.call_id), ntohs(msg.call_id_peer), msg.result_code, msg.error_code, ntohs(msg.cause_code), ntohl(msg.speed), ntohs(msg.recv_size), ntohs(msg.delay), ntohl(msg.channel)); return post_msg(conn, &msg, sizeof(msg)); }
static int send_pptp_out_call_rply(struct pptp_conn_t *conn, struct pptp_out_call_rqst *rqst, int call_id, int res_code, int err_code) { struct pptp_out_call_rply msg = { .header = PPTP_HEADER_CTRL(PPTP_OUT_CALL_RPLY), .call_id = htons(call_id), .call_id_peer = rqst->call_id, .result_code = res_code, .error_code = err_code, .cause_code = 0, .speed = rqst->bps_max, .recv_size = rqst->recv_size, .delay = 0, .channel = 0, }; if (conf_verbose) log_ppp_info2("send [PPTP Outgoing-Call-Reply <Call-ID %x> <Peer-Call-ID %x> <Result %i> <Error %i> <Cause %i> <Speed %i> <Window-Size %i> <Delay %i> <Channel %x>]\n", ntohs(msg.call_id), ntohs(msg.call_id_peer), msg.result_code, msg.error_code, ntohs(msg.cause_code), ntohl(msg.speed), ntohs(msg.recv_size), ntohs(msg.delay), ntohl(msg.channel)); return post_msg(conn, &msg, sizeof(msg)); }
367,425
0
static int show_stat_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) { cli_send(client, "pptp:\r\n"); cli_sendv(client," starting: %u\r\n", stat_starting); cli_sendv(client," active: %u\r\n", stat_active); return CLI_CMD_OK; }
static int show_stat_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) { cli_send(client, "pptp:\r\n"); cli_sendv(client," starting: %u\r\n", stat_starting); cli_sendv(client," active: %u\r\n", stat_active); return CLI_CMD_OK; }
367,426
0
static int pptp_call_clear_rqst(struct pptp_conn_t *conn) { struct pptp_call_clear_rqst *rqst = (struct pptp_call_clear_rqst *)conn->in_buf; if (conf_verbose) log_ppp_info2("recv [PPTP Call-Clear-Request <Call-ID %x>]\n", ntohs(rqst->call_id)); if (conn->echo_timer.tpd) triton_timer_del(&conn->echo_timer); if (conn->state == STATE_PPP) { __sync_sub_and_fetch(&stat_active, 1); conn->state = STATE_CLOSE; ap_session_terminate(&conn->ppp.ses, TERM_USER_REQUEST, 1); } return send_pptp_call_disconnect_notify(conn, 4); }
static int pptp_call_clear_rqst(struct pptp_conn_t *conn) { struct pptp_call_clear_rqst *rqst = (struct pptp_call_clear_rqst *)conn->in_buf; if (conf_verbose) log_ppp_info2("recv [PPTP Call-Clear-Request <Call-ID %x>]\n", ntohs(rqst->call_id)); if (conn->echo_timer.tpd) triton_timer_del(&conn->echo_timer); if (conn->state == STATE_PPP) { __sync_sub_and_fetch(&stat_active, 1); conn->state = STATE_CLOSE; ap_session_terminate(&conn->ppp.ses, TERM_USER_REQUEST, 1); } return send_pptp_call_disconnect_notify(conn, 4); }
367,427
0
static void ppp_finished(struct ap_session *ses) { struct ppp_t *ppp = container_of(ses, typeof(*ppp), ses); struct pptp_conn_t *conn = container_of(ppp, typeof(*conn), ppp); if (conn->state != STATE_CLOSE) { log_ppp_debug("pptp: ppp finished\n"); conn->state = STATE_CLOSE; __sync_sub_and_fetch(&stat_active, 1); if (send_pptp_call_disconnect_notify(conn, 3)) triton_context_call(&conn->ctx, (void (*)(void*))disconnect, conn); else if (send_pptp_stop_ctrl_conn_rqst(conn, 0)) triton_context_call(&conn->ctx, (void (*)(void*))disconnect, conn); else { if (conn->timeout_timer.tpd) triton_timer_mod(&conn->timeout_timer, 0); else triton_timer_add(&conn->ctx, &conn->timeout_timer, 0); } } }
static void ppp_finished(struct ap_session *ses) { struct ppp_t *ppp = container_of(ses, typeof(*ppp), ses); struct pptp_conn_t *conn = container_of(ppp, typeof(*conn), ppp); if (conn->state != STATE_CLOSE) { log_ppp_debug("pptp: ppp finished\n"); conn->state = STATE_CLOSE; __sync_sub_and_fetch(&stat_active, 1); if (send_pptp_call_disconnect_notify(conn, 3)) triton_context_call(&conn->ctx, (void (*)(void*))disconnect, conn); else if (send_pptp_stop_ctrl_conn_rqst(conn, 0)) triton_context_call(&conn->ctx, (void (*)(void*))disconnect, conn); else { if (conn->timeout_timer.tpd) triton_timer_mod(&conn->timeout_timer, 0); else triton_timer_add(&conn->ctx, &conn->timeout_timer, 0); } } }
367,428
0
static int pptp_start_ctrl_conn_rqst(struct pptp_conn_t *conn) { struct pptp_start_ctrl_conn *msg = (struct pptp_start_ctrl_conn *)conn->in_buf; if (conf_verbose) log_ppp_info2("recv [PPTP Start-Ctrl-Conn-Request <Version %i> <Framing %x> <Bearer %x> <Max-Chan %i>]\n", msg->version, ntohl(msg->framing_cap), ntohl(msg->bearer_cap), ntohs(msg->max_channels)); if (conn->state != STATE_IDLE) { log_ppp_warn("unexpected PPTP_START_CTRL_CONN_RQST\n"); if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_EXISTS, 0)) return -1; return 0; } if (msg->version != htons(PPTP_VERSION)) { log_ppp_warn("PPTP version mismatch: expecting %x, received %" PRIu32 "\n", PPTP_VERSION, msg->version); if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_PROTOCOL, 0)) return -1; return 0; } /*if (!(ntohl(msg->framing_cap) & PPTP_FRAME_SYNC)) { log_ppp_warn("connection does not supports sync mode\n"); if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_GE, 0)) return -1; return 0; }*/ if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_SUCCESS, 0)) return -1; if (conn->timeout_timer.tpd) triton_timer_mod(&conn->timeout_timer, 0); conn->state = STATE_ESTB; return 0; }
static int pptp_start_ctrl_conn_rqst(struct pptp_conn_t *conn) { struct pptp_start_ctrl_conn *msg = (struct pptp_start_ctrl_conn *)conn->in_buf; if (conf_verbose) log_ppp_info2("recv [PPTP Start-Ctrl-Conn-Request <Version %i> <Framing %x> <Bearer %x> <Max-Chan %i>]\n", msg->version, ntohl(msg->framing_cap), ntohl(msg->bearer_cap), ntohs(msg->max_channels)); if (conn->state != STATE_IDLE) { log_ppp_warn("unexpected PPTP_START_CTRL_CONN_RQST\n"); if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_EXISTS, 0)) return -1; return 0; } if (msg->version != htons(PPTP_VERSION)) { log_ppp_warn("PPTP version mismatch: expecting %x, received %" PRIu32 "\n", PPTP_VERSION, msg->version); if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_PROTOCOL, 0)) return -1; return 0; } if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_SUCCESS, 0)) return -1; if (conn->timeout_timer.tpd) triton_timer_mod(&conn->timeout_timer, 0); conn->state = STATE_ESTB; return 0; }
367,429
0
static void pptp_timeout(struct triton_timer_t *t) { struct pptp_conn_t *conn = container_of(t, typeof(*conn), timeout_timer); disconnect(conn); }
static void pptp_timeout(struct triton_timer_t *t) { struct pptp_conn_t *conn = container_of(t, typeof(*conn), timeout_timer); disconnect(conn); }
367,430
0
static int pptp_stop_ctrl_conn_rqst(struct pptp_conn_t *conn) { struct pptp_stop_ctrl_conn *msg = (struct pptp_stop_ctrl_conn *)conn->in_buf; if (conf_verbose) log_ppp_info2("recv [PPTP Stop-Ctrl-Conn-Request <Reason %i>]\n", msg->reason_result); send_pptp_stop_ctrl_conn_rply(conn, PPTP_CONN_STOP_OK, 0); return -1; }
static int pptp_stop_ctrl_conn_rqst(struct pptp_conn_t *conn) { struct pptp_stop_ctrl_conn *msg = (struct pptp_stop_ctrl_conn *)conn->in_buf; if (conf_verbose) log_ppp_info2("recv [PPTP Stop-Ctrl-Conn-Request <Reason %i>]\n", msg->reason_result); send_pptp_stop_ctrl_conn_rply(conn, PPTP_CONN_STOP_OK, 0); return -1; }
367,433
0
static int pptp_connect(struct triton_md_handler_t *h) { struct sockaddr_in addr; socklen_t size = sizeof(addr); int sock; struct pptp_conn_t *conn; while(1) { sock = accept(h->fd, (struct sockaddr *)&addr, &size); if (sock < 0) { if (errno == EAGAIN) return 0; log_error("pptp: accept failed: %s\n", strerror(errno)); continue; } if (ap_shutdown) { close(sock); continue; } if (conf_max_starting && ap_session_stat.starting >= conf_max_starting) { close(sock); continue; } if (conf_max_sessions && ap_session_stat.active + ap_session_stat.starting >= conf_max_sessions) { close(sock); continue; } if (triton_module_loaded("connlimit") && connlimit_check(cl_key_from_ipv4(addr.sin_addr.s_addr))) { close(sock); continue; } log_info2("pptp: new connection from %s\n", inet_ntoa(addr.sin_addr)); if (iprange_client_check(addr.sin_addr.s_addr)) { log_warn("pptp: IP is out of client-ip-range, droping connection...\n"); close(sock); continue; } if (fcntl(sock, F_SETFL, O_NONBLOCK)) { log_error("pptp: failed to set nonblocking mode: %s, closing connection...\n", strerror(errno)); close(sock); continue; } conn = mempool_alloc(conn_pool); memset(conn, 0, sizeof(*conn)); conn->hnd.fd = sock; conn->hnd.read = pptp_read; conn->hnd.write = pptp_write; conn->ctx.close = pptp_close; conn->ctx.before_switch = pptp_ctx_switch; conn->in_buf = _malloc(PPTP_CTRL_SIZE_MAX); conn->out_buf = _malloc(PPTP_CTRL_SIZE_MAX); conn->timeout_timer.expire = pptp_timeout; conn->timeout_timer.period = conf_timeout * 1000; conn->echo_timer.expire = pptp_send_echo; conn->ctrl.ctx = &conn->ctx; conn->ctrl.started = ppp_started; conn->ctrl.finished = ppp_finished; conn->ctrl.terminate = ppp_terminate; conn->ctrl.max_mtu = conf_ppp_max_mtu; conn->ctrl.type = CTRL_TYPE_PPTP; conn->ctrl.ppp = 1; conn->ctrl.name = "pptp"; conn->ctrl.ifname = ""; conn->ctrl.mppe = conf_mppe; conn->ctrl.calling_station_id = _malloc(17); conn->ctrl.called_station_id = _malloc(17); u_inet_ntoa(addr.sin_addr.s_addr, conn->ctrl.calling_station_id); getsockname(sock, &addr, &size); u_inet_ntoa(addr.sin_addr.s_addr, conn->ctrl.called_station_id); ppp_init(&conn->ppp); conn->ppp.ses.ctrl = &conn->ctrl; if (conf_ip_pool) conn->ppp.ses.ipv4_pool_name = _strdup(conf_ip_pool); if (conf_ipv6_pool) conn->ppp.ses.ipv6_pool_name = _strdup(conf_ipv6_pool); if (conf_dpv6_pool) conn->ppp.ses.dpv6_pool_name = _strdup(conf_dpv6_pool); if (conf_ifname) conn->ppp.ses.ifname_rename = _strdup(conf_ifname); triton_context_register(&conn->ctx, &conn->ppp.ses); triton_md_register_handler(&conn->ctx, &conn->hnd); triton_md_enable_handler(&conn->hnd,MD_MODE_READ); triton_timer_add(&conn->ctx, &conn->timeout_timer, 0); triton_context_wakeup(&conn->ctx); triton_event_fire(EV_CTRL_STARTING, &conn->ppp.ses); __sync_add_and_fetch(&stat_starting, 1); } return 0; }
static int pptp_connect(struct triton_md_handler_t *h) { struct sockaddr_in addr; socklen_t size = sizeof(addr); int sock; struct pptp_conn_t *conn; while(1) { sock = accept(h->fd, (struct sockaddr *)&addr, &size); if (sock < 0) { if (errno == EAGAIN) return 0; log_error("pptp: accept failed: %s\n", strerror(errno)); continue; } if (ap_shutdown) { close(sock); continue; } if (conf_max_starting && ap_session_stat.starting >= conf_max_starting) { close(sock); continue; } if (conf_max_sessions && ap_session_stat.active + ap_session_stat.starting >= conf_max_sessions) { close(sock); continue; } if (triton_module_loaded("connlimit") && connlimit_check(cl_key_from_ipv4(addr.sin_addr.s_addr))) { close(sock); continue; } log_info2("pptp: new connection from %s\n", inet_ntoa(addr.sin_addr)); if (iprange_client_check(addr.sin_addr.s_addr)) { log_warn("pptp: IP is out of client-ip-range, droping connection...\n"); close(sock); continue; } if (fcntl(sock, F_SETFL, O_NONBLOCK)) { log_error("pptp: failed to set nonblocking mode: %s, closing connection...\n", strerror(errno)); close(sock); continue; } conn = mempool_alloc(conn_pool); memset(conn, 0, sizeof(*conn)); conn->hnd.fd = sock; conn->hnd.read = pptp_read; conn->hnd.write = pptp_write; conn->ctx.close = pptp_close; conn->ctx.before_switch = pptp_ctx_switch; conn->in_buf = _malloc(PPTP_CTRL_SIZE_MAX); conn->out_buf = _malloc(PPTP_CTRL_SIZE_MAX); conn->timeout_timer.expire = pptp_timeout; conn->timeout_timer.period = conf_timeout * 1000; conn->echo_timer.expire = pptp_send_echo; conn->ctrl.ctx = &conn->ctx; conn->ctrl.started = ppp_started; conn->ctrl.finished = ppp_finished; conn->ctrl.terminate = ppp_terminate; conn->ctrl.max_mtu = conf_ppp_max_mtu; conn->ctrl.type = CTRL_TYPE_PPTP; conn->ctrl.ppp = 1; conn->ctrl.name = "pptp"; conn->ctrl.ifname = ""; conn->ctrl.mppe = conf_mppe; conn->ctrl.calling_station_id = _malloc(17); conn->ctrl.called_station_id = _malloc(17); u_inet_ntoa(addr.sin_addr.s_addr, conn->ctrl.calling_station_id); getsockname(sock, &addr, &size); u_inet_ntoa(addr.sin_addr.s_addr, conn->ctrl.called_station_id); ppp_init(&conn->ppp); conn->ppp.ses.ctrl = &conn->ctrl; if (conf_ip_pool) conn->ppp.ses.ipv4_pool_name = _strdup(conf_ip_pool); if (conf_ipv6_pool) conn->ppp.ses.ipv6_pool_name = _strdup(conf_ipv6_pool); if (conf_dpv6_pool) conn->ppp.ses.dpv6_pool_name = _strdup(conf_dpv6_pool); if (conf_ifname) conn->ppp.ses.ifname_rename = _strdup(conf_ifname); triton_context_register(&conn->ctx, &conn->ppp.ses); triton_md_register_handler(&conn->ctx, &conn->hnd); triton_md_enable_handler(&conn->hnd,MD_MODE_READ); triton_timer_add(&conn->ctx, &conn->timeout_timer, 0); triton_context_wakeup(&conn->ctx); triton_event_fire(EV_CTRL_STARTING, &conn->ppp.ses); __sync_add_and_fetch(&stat_starting, 1); } return 0; }
367,434
0
void __export pptp_get_stat(unsigned int **starting, unsigned int **active) { *starting = &stat_starting; *active = &stat_active; }
void __export pptp_get_stat(unsigned int **starting, unsigned int **active) { *starting = &stat_starting; *active = &stat_active; }
367,435
0
static int pptp_echo_rqst(struct pptp_conn_t *conn) { struct pptp_echo_rqst *in_msg = (struct pptp_echo_rqst *)conn->in_buf; struct pptp_echo_rply out_msg = { .header = PPTP_HEADER_CTRL(PPTP_ECHO_RPLY), .identifier = in_msg->identifier, .result_code = 1, }; if (conf_verbose) { log_ppp_debug("recv [PPTP Echo-Request <Identifier %x>]\n", in_msg->identifier); log_ppp_debug("send [PPTP Echo-Reply <Identifier %x>]\n", out_msg.identifier); } if (conn->echo_timer.tpd) triton_timer_mod(&conn->echo_timer, 0); return post_msg(conn, &out_msg, sizeof(out_msg)); }
static int pptp_echo_rqst(struct pptp_conn_t *conn) { struct pptp_echo_rqst *in_msg = (struct pptp_echo_rqst *)conn->in_buf; struct pptp_echo_rply out_msg = { .header = PPTP_HEADER_CTRL(PPTP_ECHO_RPLY), .identifier = in_msg->identifier, .result_code = 1, }; if (conf_verbose) { log_ppp_debug("recv [PPTP Echo-Request <Identifier %x>]\n", in_msg->identifier); log_ppp_debug("send [PPTP Echo-Reply <Identifier %x>]\n", out_msg.identifier); } if (conn->echo_timer.tpd) triton_timer_mod(&conn->echo_timer, 0); return post_msg(conn, &out_msg, sizeof(out_msg)); }
367,436
0
static void pptp_send_echo(struct triton_timer_t *t) { struct pptp_conn_t *conn = container_of(t, typeof(*conn), echo_timer); struct pptp_echo_rqst msg = { .header = PPTP_HEADER_CTRL(PPTP_ECHO_RQST), }; if (++conn->echo_sent == conf_echo_failure) { log_ppp_warn("pptp: no echo reply\n"); disconnect(conn); return; } msg.identifier = random(); if (conf_verbose) log_ppp_debug("send [PPTP Echo-Request <Identifier %x>]\n", msg.identifier); if (post_msg(conn, &msg, sizeof(msg))) disconnect(conn); }
static void pptp_send_echo(struct triton_timer_t *t) { struct pptp_conn_t *conn = container_of(t, typeof(*conn), echo_timer); struct pptp_echo_rqst msg = { .header = PPTP_HEADER_CTRL(PPTP_ECHO_RQST), }; if (++conn->echo_sent == conf_echo_failure) { log_ppp_warn("pptp: no echo reply\n"); disconnect(conn); return; } msg.identifier = random(); if (conf_verbose) log_ppp_debug("send [PPTP Echo-Request <Identifier %x>]\n", msg.identifier); if (post_msg(conn, &msg, sizeof(msg))) disconnect(conn); }
367,437
0
static int send_pptp_call_disconnect_notify(struct pptp_conn_t *conn, int result) { struct pptp_call_clear_ntfy msg = { .header = PPTP_HEADER_CTRL(PPTP_CALL_CLEAR_NTFY), .call_id = htons(conn->peer_call_id), .result_code = result, .error_code = 0, .cause_code = 0, }; if (conf_verbose) log_ppp_info2("send [PPTP Call-Disconnect-Notify <Call-ID %x> <Result %i> <Error %i> <Cause %i>]\n", ntohs(msg.call_id), msg.result_code, msg.error_code, msg.cause_code); return post_msg(conn, &msg, sizeof(msg)); }
static int send_pptp_call_disconnect_notify(struct pptp_conn_t *conn, int result) { struct pptp_call_clear_ntfy msg = { .header = PPTP_HEADER_CTRL(PPTP_CALL_CLEAR_NTFY), .call_id = htons(conn->peer_call_id), .result_code = result, .error_code = 0, .cause_code = 0, }; if (conf_verbose) log_ppp_info2("send [PPTP Call-Disconnect-Notify <Call-ID %x> <Result %i> <Error %i> <Cause %i>]\n", ntohs(msg.call_id), msg.result_code, msg.error_code, msg.cause_code); return post_msg(conn, &msg, sizeof(msg)); }
367,438
0
static void RSAZ_exp52x20_x2_256(BN_ULONG *out, /* [2][20] */ const BN_ULONG *base, /* [2][20] */ const BN_ULONG *exp[2], /* 2x16 */ const BN_ULONG *m, /* [2][20] */ const BN_ULONG *rr, /* [2][20] */ const BN_ULONG k0[2]) { # define BITSIZE_MODULUS (1024) # define EXP_WIN_SIZE (5) # define EXP_WIN_MASK ((1U << EXP_WIN_SIZE) - 1) /* * Number of digits (64-bit words) in redundant representation to handle * modulus bits */ # define RED_DIGITS (20) # define EXP_DIGITS (16) # define DAMM ossl_rsaz_amm52x20_x2_256 /* * Squaring is done using multiplication now. That can be a subject of * optimization in future. */ # define DAMS(r,a,m,k0) \ ossl_rsaz_amm52x20_x2_256((r),(a),(a),(m),(k0)) /* Allocate stack for red(undant) result Y and multiplier X */ ALIGN64 BN_ULONG red_Y[2][RED_DIGITS]; ALIGN64 BN_ULONG red_X[2][RED_DIGITS]; /* Allocate expanded exponent */ ALIGN64 BN_ULONG expz[2][EXP_DIGITS + 1]; /* Pre-computed table of base powers */ ALIGN64 BN_ULONG red_table[1U << EXP_WIN_SIZE][2][RED_DIGITS]; int idx; memset(red_Y, 0, sizeof(red_Y)); memset(red_table, 0, sizeof(red_table)); memset(red_X, 0, sizeof(red_X)); /* * Compute table of powers base^i, i = 0, ..., (2^EXP_WIN_SIZE) - 1 * table[0] = mont(x^0) = mont(1) * table[1] = mont(x^1) = mont(x) */ red_X[0][0] = 1; red_X[1][0] = 1; DAMM(red_table[0][0], (const BN_ULONG*)red_X, rr, m, k0); DAMM(red_table[1][0], base, rr, m, k0); for (idx = 1; idx < (int)((1U << EXP_WIN_SIZE) / 2); idx++) { DAMS(red_table[2 * idx + 0][0], red_table[1 * idx][0], m, k0); DAMM(red_table[2 * idx + 1][0], red_table[2 * idx][0], red_table[1][0], m, k0); } /* Copy and expand exponents */ memcpy(expz[0], exp[0], EXP_DIGITS * sizeof(BN_ULONG)); expz[0][EXP_DIGITS] = 0; memcpy(expz[1], exp[1], EXP_DIGITS * sizeof(BN_ULONG)); expz[1][EXP_DIGITS] = 0; /* Exponentiation */ { const int rem = BITSIZE_MODULUS % EXP_WIN_SIZE; BN_ULONG table_idx_mask = EXP_WIN_MASK; int exp_bit_no = BITSIZE_MODULUS - rem; int exp_chunk_no = exp_bit_no / 64; int exp_chunk_shift = exp_bit_no % 64; BN_ULONG red_table_idx_0, red_table_idx_1; /* * If rem == 0, then * exp_bit_no = modulus_bitsize - exp_win_size * However, this isn't possible because rem is { 1024, 1536, 2048 } % 5 * which is { 4, 1, 3 } respectively. * * If this assertion ever fails the fix above is easy. */ OPENSSL_assert(rem != 0); /* Process 1-st exp window - just init result */ red_table_idx_0 = expz[0][exp_chunk_no]; red_table_idx_1 = expz[1][exp_chunk_no]; /* * The function operates with fixed moduli sizes divisible by 64, * thus table index here is always in supported range [0, EXP_WIN_SIZE). */ red_table_idx_0 >>= exp_chunk_shift; red_table_idx_1 >>= exp_chunk_shift; ossl_extract_multiplier_2x20_win5(red_Y[0], (const BN_ULONG*)red_table, (int)red_table_idx_0, 0); ossl_extract_multiplier_2x20_win5(red_Y[1], (const BN_ULONG*)red_table, (int)red_table_idx_1, 1); /* Process other exp windows */ for (exp_bit_no -= EXP_WIN_SIZE; exp_bit_no >= 0; exp_bit_no -= EXP_WIN_SIZE) { /* Extract pre-computed multiplier from the table */ { BN_ULONG T; exp_chunk_no = exp_bit_no / 64; exp_chunk_shift = exp_bit_no % 64; { red_table_idx_0 = expz[0][exp_chunk_no]; T = expz[0][exp_chunk_no + 1]; red_table_idx_0 >>= exp_chunk_shift; /* * Get additional bits from then next quadword * when 64-bit boundaries are crossed. */ if (exp_chunk_shift > 64 - EXP_WIN_SIZE) { T <<= (64 - exp_chunk_shift); red_table_idx_0 ^= T; } red_table_idx_0 &= table_idx_mask; ossl_extract_multiplier_2x20_win5(red_X[0], (const BN_ULONG*)red_table, (int)red_table_idx_0, 0); } { red_table_idx_1 = expz[1][exp_chunk_no]; T = expz[1][exp_chunk_no + 1]; red_table_idx_1 >>= exp_chunk_shift; /* * Get additional bits from then next quadword * when 64-bit boundaries are crossed. */ if (exp_chunk_shift > 64 - EXP_WIN_SIZE) { T <<= (64 - exp_chunk_shift); red_table_idx_1 ^= T; } red_table_idx_1 &= table_idx_mask; ossl_extract_multiplier_2x20_win5(red_X[1], (const BN_ULONG*)red_table, (int)red_table_idx_1, 1); } } /* Series of squaring */ DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); DAMM((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, (const BN_ULONG*)red_X, m, k0); } } /* * * NB: After the last AMM of exponentiation in Montgomery domain, the result * may be 1025-bit, but the conversion out of Montgomery domain performs an * AMM(x,1) which guarantees that the final result is less than |m|, so no * conditional subtraction is needed here. See "Efficient Software * Implementations of Modular Exponentiation" (by Shay Gueron) paper for details. */ /* Convert result back in regular 2^52 domain */ memset(red_X, 0, sizeof(red_X)); red_X[0][0] = 1; red_X[1][0] = 1; DAMM(out, (const BN_ULONG*)red_Y, (const BN_ULONG*)red_X, m, k0); /* Clear exponents */ OPENSSL_cleanse(expz, sizeof(expz)); OPENSSL_cleanse(red_Y, sizeof(red_Y)); # undef DAMS # undef DAMM # undef EXP_DIGITS # undef RED_DIGITS # undef EXP_WIN_MASK # undef EXP_WIN_SIZE # undef BITSIZE_MODULUS }
static void RSAZ_exp52x20_x2_256(BN_ULONG *out, const BN_ULONG *base, const BN_ULONG *exp[2], const BN_ULONG *m, const BN_ULONG *rr, const BN_ULONG k0[2]) { # define BITSIZE_MODULUS (1024) # define EXP_WIN_SIZE (5) # define EXP_WIN_MASK ((1U << EXP_WIN_SIZE) - 1) # define RED_DIGITS (20) # define EXP_DIGITS (16) # define DAMM ossl_rsaz_amm52x20_x2_256 # define DAMS(r,a,m,k0) \ ossl_rsaz_amm52x20_x2_256((r),(a),(a),(m),(k0)) ALIGN64 BN_ULONG red_Y[2][RED_DIGITS]; ALIGN64 BN_ULONG red_X[2][RED_DIGITS]; ALIGN64 BN_ULONG expz[2][EXP_DIGITS + 1]; ALIGN64 BN_ULONG red_table[1U << EXP_WIN_SIZE][2][RED_DIGITS]; int idx; memset(red_Y, 0, sizeof(red_Y)); memset(red_table, 0, sizeof(red_table)); memset(red_X, 0, sizeof(red_X)); red_X[0][0] = 1; red_X[1][0] = 1; DAMM(red_table[0][0], (const BN_ULONG*)red_X, rr, m, k0); DAMM(red_table[1][0], base, rr, m, k0); for (idx = 1; idx < (int)((1U << EXP_WIN_SIZE) / 2); idx++) { DAMS(red_table[2 * idx + 0][0], red_table[1 * idx][0], m, k0); DAMM(red_table[2 * idx + 1][0], red_table[2 * idx][0], red_table[1][0], m, k0); } memcpy(expz[0], exp[0], EXP_DIGITS * sizeof(BN_ULONG)); expz[0][EXP_DIGITS] = 0; memcpy(expz[1], exp[1], EXP_DIGITS * sizeof(BN_ULONG)); expz[1][EXP_DIGITS] = 0; { const int rem = BITSIZE_MODULUS % EXP_WIN_SIZE; BN_ULONG table_idx_mask = EXP_WIN_MASK; int exp_bit_no = BITSIZE_MODULUS - rem; int exp_chunk_no = exp_bit_no / 64; int exp_chunk_shift = exp_bit_no % 64; BN_ULONG red_table_idx_0, red_table_idx_1; OPENSSL_assert(rem != 0); red_table_idx_0 = expz[0][exp_chunk_no]; red_table_idx_1 = expz[1][exp_chunk_no]; red_table_idx_0 >>= exp_chunk_shift; red_table_idx_1 >>= exp_chunk_shift; ossl_extract_multiplier_2x20_win5(red_Y[0], (const BN_ULONG*)red_table, (int)red_table_idx_0, 0); ossl_extract_multiplier_2x20_win5(red_Y[1], (const BN_ULONG*)red_table, (int)red_table_idx_1, 1); for (exp_bit_no -= EXP_WIN_SIZE; exp_bit_no >= 0; exp_bit_no -= EXP_WIN_SIZE) { { BN_ULONG T; exp_chunk_no = exp_bit_no / 64; exp_chunk_shift = exp_bit_no % 64; { red_table_idx_0 = expz[0][exp_chunk_no]; T = expz[0][exp_chunk_no + 1]; red_table_idx_0 >>= exp_chunk_shift; if (exp_chunk_shift > 64 - EXP_WIN_SIZE) { T <<= (64 - exp_chunk_shift); red_table_idx_0 ^= T; } red_table_idx_0 &= table_idx_mask; ossl_extract_multiplier_2x20_win5(red_X[0], (const BN_ULONG*)red_table, (int)red_table_idx_0, 0); } { red_table_idx_1 = expz[1][exp_chunk_no]; T = expz[1][exp_chunk_no + 1]; red_table_idx_1 >>= exp_chunk_shift; if (exp_chunk_shift > 64 - EXP_WIN_SIZE) { T <<= (64 - exp_chunk_shift); red_table_idx_1 ^= T; } red_table_idx_1 &= table_idx_mask; ossl_extract_multiplier_2x20_win5(red_X[1], (const BN_ULONG*)red_table, (int)red_table_idx_1, 1); } } DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); DAMM((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, (const BN_ULONG*)red_X, m, k0); } } memset(red_X, 0, sizeof(red_X)); red_X[0][0] = 1; red_X[1][0] = 1; DAMM(out, (const BN_ULONG*)red_Y, (const BN_ULONG*)red_X, m, k0); OPENSSL_cleanse(expz, sizeof(expz)); OPENSSL_cleanse(red_Y, sizeof(red_Y)); # undef DAMS # undef DAMM # undef EXP_DIGITS # undef RED_DIGITS # undef EXP_WIN_MASK # undef EXP_WIN_SIZE # undef BITSIZE_MODULUS }
367,439
0
int ossl_rsaz_mod_exp_avx512_x2(BN_ULONG *res1, const BN_ULONG *base1, const BN_ULONG *exp1, const BN_ULONG *m1, const BN_ULONG *rr1, BN_ULONG k0_1, BN_ULONG *res2, const BN_ULONG *base2, const BN_ULONG *exp2, const BN_ULONG *m2, const BN_ULONG *rr2, BN_ULONG k0_2, int factor_size) { int ret = 0; /* * Number of word-size (BN_ULONG) digits to store exponent in redundant * representation. */ int exp_digits = number_of_digits(factor_size + 2, DIGIT_SIZE); int coeff_pow = 4 * (DIGIT_SIZE * exp_digits - factor_size); BN_ULONG *base1_red, *m1_red, *rr1_red; BN_ULONG *base2_red, *m2_red, *rr2_red; BN_ULONG *coeff_red; BN_ULONG *storage = NULL; BN_ULONG *storage_aligned = NULL; BN_ULONG storage_len_bytes = 7 * exp_digits * sizeof(BN_ULONG); /* AMM = Almost Montgomery Multiplication */ AMM52 amm = NULL; /* Dual (2-exps in parallel) exponentiation */ EXP52_x2 exp_x2 = NULL; const BN_ULONG *exp[2] = {0}; BN_ULONG k0[2] = {0}; /* Only 1024-bit factor size is supported now */ switch (factor_size) { case 1024: amm = ossl_rsaz_amm52x20_x1_256; exp_x2 = RSAZ_exp52x20_x2_256; break; default: goto err; } storage = (BN_ULONG *)OPENSSL_malloc(storage_len_bytes + 64); if (storage == NULL) goto err; storage_aligned = (BN_ULONG *)ALIGN_OF(storage, 64); /* Memory layout for red(undant) representations */ base1_red = storage_aligned; base2_red = storage_aligned + 1 * exp_digits; m1_red = storage_aligned + 2 * exp_digits; m2_red = storage_aligned + 3 * exp_digits; rr1_red = storage_aligned + 4 * exp_digits; rr2_red = storage_aligned + 5 * exp_digits; coeff_red = storage_aligned + 6 * exp_digits; /* Convert base_i, m_i, rr_i, from regular to 52-bit radix */ to_words52(base1_red, exp_digits, base1, factor_size); to_words52(base2_red, exp_digits, base2, factor_size); to_words52(m1_red, exp_digits, m1, factor_size); to_words52(m2_red, exp_digits, m2, factor_size); to_words52(rr1_red, exp_digits, rr1, factor_size); to_words52(rr2_red, exp_digits, rr2, factor_size); /* * Compute target domain Montgomery converters RR' for each modulus * based on precomputed original domain's RR. * * RR -> RR' transformation steps: * (1) coeff = 2^k * (2) t = AMM(RR,RR) = RR^2 / R' mod m * (3) RR' = AMM(t, coeff) = RR^2 * 2^k / R'^2 mod m * where * k = 4 * (52 * digits52 - modlen) * R = 2^(64 * ceil(modlen/64)) mod m * RR = R^2 mod M * R' = 2^(52 * ceil(modlen/52)) mod m * * modlen = 1024: k = 64, RR = 2^2048 mod m, RR' = 2^2080 mod m */ memset(coeff_red, 0, exp_digits * sizeof(BN_ULONG)); /* (1) in reduced domain representation */ set_bit(coeff_red, 64 * (int)(coeff_pow / 52) + coeff_pow % 52); amm(rr1_red, rr1_red, rr1_red, m1_red, k0_1); /* (2) for m1 */ amm(rr1_red, rr1_red, coeff_red, m1_red, k0_1); /* (3) for m1 */ amm(rr2_red, rr2_red, rr2_red, m2_red, k0_2); /* (2) for m2 */ amm(rr2_red, rr2_red, coeff_red, m2_red, k0_2); /* (3) for m2 */ exp[0] = exp1; exp[1] = exp2; k0[0] = k0_1; k0[1] = k0_2; exp_x2(rr1_red, base1_red, exp, m1_red, rr1_red, k0); /* Convert rr_i back to regular radix */ from_words52(res1, factor_size, rr1_red); from_words52(res2, factor_size, rr2_red); /* bn_reduce_once_in_place expects number of BN_ULONG, not bit size */ factor_size /= sizeof(BN_ULONG) * 8; bn_reduce_once_in_place(res1, /*carry=*/0, m1, storage, factor_size); bn_reduce_once_in_place(res2, /*carry=*/0, m2, storage, factor_size); ret = 1; err: if (storage != NULL) { OPENSSL_cleanse(storage, storage_len_bytes); OPENSSL_free(storage); } return ret; }
int ossl_rsaz_mod_exp_avx512_x2(BN_ULONG *res1, const BN_ULONG *base1, const BN_ULONG *exp1, const BN_ULONG *m1, const BN_ULONG *rr1, BN_ULONG k0_1, BN_ULONG *res2, const BN_ULONG *base2, const BN_ULONG *exp2, const BN_ULONG *m2, const BN_ULONG *rr2, BN_ULONG k0_2, int factor_size) { int ret = 0; int exp_digits = number_of_digits(factor_size + 2, DIGIT_SIZE); int coeff_pow = 4 * (DIGIT_SIZE * exp_digits - factor_size); BN_ULONG *base1_red, *m1_red, *rr1_red; BN_ULONG *base2_red, *m2_red, *rr2_red; BN_ULONG *coeff_red; BN_ULONG *storage = NULL; BN_ULONG *storage_aligned = NULL; BN_ULONG storage_len_bytes = 7 * exp_digits * sizeof(BN_ULONG); AMM52 amm = NULL; EXP52_x2 exp_x2 = NULL; const BN_ULONG *exp[2] = {0}; BN_ULONG k0[2] = {0}; switch (factor_size) { case 1024: amm = ossl_rsaz_amm52x20_x1_256; exp_x2 = RSAZ_exp52x20_x2_256; break; default: goto err; } storage = (BN_ULONG *)OPENSSL_malloc(storage_len_bytes + 64); if (storage == NULL) goto err; storage_aligned = (BN_ULONG *)ALIGN_OF(storage, 64); base1_red = storage_aligned; base2_red = storage_aligned + 1 * exp_digits; m1_red = storage_aligned + 2 * exp_digits; m2_red = storage_aligned + 3 * exp_digits; rr1_red = storage_aligned + 4 * exp_digits; rr2_red = storage_aligned + 5 * exp_digits; coeff_red = storage_aligned + 6 * exp_digits; to_words52(base1_red, exp_digits, base1, factor_size); to_words52(base2_red, exp_digits, base2, factor_size); to_words52(m1_red, exp_digits, m1, factor_size); to_words52(m2_red, exp_digits, m2, factor_size); to_words52(rr1_red, exp_digits, rr1, factor_size); to_words52(rr2_red, exp_digits, rr2, factor_size); memset(coeff_red, 0, exp_digits * sizeof(BN_ULONG)); set_bit(coeff_red, 64 * (int)(coeff_pow / 52) + coeff_pow % 52); amm(rr1_red, rr1_red, rr1_red, m1_red, k0_1); amm(rr1_red, rr1_red, coeff_red, m1_red, k0_1); amm(rr2_red, rr2_red, rr2_red, m2_red, k0_2); amm(rr2_red, rr2_red, coeff_red, m2_red, k0_2); exp[0] = exp1; exp[1] = exp2; k0[0] = k0_1; k0[1] = k0_2; exp_x2(rr1_red, base1_red, exp, m1_red, rr1_red, k0); from_words52(res1, factor_size, rr1_red); from_words52(res2, factor_size, rr2_red); factor_size /= sizeof(BN_ULONG) * 8; bn_reduce_once_in_place(res1, 0, m1, storage, factor_size); bn_reduce_once_in_place(res2, 0, m2, storage, factor_size); ret = 1; err: if (storage != NULL) { OPENSSL_cleanse(storage, storage_len_bytes); OPENSSL_free(storage); } return ret; }
367,440
0
static void from_words52(BN_ULONG *out, int out_bitsize, const BN_ULONG *in) { int i; int out_len = BITS2WORD64_SIZE(out_bitsize); assert(out != NULL); assert(in != NULL); for (i = 0; i < out_len; i++) out[i] = 0; { uint8_t *out_str = (uint8_t *)out; for (; out_bitsize >= (2 * DIGIT_SIZE); out_bitsize -= (2 * DIGIT_SIZE), in += 2) { (*(uint64_t *)out_str) = in[0]; out_str += 6; (*(uint64_t *)out_str) ^= in[1] << 4; out_str += 7; } if (out_bitsize > DIGIT_SIZE) { put_digit52(out_str, 7, in[0]); out_str += 6; out_bitsize -= DIGIT_SIZE; put_digit52(out_str, BITS2WORD8_SIZE(out_bitsize), (in[1] << 4 | in[0] >> 48)); } else if (out_bitsize) { put_digit52(out_str, BITS2WORD8_SIZE(out_bitsize), in[0]); } } }
static void from_words52(BN_ULONG *out, int out_bitsize, const BN_ULONG *in) { int i; int out_len = BITS2WORD64_SIZE(out_bitsize); assert(out != NULL); assert(in != NULL); for (i = 0; i < out_len; i++) out[i] = 0; { uint8_t *out_str = (uint8_t *)out; for (; out_bitsize >= (2 * DIGIT_SIZE); out_bitsize -= (2 * DIGIT_SIZE), in += 2) { (*(uint64_t *)out_str) = in[0]; out_str += 6; (*(uint64_t *)out_str) ^= in[1] << 4; out_str += 7; } if (out_bitsize > DIGIT_SIZE) { put_digit52(out_str, 7, in[0]); out_str += 6; out_bitsize -= DIGIT_SIZE; put_digit52(out_str, BITS2WORD8_SIZE(out_bitsize), (in[1] << 4 | in[0] >> 48)); } else if (out_bitsize) { put_digit52(out_str, BITS2WORD8_SIZE(out_bitsize), in[0]); } } }
367,441
0
static ossl_inline uint64_t get_digit52(const uint8_t *in, int in_len) { uint64_t digit = 0; assert(in != NULL); for (; in_len > 0; in_len--) { digit <<= 8; digit += (uint64_t)(in[in_len - 1]); } return digit; }
static ossl_inline uint64_t get_digit52(const uint8_t *in, int in_len) { uint64_t digit = 0; assert(in != NULL); for (; in_len > 0; in_len--) { digit <<= 8; digit += (uint64_t)(in[in_len - 1]); } return digit; }
367,442
0
void Dispatcher::onEvent(cl_event event, cl_int status, Device & d) { if (status != CL_COMPLETE) { std::cout << "Dispatcher::onEvent - Got bad status: " << status << std::endl; } else if (d.m_eventFinished != NULL) { initContinue(d); } else { ++d.m_round; handleResult(d); bool bDispatch = true; { std::lock_guard<std::mutex> lock(m_mutex); d.m_speed.sample(m_size); printSpeed(); if( m_quit ) { bDispatch = false; if(--m_countRunning == 0) { clSetUserEventStatus(m_eventFinished, CL_COMPLETE); } } } if (bDispatch) { dispatch(d); } } }
void Dispatcher::onEvent(cl_event event, cl_int status, Device & d) { if (status != CL_COMPLETE) { std::cout << "Dispatcher::onEvent - Got bad status: " << status << std::endl; } else if (d.m_eventFinished != NULL) { initContinue(d); } else { ++d.m_round; handleResult(d); bool bDispatch = true; { std::lock_guard<std::mutex> lock(m_mutex); d.m_speed.sample(m_size); printSpeed(); if( m_quit ) { bDispatch = false; if(--m_countRunning == 0) { clSetUserEventStatus(m_eventFinished, CL_COMPLETE); } } } if (bDispatch) { dispatch(d); } } }
367,445
0
void Dispatcher::initBegin(Device & d) { // Set mode data for (auto i = 0; i < 20; ++i) { d.m_memData1[i] = m_mode.data1[i]; d.m_memData2[i] = m_mode.data2[i]; } // Write precompute table and mode data d.m_memPrecomp.write(true); d.m_memData1.write(true); d.m_memData2.write(true); // Kernel arguments - profanity_begin d.m_memPrecomp.setKernelArg(d.m_kernelInit, 0); d.m_memPointsDeltaX.setKernelArg(d.m_kernelInit, 1); d.m_memPrevLambda.setKernelArg(d.m_kernelInit, 2); d.m_memResult.setKernelArg(d.m_kernelInit, 3); CLMemory<cl_ulong4>::setKernelArg(d.m_kernelInit, 4, d.m_clSeed); // Kernel arguments - profanity_inverse d.m_memPointsDeltaX.setKernelArg(d.m_kernelInverse, 0); d.m_memInversedNegativeDoubleGy.setKernelArg(d.m_kernelInverse, 1); // Kernel arguments - profanity_iterate d.m_memPointsDeltaX.setKernelArg(d.m_kernelIterate, 0); d.m_memInversedNegativeDoubleGy.setKernelArg(d.m_kernelIterate, 1); d.m_memPrevLambda.setKernelArg(d.m_kernelIterate, 2); // Kernel arguments - profanity_transform_* if(d.m_kernelTransform) { d.m_memInversedNegativeDoubleGy.setKernelArg(d.m_kernelTransform, 0); } // Kernel arguments - profanity_score_* d.m_memInversedNegativeDoubleGy.setKernelArg(d.m_kernelScore, 0); d.m_memResult.setKernelArg(d.m_kernelScore, 1); d.m_memData1.setKernelArg(d.m_kernelScore, 2); d.m_memData2.setKernelArg(d.m_kernelScore, 3); CLMemory<cl_uchar>::setKernelArg(d.m_kernelScore, 4, d.m_clScoreMax); // Updated in handleResult() // Seed device initContinue(d); }
void Dispatcher::initBegin(Device & d) { for (auto i = 0; i < 20; ++i) { d.m_memData1[i] = m_mode.data1[i]; d.m_memData2[i] = m_mode.data2[i]; } d.m_memPrecomp.write(true); d.m_memData1.write(true); d.m_memData2.write(true); d.m_memPrecomp.setKernelArg(d.m_kernelInit, 0); d.m_memPointsDeltaX.setKernelArg(d.m_kernelInit, 1); d.m_memPrevLambda.setKernelArg(d.m_kernelInit, 2); d.m_memResult.setKernelArg(d.m_kernelInit, 3); CLMemory<cl_ulong4>::setKernelArg(d.m_kernelInit, 4, d.m_clSeed); d.m_memPointsDeltaX.setKernelArg(d.m_kernelInverse, 0); d.m_memInversedNegativeDoubleGy.setKernelArg(d.m_kernelInverse, 1); d.m_memPointsDeltaX.setKernelArg(d.m_kernelIterate, 0); d.m_memInversedNegativeDoubleGy.setKernelArg(d.m_kernelIterate, 1); d.m_memPrevLambda.setKernelArg(d.m_kernelIterate, 2); if(d.m_kernelTransform) { d.m_memInversedNegativeDoubleGy.setKernelArg(d.m_kernelTransform, 0); } d.m_memInversedNegativeDoubleGy.setKernelArg(d.m_kernelScore, 0); d.m_memResult.setKernelArg(d.m_kernelScore, 1); d.m_memData1.setKernelArg(d.m_kernelScore, 2); d.m_memData2.setKernelArg(d.m_kernelScore, 3); CLMemory<cl_uchar>::setKernelArg(d.m_kernelScore, 4, d.m_clScoreMax); initContinue(d); }
367,446
0
void Dispatcher::addDevice(cl_device_id clDeviceId, const size_t worksizeLocal, const size_t index) { Device * pDevice = new Device(*this, m_clContext, m_clProgram, clDeviceId, worksizeLocal, m_size, index, m_mode); m_vDevices.push_back(pDevice); }
void Dispatcher::addDevice(cl_device_id clDeviceId, const size_t worksizeLocal, const size_t index) { Device * pDevice = new Device(*this, m_clContext, m_clProgram, clDeviceId, worksizeLocal, m_size, index, m_mode); m_vDevices.push_back(pDevice); }
367,448
0
bool printResult(const cl_int err) { std::cout << ((err != CL_SUCCESS) ? toString(err) : "OK") << std::endl; return err != CL_SUCCESS; }
bool printResult(const cl_int err) { std::cout << ((err != CL_SUCCESS) ? toString(err) : "OK") << std::endl; return err != CL_SUCCESS; }
367,450
0
void Dispatcher::run() { m_eventFinished = clCreateUserEvent(m_clContext, NULL); timeStart = std::chrono::steady_clock::now(); init(); const auto timeInitialization = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - timeStart).count(); std::cout << "Initialization time: " << timeInitialization << " seconds" << std::endl; m_quit = false; m_countRunning = m_vDevices.size(); std::cout << "Running..." << std::endl; std::cout << " Always verify that a private key generated by this program corresponds to the" << std::endl; std::cout << " public key printed by importing it to a wallet of your choice. This program" << std::endl; std::cout << " like any software might contain bugs and it does by design cut corners to" << std::endl; std::cout << " improve overall performance." << std::endl; std::cout << std::endl; for (auto it = m_vDevices.begin(); it != m_vDevices.end(); ++it) { dispatch(*(*it)); } clWaitForEvents(1, &m_eventFinished); clReleaseEvent(m_eventFinished); m_eventFinished = NULL; }
void Dispatcher::run() { m_eventFinished = clCreateUserEvent(m_clContext, NULL); timeStart = std::chrono::steady_clock::now(); init(); const auto timeInitialization = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - timeStart).count(); std::cout << "Initialization time: " << timeInitialization << " seconds" << std::endl; m_quit = false; m_countRunning = m_vDevices.size(); std::cout << "Running..." << std::endl; std::cout << " Always verify that a private key generated by this program corresponds to the" << std::endl; std::cout << " public key printed by importing it to a wallet of your choice. This program" << std::endl; std::cout << " like any software might contain bugs and it does by design cut corners to" << std::endl; std::cout << " improve overall performance." << std::endl; std::cout << std::endl; for (auto it = m_vDevices.begin(); it != m_vDevices.end(); ++it) { dispatch(*(*it)); } clWaitForEvents(1, &m_eventFinished); clReleaseEvent(m_eventFinished); m_eventFinished = NULL; }
367,453
0
std::vector<std::string> getBinaries(cl_program & clProgram) { std::vector<std::string> vReturn; auto vSizes = clGetWrapperVector<size_t>(clGetProgramInfo, clProgram, CL_PROGRAM_BINARY_SIZES); if (!vSizes.empty()) { unsigned char * * pBuffers = new unsigned char *[vSizes.size()]; for (size_t i = 0; i < vSizes.size(); ++i) { pBuffers[i] = new unsigned char[vSizes[i]]; } clGetProgramInfo(clProgram, CL_PROGRAM_BINARIES, vSizes.size() * sizeof(unsigned char *), pBuffers, NULL); for (size_t i = 0; i < vSizes.size(); ++i) { std::string strData(reinterpret_cast<char *>(pBuffers[i]), vSizes[i]); vReturn.push_back(strData); delete[] pBuffers[i]; } delete[] pBuffers; } return vReturn; }
std::vector<std::string> getBinaries(cl_program & clProgram) { std::vector<std::string> vReturn; auto vSizes = clGetWrapperVector<size_t>(clGetProgramInfo, clProgram, CL_PROGRAM_BINARY_SIZES); if (!vSizes.empty()) { unsigned char * * pBuffers = new unsigned char *[vSizes.size()]; for (size_t i = 0; i < vSizes.size(); ++i) { pBuffers[i] = new unsigned char[vSizes[i]]; } clGetProgramInfo(clProgram, CL_PROGRAM_BINARIES, vSizes.size() * sizeof(unsigned char *), pBuffers, NULL); for (size_t i = 0; i < vSizes.size(); ++i) { std::string strData(reinterpret_cast<char *>(pBuffers[i]), vSizes[i]); vReturn.push_back(strData); delete[] pBuffers[i]; } delete[] pBuffers; } return vReturn; }
367,455
0
std::string clGetWrapperString(U function, V param, W param2) { size_t len; function(param, param2, 0, NULL, &len); char * const szString = new char[len]; function(param, param2, len, szString, NULL); std::string r(szString); delete[] szString; return r; }
std::string clGetWrapperString(U function, V param, W param2) { size_t len; function(param, param2, 0, NULL, &len); char * const szString = new char[len]; function(param, param2, len, szString, NULL); std::string r(szString); delete[] szString; return r; }
367,458
0
void Dispatcher::printSpeed() { ++m_countPrint; if( m_countPrint > m_vDevices.size() ) { std::string strGPUs; double speedTotal = 0; unsigned int i = 0; for (auto & e : m_vDevices) { const auto curSpeed = e->m_speed.getSpeed(); speedTotal += curSpeed; strGPUs += " GPU" + toString(e->m_index) + ": " + formatSpeed(curSpeed); ++i; } const std::string strVT100ClearLine = "\33[2K\r"; std::cerr << strVT100ClearLine << "Total: " << formatSpeed(speedTotal) << " -" << strGPUs << '\r' << std::flush; m_countPrint = 0; } }
void Dispatcher::printSpeed() { ++m_countPrint; if( m_countPrint > m_vDevices.size() ) { std::string strGPUs; double speedTotal = 0; unsigned int i = 0; for (auto & e : m_vDevices) { const auto curSpeed = e->m_speed.getSpeed(); speedTotal += curSpeed; strGPUs += " GPU" + toString(e->m_index) + ": " + formatSpeed(curSpeed); ++i; } const std::string strVT100ClearLine = "\33[2K\r"; std::cerr << strVT100ClearLine << "Total: " << formatSpeed(speedTotal) << " -" << strGPUs << '\r' << std::flush; m_countPrint = 0; } }
367,459
0
std::string readFile(const char * const szFilename) { std::ifstream in(szFilename, std::ios::in | std::ios::binary); std::ostringstream contents; contents << in.rdbuf(); return contents.str(); }
std::string readFile(const char * const szFilename) { std::ifstream in(szFilename, std::ios::in | std::ios::binary); std::ostringstream contents; contents << in.rdbuf(); return contents.str(); }
367,460
0
std::string getDeviceCacheFilename(cl_device_id & d, const size_t & inverseSize) { const auto uniqueId = getUniqueDeviceIdentifier(d); return "cache-opencl." + toString(inverseSize) + "." + toString(uniqueId); }
std::string getDeviceCacheFilename(cl_device_id & d, const size_t & inverseSize) { const auto uniqueId = getUniqueDeviceIdentifier(d); return "cache-opencl." + toString(inverseSize) + "." + toString(uniqueId); }
367,461
0
unsigned int getUniqueDeviceIdentifier(const cl_device_id & deviceId) { #if defined(CL_DEVICE_TOPOLOGY_AMD) auto topology = clGetWrapper<cl_device_topology_amd>(clGetDeviceInfo, deviceId, CL_DEVICE_TOPOLOGY_AMD); if (topology.raw.type == CL_DEVICE_TOPOLOGY_TYPE_PCIE_AMD) { return (topology.pcie.bus << 16) + (topology.pcie.device << 8) + topology.pcie.function; } #endif cl_int bus_id = clGetWrapper<cl_int>(clGetDeviceInfo, deviceId, CL_DEVICE_PCI_BUS_ID_NV); cl_int slot_id = clGetWrapper<cl_int>(clGetDeviceInfo, deviceId, CL_DEVICE_PCI_SLOT_ID_NV); return (bus_id << 16) + slot_id; }
unsigned int getUniqueDeviceIdentifier(const cl_device_id & deviceId) { #if defined(CL_DEVICE_TOPOLOGY_AMD) auto topology = clGetWrapper<cl_device_topology_amd>(clGetDeviceInfo, deviceId, CL_DEVICE_TOPOLOGY_AMD); if (topology.raw.type == CL_DEVICE_TOPOLOGY_TYPE_PCIE_AMD) { return (topology.pcie.bus << 16) + (topology.pcie.device << 8) + topology.pcie.function; } #endif cl_int bus_id = clGetWrapper<cl_int>(clGetDeviceInfo, deviceId, CL_DEVICE_PCI_BUS_ID_NV); cl_int slot_id = clGetWrapper<cl_int>(clGetDeviceInfo, deviceId, CL_DEVICE_PCI_SLOT_ID_NV); return (bus_id << 16) + slot_id; }
367,462
0
void Dispatcher::dispatch(Device & d) { cl_event event; d.m_memResult.read(false, &event); #ifdef PROFANITY_DEBUG cl_event eventInverse; cl_event eventIterate; enqueueKernelDevice(d, d.m_kernelInverse, m_size / m_inverseSize, &eventInverse); enqueueKernelDevice(d, d.m_kernelIterate, m_size, &eventIterate); #else enqueueKernelDevice(d, d.m_kernelInverse, m_size / m_inverseSize); enqueueKernelDevice(d, d.m_kernelIterate, m_size); #endif if (d.m_kernelTransform) { enqueueKernelDevice(d, d.m_kernelTransform, m_size); } enqueueKernelDevice(d, d.m_kernelScore, m_size); clFlush(d.m_clQueue); #ifdef PROFANITY_DEBUG // We're actually not allowed to call clFinish here because this function is ultimately asynchronously called by OpenCL. // However, this happens to work on my computer and it's not really intended for release, just something to aid me in // optimizations. clFinish(d.m_clQueue); std::cout << "Timing: profanity_inverse = " << getKernelExecutionTimeMicros(eventInverse) << "us, profanity_iterate = " << getKernelExecutionTimeMicros(eventIterate) << "us" << std::endl; #endif const auto res = clSetEventCallback(event, CL_COMPLETE, staticCallback, &d); OpenCLException::throwIfError("failed to set custom callback", res); }
void Dispatcher::dispatch(Device & d) { cl_event event; d.m_memResult.read(false, &event); #ifdef PROFANITY_DEBUG cl_event eventInverse; cl_event eventIterate; enqueueKernelDevice(d, d.m_kernelInverse, m_size / m_inverseSize, &eventInverse); enqueueKernelDevice(d, d.m_kernelIterate, m_size, &eventIterate); #else enqueueKernelDevice(d, d.m_kernelInverse, m_size / m_inverseSize); enqueueKernelDevice(d, d.m_kernelIterate, m_size); #endif if (d.m_kernelTransform) { enqueueKernelDevice(d, d.m_kernelTransform, m_size); } enqueueKernelDevice(d, d.m_kernelScore, m_size); clFlush(d.m_clQueue); #ifdef PROFANITY_DEBUG clFinish(d.m_clQueue); std::cout << "Timing: profanity_inverse = " << getKernelExecutionTimeMicros(eventInverse) << "us, profanity_iterate = " << getKernelExecutionTimeMicros(eventIterate) << "us" << std::endl; #endif const auto res = clSetEventCallback(event, CL_COMPLETE, staticCallback, &d); OpenCLException::throwIfError("failed to set custom callback", res); }
367,463
0
Dispatcher::OpenCLException::OpenCLException(const std::string s, const cl_int res) : std::runtime_error( s + " (res = " + toString(res) + ")"), m_res(res) { }
Dispatcher::OpenCLException::OpenCLException(const std::string s, const cl_int res) : std::runtime_error( s + " (res = " + toString(res) + ")"), m_res(res) { }
367,464
0
std::vector<T> clGetWrapperVector(U function, V param, W param2) { size_t len; function(param, param2, 0, NULL, &len); len /= sizeof(T); std::vector<T> v; if (len > 0) { T * pArray = new T[len]; function(param, param2, len * sizeof(T), pArray, NULL); for (size_t i = 0; i < len; ++i) { v.push_back(pArray[i]); } delete[] pArray; } return v; }
std::vector<T> clGetWrapperVector(U function, V param, W param2) { size_t len; function(param, param2, 0, NULL, &len); len /= sizeof(T); std::vector<T> v; if (len > 0) { T * pArray = new T[len]; function(param, param2, len * sizeof(T), pArray, NULL); for (size_t i = 0; i < len; ++i) { v.push_back(pArray[i]); } delete[] pArray; } return v; }
367,465
0
void Dispatcher::initContinue(Device & d) { size_t sizeLeft = m_size - d.m_sizeInitialized; const size_t sizeInitLimit = m_size / 20; // Print progress const size_t percentDone = m_sizeInitDone * 100 / m_sizeInitTotal; std::cout << " " << percentDone << "%\r" << std::flush; if (sizeLeft) { cl_event event; const size_t sizeRun = std::min(sizeInitLimit, std::min(sizeLeft, m_worksizeMax)); const auto resEnqueue = clEnqueueNDRangeKernel(d.m_clQueue, d.m_kernelInit, 1, &d.m_sizeInitialized, &sizeRun, NULL, 0, NULL, &event); OpenCLException::throwIfError("kernel queueing failed during initilization", resEnqueue); // See: https://www.khronos.org/registry/OpenCL/sdk/1.2/docs/man/xhtml/clSetEventCallback.html // If an application needs to wait for completion of a routine from the above list in a callback, please use the non-blocking form of the function, and // assign a completion callback to it to do the remainder of your work. Note that when a callback (or other code) enqueues commands to a command-queue, // the commands are not required to begin execution until the queue is flushed. In standard usage, blocking enqueue calls serve this role by implicitly // flushing the queue. Since blocking calls are not permitted in callbacks, those callbacks that enqueue commands on a command queue should either call // clFlush on the queue before returning or arrange for clFlush to be called later on another thread. clFlush(d.m_clQueue); std::lock_guard<std::mutex> lock(m_mutex); d.m_sizeInitialized += sizeRun; m_sizeInitDone += sizeRun; const auto resCallback = clSetEventCallback(event, CL_COMPLETE, staticCallback, &d); OpenCLException::throwIfError("failed to set custom callback during initialization", resCallback); } else { // Printing one whole string at once helps in avoiding garbled output when executed in parallell const std::string strOutput = " GPU" + toString(d.m_index) + " initialized"; std::cout << strOutput << std::endl; clSetUserEventStatus(d.m_eventFinished, CL_COMPLETE); } }
void Dispatcher::initContinue(Device & d) { size_t sizeLeft = m_size - d.m_sizeInitialized; const size_t sizeInitLimit = m_size / 20; const size_t percentDone = m_sizeInitDone * 100 / m_sizeInitTotal; std::cout << " " << percentDone << "%\r" << std::flush; if (sizeLeft) { cl_event event; const size_t sizeRun = std::min(sizeInitLimit, std::min(sizeLeft, m_worksizeMax)); const auto resEnqueue = clEnqueueNDRangeKernel(d.m_clQueue, d.m_kernelInit, 1, &d.m_sizeInitialized, &sizeRun, NULL, 0, NULL, &event); OpenCLException::throwIfError("kernel queueing failed during initilization", resEnqueue); clFlush(d.m_clQueue); std::lock_guard<std::mutex> lock(m_mutex); d.m_sizeInitialized += sizeRun; m_sizeInitDone += sizeRun; const auto resCallback = clSetEventCallback(event, CL_COMPLETE, staticCallback, &d); OpenCLException::throwIfError("failed to set custom callback during initialization", resCallback); } else { const std::string strOutput = " GPU" + toString(d.m_index) + " initialized"; std::cout << strOutput << std::endl; clSetUserEventStatus(d.m_eventFinished, CL_COMPLETE); } }
367,466
0
std::vector<cl_device_id> getAllDevices(cl_device_type deviceType = CL_DEVICE_TYPE_GPU) { std::vector<cl_device_id> vDevices; cl_uint platformIdCount = 0; clGetPlatformIDs (0, NULL, &platformIdCount); std::vector<cl_platform_id> platformIds (platformIdCount); clGetPlatformIDs (platformIdCount, platformIds.data (), NULL); for( auto it = platformIds.cbegin(); it != platformIds.cend(); ++it ) { cl_uint countDevice; clGetDeviceIDs(*it, deviceType, 0, NULL, &countDevice); std::vector<cl_device_id> deviceIds(countDevice); clGetDeviceIDs(*it, deviceType, countDevice, deviceIds.data(), &countDevice); std::copy( deviceIds.begin(), deviceIds.end(), std::back_inserter(vDevices) ); } return vDevices; }
std::vector<cl_device_id> getAllDevices(cl_device_type deviceType = CL_DEVICE_TYPE_GPU) { std::vector<cl_device_id> vDevices; cl_uint platformIdCount = 0; clGetPlatformIDs (0, NULL, &platformIdCount); std::vector<cl_platform_id> platformIds (platformIdCount); clGetPlatformIDs (platformIdCount, platformIds.data (), NULL); for( auto it = platformIds.cbegin(); it != platformIds.cend(); ++it ) { cl_uint countDevice; clGetDeviceIDs(*it, deviceType, 0, NULL, &countDevice); std::vector<cl_device_id> deviceIds(countDevice); clGetDeviceIDs(*it, deviceType, countDevice, deviceIds.data(), &countDevice); std::copy( deviceIds.begin(), deviceIds.end(), std::back_inserter(vDevices) ); } return vDevices; }
367,467
0
static void printResult(cl_ulong4 seed, cl_ulong round, result r, cl_uchar score, const std::chrono::time_point<std::chrono::steady_clock> & timeStart, const Mode & mode) { // Time delta const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - timeStart).count(); // Format private key cl_ulong carry = 0; cl_ulong4 seedRes; seedRes.s[0] = seed.s[0] + round; carry = seedRes.s[0] < round; seedRes.s[1] = seed.s[1] + carry; carry = !seedRes.s[1]; seedRes.s[2] = seed.s[2] + carry; carry = !seedRes.s[2]; seedRes.s[3] = seed.s[3] + carry + r.foundId; std::ostringstream ss; ss << std::hex << std::setfill('0'); ss << std::setw(16) << seedRes.s[3] << std::setw(16) << seedRes.s[2] << std::setw(16) << seedRes.s[1] << std::setw(16) << seedRes.s[0]; const std::string strPrivate = ss.str(); // Format public key const std::string strPublic = toHex(r.foundHash, 20); // Print const std::string strVT100ClearLine = "\33[2K\r"; std::cout << strVT100ClearLine << " Time: " << std::setw(5) << seconds << "s Score: " << std::setw(2) << (int) score << " Private: 0x" << strPrivate << ' '; std::cout << mode.transformName(); std::cout << ": 0x" << strPublic << std::endl; }
static void printResult(cl_ulong4 seed, cl_ulong round, result r, cl_uchar score, const std::chrono::time_point<std::chrono::steady_clock> & timeStart, const Mode & mode) { const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - timeStart).count(); cl_ulong carry = 0; cl_ulong4 seedRes; seedRes.s[0] = seed.s[0] + round; carry = seedRes.s[0] < round; seedRes.s[1] = seed.s[1] + carry; carry = !seedRes.s[1]; seedRes.s[2] = seed.s[2] + carry; carry = !seedRes.s[2]; seedRes.s[3] = seed.s[3] + carry + r.foundId; std::ostringstream ss; ss << std::hex << std::setfill('0'); ss << std::setw(16) << seedRes.s[3] << std::setw(16) << seedRes.s[2] << std::setw(16) << seedRes.s[1] << std::setw(16) << seedRes.s[0]; const std::string strPrivate = ss.str(); const std::string strPublic = toHex(r.foundHash, 20); const std::string strVT100ClearLine = "\33[2K\r"; std::cout << strVT100ClearLine << " Time: " << std::setw(5) << seconds << "s Score: " << std::setw(2) << (int) score << " Private: 0x" << strPrivate << ' '; std::cout << mode.transformName(); std::cout << ": 0x" << strPublic << std::endl; }
367,468
0
void Dispatcher::init() { std::cout << "Initializing devices..." << std::endl; std::cout << " This should take less than a minute. The number of objects initialized on each" << std::endl; std::cout << " device is equal to inverse-size * inverse-multiple. To lower" << std::endl; std::cout << " initialization time (and memory footprint) I suggest lowering the" << std::endl; std::cout << " inverse-multiple first. You can do this via the -I switch. Do note that" << std::endl; std::cout << " this might negatively impact your performance." << std::endl; std::cout << std::endl; const auto deviceCount = m_vDevices.size(); m_sizeInitTotal = m_size * deviceCount; m_sizeInitDone = 0; cl_event * const pInitEvents = new cl_event[deviceCount]; for (size_t i = 0; i < deviceCount; ++i) { pInitEvents[i] = clCreateUserEvent(m_clContext, NULL); m_vDevices[i]->m_eventFinished = pInitEvents[i]; initBegin(*m_vDevices[i]); } clWaitForEvents(deviceCount, pInitEvents); for (size_t i = 0; i < deviceCount; ++i) { m_vDevices[i]->m_eventFinished = NULL; clReleaseEvent(pInitEvents[i]); } delete[] pInitEvents; std::cout << std::endl; }
void Dispatcher::init() { std::cout << "Initializing devices..." << std::endl; std::cout << " This should take less than a minute. The number of objects initialized on each" << std::endl; std::cout << " device is equal to inverse-size * inverse-multiple. To lower" << std::endl; std::cout << " initialization time (and memory footprint) I suggest lowering the" << std::endl; std::cout << " inverse-multiple first. You can do this via the -I switch. Do note that" << std::endl; std::cout << " this might negatively impact your performance." << std::endl; std::cout << std::endl; const auto deviceCount = m_vDevices.size(); m_sizeInitTotal = m_size * deviceCount; m_sizeInitDone = 0; cl_event * const pInitEvents = new cl_event[deviceCount]; for (size_t i = 0; i < deviceCount; ++i) { pInitEvents[i] = clCreateUserEvent(m_clContext, NULL); m_vDevices[i]->m_eventFinished = pInitEvents[i]; initBegin(*m_vDevices[i]); } clWaitForEvents(deviceCount, pInitEvents); for (size_t i = 0; i < deviceCount; ++i) { m_vDevices[i]->m_eventFinished = NULL; clReleaseEvent(pInitEvents[i]); } delete[] pInitEvents; std::cout << std::endl; }
367,469
0
cl_command_queue Dispatcher::Device::createQueue(cl_context & clContext, cl_device_id & clDeviceId) { // nVidia CUDA Toolkit 10.1 only supports OpenCL 1.2 so we revert back to older functions for compatability #ifdef PROFANITY_DEBUG cl_command_queue_properties p = CL_QUEUE_PROFILING_ENABLE; #else cl_command_queue_properties p = NULL; #endif #ifdef CL_VERSION_2_0 const cl_command_queue ret = clCreateCommandQueueWithProperties(clContext, clDeviceId, &p, NULL); #else const cl_command_queue ret = clCreateCommandQueue(clContext, clDeviceId, p, NULL); #endif return ret == NULL ? throw std::runtime_error("failed to create command queue") : ret; }
cl_command_queue Dispatcher::Device::createQueue(cl_context & clContext, cl_device_id & clDeviceId) { #ifdef PROFANITY_DEBUG cl_command_queue_properties p = CL_QUEUE_PROFILING_ENABLE; #else cl_command_queue_properties p = NULL; #endif #ifdef CL_VERSION_2_0 const cl_command_queue ret = clCreateCommandQueueWithProperties(clContext, clDeviceId, &p, NULL); #else const cl_command_queue ret = clCreateCommandQueue(clContext, clDeviceId, p, NULL); #endif return ret == NULL ? throw std::runtime_error("failed to create command queue") : ret; }
367,470
0
void Dispatcher::handleResult(Device & d) { for (auto i = PROFANITY_MAX_SCORE; i > m_clScoreMax; --i) { result & r = d.m_memResult[i]; if (r.found > 0 && i >= d.m_clScoreMax) { d.m_clScoreMax = i; CLMemory<cl_uchar>::setKernelArg(d.m_kernelScore, 4, d.m_clScoreMax); std::lock_guard<std::mutex> lock(m_mutex); if (i >= m_clScoreMax) { m_clScoreMax = i; if (m_clScoreQuit && i >= m_clScoreQuit) { m_quit = true; } printResult(d.m_clSeed, d.m_round, r, i, timeStart, m_mode); } break; } } }
void Dispatcher::handleResult(Device & d) { for (auto i = PROFANITY_MAX_SCORE; i > m_clScoreMax; --i) { result & r = d.m_memResult[i]; if (r.found > 0 && i >= d.m_clScoreMax) { d.m_clScoreMax = i; CLMemory<cl_uchar>::setKernelArg(d.m_kernelScore, 4, d.m_clScoreMax); std::lock_guard<std::mutex> lock(m_mutex); if (i >= m_clScoreMax) { m_clScoreMax = i; if (m_clScoreQuit && i >= m_clScoreQuit) { m_quit = true; } printResult(d.m_clSeed, d.m_round, r, i, timeStart, m_mode); } break; } } }
367,471
0
template <typename T> bool printResult(const T & t, const cl_int & err) { std::cout << ((t == NULL) ? toString(err) : "OK") << std::endl; return t == NULL; }
template <typename T> bool printResult(const T & t, const cl_int & err) { std::cout << ((t == NULL) ? toString(err) : "OK") << std::endl; return t == NULL; }
367,472
0
void CL_CALLBACK Dispatcher::staticCallback(cl_event event, cl_int event_command_exec_status, void * user_data) { Device * const pDevice = static_cast<Device *>(user_data); pDevice->m_parent.onEvent(event, event_command_exec_status, *pDevice); clReleaseEvent(event); }
void CL_CALLBACK Dispatcher::staticCallback(cl_event event, cl_int event_command_exec_status, void * user_data) { Device * const pDevice = static_cast<Device *>(user_data); pDevice->m_parent.onEvent(event, event_command_exec_status, *pDevice); clReleaseEvent(event); }
367,473
0
int main(int argc, char * * argv) { // THIS LINE WILL LEAD TO A COMPILE ERROR. THIS TOOL SHOULD NOT BE USED, SEE README. try { ArgParser argp(argc, argv); bool bHelp = false; bool bModeBenchmark = false; bool bModeZeros = false; bool bModeLetters = false; bool bModeNumbers = false; std::string strModeLeading; std::string strModeMatching; bool bModeLeadingRange = false; bool bModeRange = false; bool bModeMirror = false; bool bModeDoubles = false; int rangeMin = 0; int rangeMax = 0; std::vector<size_t> vDeviceSkipIndex; size_t worksizeLocal = 64; size_t worksizeMax = 0; // Will be automatically determined later if not overriden by user bool bNoCache = false; size_t inverseSize = 255; size_t inverseMultiple = 16384; bool bMineContract = false; argp.addSwitch('h', "help", bHelp); argp.addSwitch('0', "benchmark", bModeBenchmark); argp.addSwitch('1', "zeros", bModeZeros); argp.addSwitch('2', "letters", bModeLetters); argp.addSwitch('3', "numbers", bModeNumbers); argp.addSwitch('4', "leading", strModeLeading); argp.addSwitch('5', "matching", strModeMatching); argp.addSwitch('6', "leading-range", bModeLeadingRange); argp.addSwitch('7', "range", bModeRange); argp.addSwitch('8', "mirror", bModeMirror); argp.addSwitch('9', "leading-doubles", bModeDoubles); argp.addSwitch('m', "min", rangeMin); argp.addSwitch('M', "max", rangeMax); argp.addMultiSwitch('s', "skip", vDeviceSkipIndex); argp.addSwitch('w', "work", worksizeLocal); argp.addSwitch('W', "work-max", worksizeMax); argp.addSwitch('n', "no-cache", bNoCache); argp.addSwitch('i', "inverse-size", inverseSize); argp.addSwitch('I', "inverse-multiple", inverseMultiple); argp.addSwitch('c', "contract", bMineContract); if (!argp.parse()) { std::cout << "error: bad arguments, try again :<" << std::endl; return 1; } if (bHelp) { std::cout << g_strHelp << std::endl; return 0; } Mode mode = Mode::benchmark(); if (bModeBenchmark) { mode = Mode::benchmark(); } else if (bModeZeros) { mode = Mode::zeros(); } else if (bModeLetters) { mode = Mode::letters(); } else if (bModeNumbers) { mode = Mode::numbers(); } else if (!strModeLeading.empty()) { mode = Mode::leading(strModeLeading.front()); } else if (!strModeMatching.empty()) { mode = Mode::matching(strModeMatching); } else if (bModeLeadingRange) { mode = Mode::leadingRange(rangeMin, rangeMax); } else if (bModeRange) { mode = Mode::range(rangeMin, rangeMax); } else if(bModeMirror) { mode = Mode::mirror(); } else if (bModeDoubles) { mode = Mode::doubles(); } else { std::cout << g_strHelp << std::endl; return 0; } std::cout << "Mode: " << mode.name << std::endl; if (bMineContract) { mode.target = CONTRACT; } else { mode.target = ADDRESS; } std::cout << "Target: " << mode.transformName() << std:: endl; std::vector<cl_device_id> vFoundDevices = getAllDevices(); std::vector<cl_device_id> vDevices; std::map<cl_device_id, size_t> mDeviceIndex; std::vector<std::string> vDeviceBinary; std::vector<size_t> vDeviceBinarySize; cl_int errorCode; bool bUsedCache = false; std::cout << "Devices:" << std::endl; for (size_t i = 0; i < vFoundDevices.size(); ++i) { // Ignore devices in skip index if (std::find(vDeviceSkipIndex.begin(), vDeviceSkipIndex.end(), i) != vDeviceSkipIndex.end()) { continue; } cl_device_id & deviceId = vFoundDevices[i]; const auto strName = clGetWrapperString(clGetDeviceInfo, deviceId, CL_DEVICE_NAME); const auto computeUnits = clGetWrapper<cl_uint>(clGetDeviceInfo, deviceId, CL_DEVICE_MAX_COMPUTE_UNITS); const auto globalMemSize = clGetWrapper<cl_ulong>(clGetDeviceInfo, deviceId, CL_DEVICE_GLOBAL_MEM_SIZE); bool precompiled = false; // Check if there's a prebuilt binary for this device and load it if(!bNoCache) { std::ifstream fileIn(getDeviceCacheFilename(deviceId, inverseSize), std::ios::binary); if (fileIn.is_open()) { vDeviceBinary.push_back(std::string((std::istreambuf_iterator<char>(fileIn)), std::istreambuf_iterator<char>())); vDeviceBinarySize.push_back(vDeviceBinary.back().size()); precompiled = true; } } std::cout << " GPU" << i << ": " << strName << ", " << globalMemSize << " bytes available, " << computeUnits << " compute units (precompiled = " << (precompiled ? "yes" : "no") << ")" << std::endl; vDevices.push_back(vFoundDevices[i]); mDeviceIndex[vFoundDevices[i]] = i; } if (vDevices.empty()) { return 1; } std::cout << std::endl; std::cout << "Initializing OpenCL..." << std::endl; std::cout << " Creating context..." << std::flush; auto clContext = clCreateContext( NULL, vDevices.size(), vDevices.data(), NULL, NULL, &errorCode); if (printResult(clContext, errorCode)) { return 1; } cl_program clProgram; if (vDeviceBinary.size() == vDevices.size()) { // Create program from binaries bUsedCache = true; std::cout << " Loading kernel from binary..." << std::flush; const unsigned char * * pKernels = new const unsigned char *[vDevices.size()]; for (size_t i = 0; i < vDeviceBinary.size(); ++i) { pKernels[i] = reinterpret_cast<const unsigned char *>(vDeviceBinary[i].data()); } cl_int * pStatus = new cl_int[vDevices.size()]; clProgram = clCreateProgramWithBinary(clContext, vDevices.size(), vDevices.data(), vDeviceBinarySize.data(), pKernels, pStatus, &errorCode); if(printResult(clProgram, errorCode)) { return 1; } } else { // Create a program from the kernel source std::cout << " Compiling kernel..." << std::flush; const std::string strKeccak = readFile("keccak.cl"); const std::string strVanity = readFile("profanity.cl"); const char * szKernels[] = { strKeccak.c_str(), strVanity.c_str() }; clProgram = clCreateProgramWithSource(clContext, sizeof(szKernels) / sizeof(char *), szKernels, NULL, &errorCode); if (printResult(clProgram, errorCode)) { return 1; } } // Build the program std::cout << " Building program..." << std::flush; const std::string strBuildOptions = "-D PROFANITY_INVERSE_SIZE=" + toString(inverseSize) + " -D PROFANITY_MAX_SCORE=" + toString(PROFANITY_MAX_SCORE); if (printResult(clBuildProgram(clProgram, vDevices.size(), vDevices.data(), strBuildOptions.c_str(), NULL, NULL))) { #ifdef PROFANITY_DEBUG std::cout << std::endl; std::cout << "build log:" << std::endl; size_t sizeLog; clGetProgramBuildInfo(clProgram, vDevices[0], CL_PROGRAM_BUILD_LOG, 0, NULL, &sizeLog); char * const szLog = new char[sizeLog]; clGetProgramBuildInfo(clProgram, vDevices[0], CL_PROGRAM_BUILD_LOG, sizeLog, szLog, NULL); std::cout << szLog << std::endl; delete[] szLog; #endif return 1; } // Save binary to improve future start times if( !bUsedCache && !bNoCache ) { std::cout << " Saving program..." << std::flush; auto binaries = getBinaries(clProgram); for (size_t i = 0; i < binaries.size(); ++i) { std::ofstream fileOut(getDeviceCacheFilename(vDevices[i], inverseSize), std::ios::binary); fileOut.write(binaries[i].data(), binaries[i].size()); } std::cout << "OK" << std::endl; } std::cout << std::endl; Dispatcher d(clContext, clProgram, mode, worksizeMax == 0 ? inverseSize * inverseMultiple : worksizeMax, inverseSize, inverseMultiple, 0); for (auto & i : vDevices) { d.addDevice(i, worksizeLocal, mDeviceIndex[i]); } d.run(); clReleaseContext(clContext); return 0; } catch (std::runtime_error & e) { std::cout << "std::runtime_error - " << e.what() << std::endl; } catch (...) { std::cout << "unknown exception occured" << std::endl; } return 1; }
int main(int argc, char * * argv) { try { ArgParser argp(argc, argv); bool bHelp = false; bool bModeBenchmark = false; bool bModeZeros = false; bool bModeLetters = false; bool bModeNumbers = false; std::string strModeLeading; std::string strModeMatching; bool bModeLeadingRange = false; bool bModeRange = false; bool bModeMirror = false; bool bModeDoubles = false; int rangeMin = 0; int rangeMax = 0; std::vector<size_t> vDeviceSkipIndex; size_t worksizeLocal = 64; size_t worksizeMax = 0; bool bNoCache = false; size_t inverseSize = 255; size_t inverseMultiple = 16384; bool bMineContract = false; argp.addSwitch('h', "help", bHelp); argp.addSwitch('0', "benchmark", bModeBenchmark); argp.addSwitch('1', "zeros", bModeZeros); argp.addSwitch('2', "letters", bModeLetters); argp.addSwitch('3', "numbers", bModeNumbers); argp.addSwitch('4', "leading", strModeLeading); argp.addSwitch('5', "matching", strModeMatching); argp.addSwitch('6', "leading-range", bModeLeadingRange); argp.addSwitch('7', "range", bModeRange); argp.addSwitch('8', "mirror", bModeMirror); argp.addSwitch('9', "leading-doubles", bModeDoubles); argp.addSwitch('m', "min", rangeMin); argp.addSwitch('M', "max", rangeMax); argp.addMultiSwitch('s', "skip", vDeviceSkipIndex); argp.addSwitch('w', "work", worksizeLocal); argp.addSwitch('W', "work-max", worksizeMax); argp.addSwitch('n', "no-cache", bNoCache); argp.addSwitch('i', "inverse-size", inverseSize); argp.addSwitch('I', "inverse-multiple", inverseMultiple); argp.addSwitch('c', "contract", bMineContract); if (!argp.parse()) { std::cout << "error: bad arguments, try again :<" << std::endl; return 1; } if (bHelp) { std::cout << g_strHelp << std::endl; return 0; } Mode mode = Mode::benchmark(); if (bModeBenchmark) { mode = Mode::benchmark(); } else if (bModeZeros) { mode = Mode::zeros(); } else if (bModeLetters) { mode = Mode::letters(); } else if (bModeNumbers) { mode = Mode::numbers(); } else if (!strModeLeading.empty()) { mode = Mode::leading(strModeLeading.front()); } else if (!strModeMatching.empty()) { mode = Mode::matching(strModeMatching); } else if (bModeLeadingRange) { mode = Mode::leadingRange(rangeMin, rangeMax); } else if (bModeRange) { mode = Mode::range(rangeMin, rangeMax); } else if(bModeMirror) { mode = Mode::mirror(); } else if (bModeDoubles) { mode = Mode::doubles(); } else { std::cout << g_strHelp << std::endl; return 0; } std::cout << "Mode: " << mode.name << std::endl; if (bMineContract) { mode.target = CONTRACT; } else { mode.target = ADDRESS; } std::cout << "Target: " << mode.transformName() << std:: endl; std::vector<cl_device_id> vFoundDevices = getAllDevices(); std::vector<cl_device_id> vDevices; std::map<cl_device_id, size_t> mDeviceIndex; std::vector<std::string> vDeviceBinary; std::vector<size_t> vDeviceBinarySize; cl_int errorCode; bool bUsedCache = false; std::cout << "Devices:" << std::endl; for (size_t i = 0; i < vFoundDevices.size(); ++i) { if (std::find(vDeviceSkipIndex.begin(), vDeviceSkipIndex.end(), i) != vDeviceSkipIndex.end()) { continue; } cl_device_id & deviceId = vFoundDevices[i]; const auto strName = clGetWrapperString(clGetDeviceInfo, deviceId, CL_DEVICE_NAME); const auto computeUnits = clGetWrapper<cl_uint>(clGetDeviceInfo, deviceId, CL_DEVICE_MAX_COMPUTE_UNITS); const auto globalMemSize = clGetWrapper<cl_ulong>(clGetDeviceInfo, deviceId, CL_DEVICE_GLOBAL_MEM_SIZE); bool precompiled = false; if(!bNoCache) { std::ifstream fileIn(getDeviceCacheFilename(deviceId, inverseSize), std::ios::binary); if (fileIn.is_open()) { vDeviceBinary.push_back(std::string((std::istreambuf_iterator<char>(fileIn)), std::istreambuf_iterator<char>())); vDeviceBinarySize.push_back(vDeviceBinary.back().size()); precompiled = true; } } std::cout << " GPU" << i << ": " << strName << ", " << globalMemSize << " bytes available, " << computeUnits << " compute units (precompiled = " << (precompiled ? "yes" : "no") << ")" << std::endl; vDevices.push_back(vFoundDevices[i]); mDeviceIndex[vFoundDevices[i]] = i; } if (vDevices.empty()) { return 1; } std::cout << std::endl; std::cout << "Initializing OpenCL..." << std::endl; std::cout << " Creating context..." << std::flush; auto clContext = clCreateContext( NULL, vDevices.size(), vDevices.data(), NULL, NULL, &errorCode); if (printResult(clContext, errorCode)) { return 1; } cl_program clProgram; if (vDeviceBinary.size() == vDevices.size()) { bUsedCache = true; std::cout << " Loading kernel from binary..." << std::flush; const unsigned char * * pKernels = new const unsigned char *[vDevices.size()]; for (size_t i = 0; i < vDeviceBinary.size(); ++i) { pKernels[i] = reinterpret_cast<const unsigned char *>(vDeviceBinary[i].data()); } cl_int * pStatus = new cl_int[vDevices.size()]; clProgram = clCreateProgramWithBinary(clContext, vDevices.size(), vDevices.data(), vDeviceBinarySize.data(), pKernels, pStatus, &errorCode); if(printResult(clProgram, errorCode)) { return 1; } } else { std::cout << " Compiling kernel..." << std::flush; const std::string strKeccak = readFile("keccak.cl"); const std::string strVanity = readFile("profanity.cl"); const char * szKernels[] = { strKeccak.c_str(), strVanity.c_str() }; clProgram = clCreateProgramWithSource(clContext, sizeof(szKernels) / sizeof(char *), szKernels, NULL, &errorCode); if (printResult(clProgram, errorCode)) { return 1; } } std::cout << " Building program..." << std::flush; const std::string strBuildOptions = "-D PROFANITY_INVERSE_SIZE=" + toString(inverseSize) + " -D PROFANITY_MAX_SCORE=" + toString(PROFANITY_MAX_SCORE); if (printResult(clBuildProgram(clProgram, vDevices.size(), vDevices.data(), strBuildOptions.c_str(), NULL, NULL))) { #ifdef PROFANITY_DEBUG std::cout << std::endl; std::cout << "build log:" << std::endl; size_t sizeLog; clGetProgramBuildInfo(clProgram, vDevices[0], CL_PROGRAM_BUILD_LOG, 0, NULL, &sizeLog); char * const szLog = new char[sizeLog]; clGetProgramBuildInfo(clProgram, vDevices[0], CL_PROGRAM_BUILD_LOG, sizeLog, szLog, NULL); std::cout << szLog << std::endl; delete[] szLog; #endif return 1; } if( !bUsedCache && !bNoCache ) { std::cout << " Saving program..." << std::flush; auto binaries = getBinaries(clProgram); for (size_t i = 0; i < binaries.size(); ++i) { std::ofstream fileOut(getDeviceCacheFilename(vDevices[i], inverseSize), std::ios::binary); fileOut.write(binaries[i].data(), binaries[i].size()); } std::cout << "OK" << std::endl; } std::cout << std::endl; Dispatcher d(clContext, clProgram, mode, worksizeMax == 0 ? inverseSize * inverseMultiple : worksizeMax, inverseSize, inverseMultiple, 0); for (auto & i : vDevices) { d.addDevice(i, worksizeLocal, mDeviceIndex[i]); } d.run(); clReleaseContext(clContext); return 0; } catch (std::runtime_error & e) { std::cout << "std::runtime_error - " << e.what() << std::endl; } catch (...) { std::cout << "unknown exception occured" << std::endl; } return 1; }
367,474
0
Dispatcher::Device::Device(Dispatcher & parent, cl_context & clContext, cl_program & clProgram, cl_device_id clDeviceId, const size_t worksizeLocal, const size_t size, const size_t index, const Mode & mode) : m_parent(parent), m_index(index), m_clDeviceId(clDeviceId), m_worksizeLocal(worksizeLocal), m_clScoreMax(0), m_clQueue(createQueue(clContext, clDeviceId) ), m_kernelInit( createKernel(clProgram, "profanity_init") ), m_kernelInverse(createKernel(clProgram, "profanity_inverse")), m_kernelIterate(createKernel(clProgram, "profanity_iterate")), m_kernelTransform( mode.transformKernel() == "" ? NULL : createKernel(clProgram, mode.transformKernel())), m_kernelScore(createKernel(clProgram, mode.kernel)), m_memPrecomp(clContext, m_clQueue, CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY, sizeof(g_precomp), g_precomp), m_memPointsDeltaX(clContext, m_clQueue, CL_MEM_READ_WRITE | CL_MEM_HOST_NO_ACCESS, size, true), m_memInversedNegativeDoubleGy(clContext, m_clQueue, CL_MEM_READ_WRITE | CL_MEM_HOST_NO_ACCESS, size, true), m_memPrevLambda(clContext, m_clQueue, CL_MEM_READ_WRITE | CL_MEM_HOST_NO_ACCESS, size, true), m_memResult(clContext, m_clQueue, CL_MEM_READ_WRITE | CL_MEM_HOST_READ_ONLY, PROFANITY_MAX_SCORE + 1), m_memData1(clContext, m_clQueue, CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY, 20), m_memData2(clContext, m_clQueue, CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY, 20), m_clSeed(createSeed()), m_round(0), m_speed(PROFANITY_SPEEDSAMPLES), m_sizeInitialized(0), m_eventFinished(NULL) { }
Dispatcher::Device::Device(Dispatcher & parent, cl_context & clContext, cl_program & clProgram, cl_device_id clDeviceId, const size_t worksizeLocal, const size_t size, const size_t index, const Mode & mode) : m_parent(parent), m_index(index), m_clDeviceId(clDeviceId), m_worksizeLocal(worksizeLocal), m_clScoreMax(0), m_clQueue(createQueue(clContext, clDeviceId) ), m_kernelInit( createKernel(clProgram, "profanity_init") ), m_kernelInverse(createKernel(clProgram, "profanity_inverse")), m_kernelIterate(createKernel(clProgram, "profanity_iterate")), m_kernelTransform( mode.transformKernel() == "" ? NULL : createKernel(clProgram, mode.transformKernel())), m_kernelScore(createKernel(clProgram, mode.kernel)), m_memPrecomp(clContext, m_clQueue, CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY, sizeof(g_precomp), g_precomp), m_memPointsDeltaX(clContext, m_clQueue, CL_MEM_READ_WRITE | CL_MEM_HOST_NO_ACCESS, size, true), m_memInversedNegativeDoubleGy(clContext, m_clQueue, CL_MEM_READ_WRITE | CL_MEM_HOST_NO_ACCESS, size, true), m_memPrevLambda(clContext, m_clQueue, CL_MEM_READ_WRITE | CL_MEM_HOST_NO_ACCESS, size, true), m_memResult(clContext, m_clQueue, CL_MEM_READ_WRITE | CL_MEM_HOST_READ_ONLY, PROFANITY_MAX_SCORE + 1), m_memData1(clContext, m_clQueue, CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY, 20), m_memData2(clContext, m_clQueue, CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY, 20), m_clSeed(createSeed()), m_round(0), m_speed(PROFANITY_SPEEDSAMPLES), m_sizeInitialized(0), m_eventFinished(NULL) { }
367,475
0
Dispatcher::~Dispatcher() { }
Dispatcher::~Dispatcher() { }
367,476
0
void Dispatcher::enqueueKernel(cl_command_queue & clQueue, cl_kernel & clKernel, size_t worksizeGlobal, const size_t worksizeLocal, cl_event * pEvent = NULL) { const size_t worksizeMax = m_worksizeMax; size_t worksizeOffset = 0; while (worksizeGlobal) { const size_t worksizeRun = std::min(worksizeGlobal, worksizeMax); const size_t * const pWorksizeLocal = (worksizeLocal == 0 ? NULL : &worksizeLocal); const auto res = clEnqueueNDRangeKernel(clQueue, clKernel, 1, &worksizeOffset, &worksizeRun, pWorksizeLocal, 0, NULL, pEvent); OpenCLException::throwIfError("kernel queueing failed", res); worksizeGlobal -= worksizeRun; worksizeOffset += worksizeRun; } }
void Dispatcher::enqueueKernel(cl_command_queue & clQueue, cl_kernel & clKernel, size_t worksizeGlobal, const size_t worksizeLocal, cl_event * pEvent = NULL) { const size_t worksizeMax = m_worksizeMax; size_t worksizeOffset = 0; while (worksizeGlobal) { const size_t worksizeRun = std::min(worksizeGlobal, worksizeMax); const size_t * const pWorksizeLocal = (worksizeLocal == 0 ? NULL : &worksizeLocal); const auto res = clEnqueueNDRangeKernel(clQueue, clKernel, 1, &worksizeOffset, &worksizeRun, pWorksizeLocal, 0, NULL, pEvent); OpenCLException::throwIfError("kernel queueing failed", res); worksizeGlobal -= worksizeRun; worksizeOffset += worksizeRun; } }
367,477
0
static std::string toHex(const uint8_t * const s, const size_t len) { std::string b("0123456789abcdef"); std::string r; for (size_t i = 0; i < len; ++i) { const unsigned char h = s[i] / 16; const unsigned char l = s[i] % 16; r = r + b.substr(h, 1) + b.substr(l, 1); } return r; }
static std::string toHex(const uint8_t * const s, const size_t len) { std::string b("0123456789abcdef"); std::string r; for (size_t i = 0; i < len; ++i) { const unsigned char h = s[i] / 16; const unsigned char l = s[i] % 16; r = r + b.substr(h, 1) + b.substr(l, 1); } return r; }
367,478
0
void Dispatcher::OpenCLException::OpenCLException::throwIfError(const std::string s, const cl_int res) { if (res != CL_SUCCESS) { throw OpenCLException(s, res); } }
void Dispatcher::OpenCLException::OpenCLException::throwIfError(const std::string s, const cl_int res) { if (res != CL_SUCCESS) { throw OpenCLException(s, res); } }
367,480
0
process(register int code, unsigned char** fill) { int incode; static unsigned char firstchar; if (code == clear) { codesize = datasize + 1; codemask = (1 << codesize) - 1; avail = clear + 2; oldcode = -1; return 1; } if (oldcode == -1) { if (code >= clear) { fprintf(stderr, "bad input: code=%d is larger than clear=%d\n",code, clear); return 0; } *(*fill)++ = suffix[code]; firstchar = oldcode = code; return 1; } if (code > avail) { fprintf(stderr, "code %d too large for %d\n", code, avail); return 0; } incode = code; if (code == avail) { /* the first code is always < avail */ *stackp++ = firstchar; code = oldcode; } while (code > clear) { *stackp++ = suffix[code]; code = prefix[code]; } *stackp++ = firstchar = suffix[code]; prefix[avail] = oldcode; suffix[avail] = firstchar; avail++; if (((avail & codemask) == 0) && (avail < 4096)) { codesize++; codemask += avail; } oldcode = incode; do { *(*fill)++ = *--stackp; } while (stackp > stack); return 1; }
process(register int code, unsigned char** fill) { int incode; static unsigned char firstchar; if (code == clear) { codesize = datasize + 1; codemask = (1 << codesize) - 1; avail = clear + 2; oldcode = -1; return 1; } if (oldcode == -1) { if (code >= clear) { fprintf(stderr, "bad input: code=%d is larger than clear=%d\n",code, clear); return 0; } *(*fill)++ = suffix[code]; firstchar = oldcode = code; return 1; } if (code > avail) { fprintf(stderr, "code %d too large for %d\n", code, avail); return 0; } incode = code; if (code == avail) { *stackp++ = firstchar; code = oldcode; } while (code > clear) { *stackp++ = suffix[code]; code = prefix[code]; } *stackp++ = firstchar = suffix[code]; prefix[avail] = oldcode; suffix[avail] = firstchar; avail++; if (((avail & codemask) == 0) && (avail < 4096)) { codesize++; codemask += avail; } oldcode = incode; do { *(*fill)++ = *--stackp; } while (stackp > stack); return 1; }
367,482
0
readraster(void) { unsigned char *fill = raster; unsigned char buf[255]; register int bits=0; register unsigned long datum=0; register unsigned char *ch; register int count, code; int status = 1; datasize = getc(infile); if (datasize > 12) return 0; clear = 1 << datasize; eoi = clear + 1; avail = clear + 2; oldcode = -1; codesize = datasize + 1; codemask = (1 << codesize) - 1; for (code = 0; code < clear; code++) { prefix[code] = 0; suffix[code] = code; } stackp = stack; for (count = getc(infile); count > 0; count = getc(infile)) { fread(buf,1,count,infile); for (ch=buf; count-- > 0; ch++) { datum += (unsigned long) *ch << bits; bits += 8; while (bits >= codesize) { code = datum & codemask; datum >>= codesize; bits -= codesize; if (code == eoi) { /* This kludge put in */ goto exitloop; /* because some GIF files*/ } /* aren't standard */ if (!process(code, &fill)) { status = 0; goto exitloop; } } } if (fill >= raster + width*height) { fprintf(stderr, "raster full before eoi code\n"); break; } } exitloop: if (fill != raster + width*height) { fprintf(stderr, "warning: wrong rastersize: %ld bytes\n", (long) (fill-raster)); fprintf(stderr, " instead of %ld bytes\n", (long) width*height); } return status; }
readraster(void) { unsigned char *fill = raster; unsigned char buf[255]; register int bits=0; register unsigned long datum=0; register unsigned char *ch; register int count, code; int status = 1; datasize = getc(infile); if (datasize > 12) return 0; clear = 1 << datasize; eoi = clear + 1; avail = clear + 2; oldcode = -1; codesize = datasize + 1; codemask = (1 << codesize) - 1; for (code = 0; code < clear; code++) { prefix[code] = 0; suffix[code] = code; } stackp = stack; for (count = getc(infile); count > 0; count = getc(infile)) { fread(buf,1,count,infile); for (ch=buf; count-- > 0; ch++) { datum += (unsigned long) *ch << bits; bits += 8; while (bits >= codesize) { code = datum & codemask; datum >>= codesize; bits -= codesize; if (code == eoi) { goto exitloop; } if (!process(code, &fill)) { status = 0; goto exitloop; } } } if (fill >= raster + width*height) { fprintf(stderr, "raster full before eoi code\n"); break; } } exitloop: if (fill != raster + width*height) { fprintf(stderr, "warning: wrong rastersize: %ld bytes\n", (long) (fill-raster)); fprintf(stderr, " instead of %ld bytes\n", (long) width*height); } return status; }
367,483
0
readscreen(void) { unsigned char buf[7]; fread(buf,1,7,infile); global = buf[4] & 0x80; if (global) { globalbits = (buf[4] & 0x07) + 1; fread(globalmap,3,((size_t)1)<<globalbits,infile); } }
readscreen(void) { unsigned char buf[7]; fread(buf,1,7,infile); global = buf[4] & 0x80; if (global) { globalbits = (buf[4] & 0x07) + 1; fread(globalmap,3,((size_t)1)<<globalbits,infile); } }
367,484
0
initcolors(unsigned char colormap[COLSIZE][3], int ncolors) { register int i; for (i = 0; i < ncolors; i++) { red[i] = gamtab[colormap[i][0]]; green[i] = gamtab[colormap[i][1]]; blue[i] = gamtab[colormap[i][2]]; } }
initcolors(unsigned char colormap[COLSIZE][3], int ncolors) { register int i; for (i = 0; i < ncolors; i++) { red[i] = gamtab[colormap[i][0]]; green[i] = gamtab[colormap[i][1]]; blue[i] = gamtab[colormap[i][2]]; } }
367,485
0
processCompressOptions(char* opt) { if (streq(opt, "none")) compression = COMPRESSION_NONE; else if (streq(opt, "packbits")) compression = COMPRESSION_PACKBITS; else if (strneq(opt, "lzw", 3)) { char* cp = strchr(opt, ':'); if (cp) predictor = atoi(cp+1); compression = COMPRESSION_LZW; } else if (strneq(opt, "zip", 3)) { char* cp = strchr(opt, ':'); if (cp) predictor = atoi(cp+1); compression = COMPRESSION_DEFLATE; } else return (0); return (1); }
processCompressOptions(char* opt) { if (streq(opt, "none")) compression = COMPRESSION_NONE; else if (streq(opt, "packbits")) compression = COMPRESSION_PACKBITS; else if (strneq(opt, "lzw", 3)) { char* cp = strchr(opt, ':'); if (cp) predictor = atoi(cp+1); compression = COMPRESSION_LZW; } else if (strneq(opt, "zip", 3)) { char* cp = strchr(opt, ':'); if (cp) predictor = atoi(cp+1); compression = COMPRESSION_DEFLATE; } else return (0); return (1); }
367,486
0
readextension(void) { int count; char buf[255]; (void) getc(infile); while ((count = getc(infile))) fread(buf, 1, count, infile); }
readextension(void) { int count; char buf[255]; (void) getc(infile); while ((count = getc(infile))) fread(buf, 1, count, infile); }
367,488
0
rasterize(int interleaved, char* mode) { register unsigned long row; unsigned char *newras; unsigned char *ras; TIFF *tif; tstrip_t strip; tsize_t stripsize; if ((newras = (unsigned char*) _TIFFmalloc(width*height+EXTRAFUDGE)) == NULL) { fprintf(stderr, "not enough memory for image\n"); return; } #define DRAWSEGMENT(offset, step) { \ for (row = offset; row < height; row += step) { \ _TIFFmemcpy(newras + row*width, ras, width);\ ras += width; \ } \ } ras = raster; if (interleaved) { DRAWSEGMENT(0, 8); DRAWSEGMENT(4, 8); DRAWSEGMENT(2, 4); DRAWSEGMENT(1, 2); } else DRAWSEGMENT(0, 1); #undef DRAWSEGMENT tif = TIFFOpen(imagename, mode); if (!tif) { TIFFError(imagename,"Can not open output image"); exit(-1); } TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, (uint32) width); TIFFSetField(tif, TIFFTAG_IMAGELENGTH, (uint32) height); TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE); TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1); TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8); TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip = TIFFDefaultStripSize(tif, rowsperstrip)); TIFFSetField(tif, TIFFTAG_COMPRESSION, compression); switch (compression) { case COMPRESSION_LZW: case COMPRESSION_DEFLATE: if (predictor != 0) TIFFSetField(tif, TIFFTAG_PREDICTOR, predictor); break; } TIFFSetField(tif, TIFFTAG_COLORMAP, red, green, blue); TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT); strip = 0; stripsize = TIFFStripSize(tif); for (row=0; row<height; row += rowsperstrip) { if (rowsperstrip > height-row) { rowsperstrip = height-row; stripsize = TIFFVStripSize(tif, rowsperstrip); } if (TIFFWriteEncodedStrip(tif, strip, newras+row*width, stripsize) < 0) break; strip++; } TIFFClose(tif); _TIFFfree(newras); }
rasterize(int interleaved, char* mode) { register unsigned long row; unsigned char *newras; unsigned char *ras; TIFF *tif; tstrip_t strip; tsize_t stripsize; if ((newras = (unsigned char*) _TIFFmalloc(width*height+EXTRAFUDGE)) == NULL) { fprintf(stderr, "not enough memory for image\n"); return; } #define DRAWSEGMENT(offset, step) { \ for (row = offset; row < height; row += step) { \ _TIFFmemcpy(newras + row*width, ras, width);\ ras += width; \ } \ } ras = raster; if (interleaved) { DRAWSEGMENT(0, 8); DRAWSEGMENT(4, 8); DRAWSEGMENT(2, 4); DRAWSEGMENT(1, 2); } else DRAWSEGMENT(0, 1); #undef DRAWSEGMENT tif = TIFFOpen(imagename, mode); if (!tif) { TIFFError(imagename,"Can not open output image"); exit(-1); } TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, (uint32) width); TIFFSetField(tif, TIFFTAG_IMAGELENGTH, (uint32) height); TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE); TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1); TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8); TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip = TIFFDefaultStripSize(tif, rowsperstrip)); TIFFSetField(tif, TIFFTAG_COMPRESSION, compression); switch (compression) { case COMPRESSION_LZW: case COMPRESSION_DEFLATE: if (predictor != 0) TIFFSetField(tif, TIFFTAG_PREDICTOR, predictor); break; } TIFFSetField(tif, TIFFTAG_COLORMAP, red, green, blue); TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT); strip = 0; stripsize = TIFFStripSize(tif); for (row=0; row<height; row += rowsperstrip) { if (rowsperstrip > height-row) { rowsperstrip = height-row; stripsize = TIFFVStripSize(tif, rowsperstrip); } if (TIFFWriteEncodedStrip(tif, strip, newras+row*width, stripsize) < 0) break; strip++; } TIFFClose(tif); _TIFFfree(newras); }
367,489
0
main(int argc, char* argv[]) { extern int optind; extern char *optarg; int c, status; while ((c = getopt(argc, argv, "c:r:")) != -1) switch (c) { case 'c': /* compression scheme */ if (!processCompressOptions(optarg)) usage(); break; case 'r': /* rows/strip */ rowsperstrip = atoi(optarg); break; case '?': usage(); /*NOTREACHED*/ } if (argc - optind != 2) usage(); makegamtab(GIFGAMMA); filename = argv[optind]; imagename = argv[optind+1]; if ((infile = fopen(imagename, "rb")) != NULL) { int c; fclose(infile); printf("overwrite %s? ", imagename); fflush(stdout); c = getc(stdin); if (c != 'y' && c != 'Y') return (1); } if ((infile = fopen(filename, "rb")) == NULL) { perror(filename); return (1); } status = convert(); fclose(infile); return (status); }
main(int argc, char* argv[]) { extern int optind; extern char *optarg; int c, status; while ((c = getopt(argc, argv, "c:r:")) != -1) switch (c) { case 'c': if (!processCompressOptions(optarg)) usage(); break; case 'r': rowsperstrip = atoi(optarg); break; case '?': usage(); } if (argc - optind != 2) usage(); makegamtab(GIFGAMMA); filename = argv[optind]; imagename = argv[optind+1]; if ((infile = fopen(imagename, "rb")) != NULL) { int c; fclose(infile); printf("overwrite %s? ", imagename); fflush(stdout); c = getc(stdin); if (c != 'y' && c != 'Y') return (1); } if ((infile = fopen(filename, "rb")) == NULL) { perror(filename); return (1); } status = convert(); fclose(infile); return (status); }
367,490
0
checksignature(void) { char buf[6]; fread(buf,1,6,infile); if (strncmp(buf,"GIF",3)) { fprintf(stderr, "file is not a GIF file\n"); return 0; } if (strncmp(&buf[3],"87a",3)) { fprintf(stderr, "unknown GIF version number\n"); return 0; } return 1; }
checksignature(void) { char buf[6]; fread(buf,1,6,infile); if (strncmp(buf,"GIF",3)) { fprintf(stderr, "file is not a GIF file\n"); return 0; } if (strncmp(&buf[3],"87a",3)) { fprintf(stderr, "unknown GIF version number\n"); return 0; } return 1; }
367,491
0
readgifimage(char* mode) { unsigned char buf[9]; int local, interleaved; unsigned char localmap[256][3]; int localbits; int status; if (fread(buf, 1, 9, infile) == 0) { perror(filename); return (0); } width = buf[4] + (buf[5] << 8); height = buf[6] + (buf[7] << 8); local = buf[8] & 0x80; interleaved = buf[8] & 0x40; if (local == 0 && global == 0) { fprintf(stderr, "no colormap present for image\n"); return (0); } if ((raster = (unsigned char*) _TIFFmalloc(width*height+EXTRAFUDGE)) == NULL) { fprintf(stderr, "not enough memory for image\n"); return (0); } if (local) { localbits = (buf[8] & 0x7) + 1; fprintf(stderr, " local colors: %d\n", 1<<localbits); fread(localmap, 3, ((size_t)1)<<localbits, infile); initcolors(localmap, 1<<localbits); } else if (global) { initcolors(globalmap, 1<<globalbits); } if ((status = readraster())) rasterize(interleaved, mode); _TIFFfree(raster); return status; }
readgifimage(char* mode) { unsigned char buf[9]; int local, interleaved; unsigned char localmap[256][3]; int localbits; int status; if (fread(buf, 1, 9, infile) == 0) { perror(filename); return (0); } width = buf[4] + (buf[5] << 8); height = buf[6] + (buf[7] << 8); local = buf[8] & 0x80; interleaved = buf[8] & 0x40; if (local == 0 && global == 0) { fprintf(stderr, "no colormap present for image\n"); return (0); } if ((raster = (unsigned char*) _TIFFmalloc(width*height+EXTRAFUDGE)) == NULL) { fprintf(stderr, "not enough memory for image\n"); return (0); } if (local) { localbits = (buf[8] & 0x7) + 1; fprintf(stderr, " local colors: %d\n", 1<<localbits); fread(localmap, 3, ((size_t)1)<<localbits, infile); initcolors(localmap, 1<<localbits); } else if (global) { initcolors(globalmap, 1<<globalbits); } if ((status = readraster())) rasterize(interleaved, mode); _TIFFfree(raster); return status; }
367,492
0
inline void set_stmt_row_injection() { DBUG_ENTER("set_stmt_row_injection"); binlog_stmt_flags|= (1U << BINLOG_STMT_TYPE_ROW_INJECTION); DBUG_VOID_RETURN; }
inline void set_stmt_row_injection() { DBUG_ENTER("set_stmt_row_injection"); binlog_stmt_flags|= (1U << BINLOG_STMT_TYPE_ROW_INJECTION); DBUG_VOID_RETURN; }
367,493