Import deployed 203 server source and external build dependencies

This commit is contained in:
shen
2026-10-14 19:18:21 -07:00
commit 4577d869fd
14839 changed files with 3058983 additions and 0 deletions
BIN
View File
Binary file not shown.
@@ -0,0 +1,28 @@
모든 서버 공통
외부접근 차단
ipfw delete 10000
천마 오픈
root: Ekwlwlak (한글로 따지지마)
ipfw add 10000 allow tcp from any to me dst-port 50000-60000 setup
ipfw add 10000 allow udp from any to me dst-port 50000-60000
ipfw add 10000 allow udp from me 50000-60000 to any
쾌도 오픈
root: webzen@2
ipfw add 10000 allow tcp from any to me dst-port 50000-60000 setup
ipfw add 10000 allow udp from any to me dst-port 50000-60000
ipfw add 10000 allow udp from me 50000-60000 to any
ipfw add 10000 allow udp from me 10000-20000 to any
웹서버 오픈
ipfw add 10000 allow tcp from any to me 80 setup
ipfw add 10000 allow tcp from any to me 444 setup
ipfw add 10000 allow tcp from any to me 443 setup
+21
View File
@@ -0,0 +1,21 @@
WELCOME_MSG = "DB Server has been started"
SQL_ACCOUNT = "10.1.89.23 ymir_account metin2 dhels 0"
SQL_PLAYER = "10.1.89.23 ymir_player metin2 dhels 0"
SQL_COMMON = "10.1.89.23 ymir_common metin2 dhels 0"
SQL_HOTBACKUP = "10.1.89.23 ymir_hotbackup metin2 dhels 0"
TABLE_POSTFIX = ""
BIND_PORT = 15900
DB_SLEEP_MSEC = 10
CLIENT_HEART_FPS = 10
HASH_PLAYER_LIFE_SEC = 600
BACKUP_LIMIT_SEC = 3600
PLAYER_ID_START = 100
PLAYER_DELETE_LEVEL_LIMIT = 70
ITEM_ID_RANGE = 2000000000 2100000000
#NAME_COLUMN = "gb2312name"
#LOCALE = "gb2312"
Binary file not shown.
+21
View File
@@ -0,0 +1,21 @@
WELCOME_MSG = "DB Server has been started"
SQL_ACCOUNT = "202.31.212.73 ymir_account ymir xptmxmelql1 0"
SQL_PLAYER = "202.31.212.73 ymir_player ymir xptmxmelql1 0"
SQL_COMMON = "202.31.212.73 ymir_common ymir xptmxmelql1 0"
SQL_HOTBACKUP = "202.31.212.73 ymir_hotbackup ymir xptmxmelql1 0"
TABLE_POSTFIX = ""
BIND_PORT = 15900
DB_SLEEP_MSEC = 10
CLIENT_HEART_FPS = 10
HASH_PLAYER_LIFE_SEC = 600
BACKUP_LIMIT_SEC = 3600
PLAYER_ID_START = 100
PLAYER_DELETE_LEVEL_LIMIT = 70
ITEM_ID_RANGE = 2000000000 2100000000
#NAME_COLUMN = "gb2312name"
#LOCALE = "gb2312"
+239
View File
@@ -0,0 +1,239 @@
# 용혼석 테이블들...
# TAB 으로 구분되니 엑셀로 볼 것.
# vim으로 본다면 탭간 간격을 조정하고 볼 것. (set ts=16 추천)
# 큰 따옴표로 묶인 부분은 안 구분.
# \" 이딴거 지원 안함.
# 용혼석 Vnum에 대한 comment
# ITEM VNUM을 10만 자리부터, FEDCBA라고 한다면
# FE : 용혼석 종류. D : 등급
# C : 단계 B : 강화
# A : 여벌의 번호들...
# 이 체계에서 벗어나는 용혼석은 용서하지 않을 것이다.
# ok?
# 용혼석이 너무나도 많기 때문에 Vnum이 중구난방이면,
# Special item group에서 group으로 묶어서 처리하기도 힘들고-_-,
# VnumHelper.h에서 처리하는 것도 힘들다. -_-
# Group 잡는데만 수천줄을 써야할 지도...
# Vnum에 체계를 잡아서 자릿수 기반으로 해야만 한다.
# Table은 "Group"과 "이름"으로 시작한다.
# Table 내부에 또 Table이 있을 수 있다.
# 그렇다고 엉뚱한 테이블을 써놓는다고 서버가 인식하는 것은 아니다.
# 필요한 테이블은 다음과 같다.
# BaseVnums, BaseAttrs, AddtionalAttrs, AttrSettings, UpgradeTable, ImproveTable,
# RefineTable, UpgradeMoneys, ImproveTable, RefineMoneys, WeightTable, DurationTable,
# DragonHeartExtTable, DragonSoulExtTable
Group BaseVnums
{
# 시작 vnum.
# 여기서 써야할 부분은 위에 설명한 FE에 해당하는 부분. 나머지는 써봐야 싹다 무시함.
# FE * 10000을 써줄 것 ok?
백룡석 110000
흑룡석 120000
...
}
Group BaseAttrs
{
Group 백룡석
{
# 순서값이 낮은 것 부터 부여된다.
# (개발자 comment : APPLY_어쩌고 이런거 읽어서 value로 변환해줘야함.)
# (졸라 귀찮아...)
# 순서 속성 값
1 APPLY_INT 10
2 APPLY_DEX 10
}
}
Group AddtionalAttrs
{
Group 백룡석
{
# 속성 값 확률
# 확률은 백분위가 아니라 전체 확률 값을 모두 더한 값에서의 비율만큼 적용된다.
APPLY_DEX 10 20
APPLY_STEAL_SP 10 30
APPLY_DEF_GRADE_BONUS 10 30
}
Group 흑룡석
{
...
}
}
# 등급에 따른 속성
# min ~ max. 오케이? (중간에 SPACE 있어도 되고 없어도 되고.)
Group AttrSettings
{
Group 백룡석
{
# 등급 1 2 3 4 5
기본 1 1 1 2 2
추가_min 0 0 0 0 0
추가_max 0 1 2 2 3
}
}
# 개량 table
Group UpgradeTable
{
# 변환등급
# 등급 필요개수 일반 화려 희귀 전설 고대
일반 20 70 25 5 0 0
화려 10 25 70 5 0 0
희귀 5 9.9 20 80 0.1 0
전설 3 1.9 3 5 90 0.1
}
Group ImproveTable
{
# 단계등급
# 단계 필요개수 최하급 하급 중급 상급 최상급
최하급 4 70 25 5 0 0
하급 3 25 70 5 0 0
중급 2 10 20 80 1 0
상급 1 2 3 5 90 1
}
Group RefineTable
{
# 강화 레벨
# 분류 1 2 3 4 5 6 7
일반 강화석 100 80 70 50 30 20 10
축복의 강화석 100 88 77 55 33 22 11
용신의 강화석 100 90 80 60 40 30 20
}
# special_item_group 읽으면, group_name도 저장할 것.
# group_name으로 "일반 강화석" 찾아서 쓸 것.
# 아래 Money 테이블들은 개량시 필요한 돈을 말함.
Group UpgradeMoneys
{
일반 10000
화려 15000
희귀 20000
전설 20000
}
Group ImproveTable
{
최하급 10000
하급 10000
중급 20000
상급 25000
}
Group RefineMoneys
{
1 1000
2 2000
3 3000
4 3000
5 3000
6 20000
}
# 용혼석 가중치 테이블.
# 이 테이블에서 값이 0이라면 그 이상의 강화는 불가능하다고 판단한다.
Group WeightTable
{
Group 일반
{
# 단계 강화
# 1 2 3 4 5 6 7
최하급 1 2 3 0 0 0 0    
하급 2 3 4 0 0 0 0
중급 3 4 5 6 0 0 0
상급 4 5 6 7 0 0 0
최상급 5 6 7 8 10 0 0
}
# 단계 강화
# 1 2 3 4 5 6 7
Group 화려
{
최하급 3 4 5 6 0 0 0
하급 4 5 6 8 0 0 0
중급 5 6 8 10 0 0 0
상급 6 8 10 12 15 0 0
최상급 8 10 12 15 20 0 0
}
# 단계 강화
# 1 2 3 4 5 6 7
Group 희귀
{
최하급 6 7 9 11 15 0 0
하급 7 9 11 15 20 0 0
중급 9 11 15 20 25 0 0
상급 11 15 20 25 30 0 0
최상급 15 20 25 30 40 0 0
}
# 단계 강화
# 1 2 3 4 5 6 7
Group 고대
{
최하급 10 12 15 18 20 0 0
하급 12 15 18 20 25 0 0
중급 15 18 20 25 35 0 0
상급 18 20 25 35 40 0 0
최상급 20 25 35 40 60 80 0
}
# 단계 강화
# 1 2 3 4 5 6 7
Group 전설
{
최하급 30 35 40 45 50 0 0
하급 35 40 45 50 55 0 0
중급 40 45 50 55 65 0 0
상급 45 50 55 65 75 90 0
최상급 50 55 65 75 90 105 120
}
# 용혼석 지속시간
Group DurationTable
{
일반 24
화려 12
희귀 8
고대 6
전설 4
}
# 용심 추출 확률 테이블
Group DragonHeartExtTable
{
# 용심 충전량(%)
용심 충전량 0 5 15 30 50
# 등급과 충전량에 따른 확률 테이블
# 등급 확률
일반 50 35 12 2 1
화려 35 40 20 4 1
희귀 20 35 30 12 3
고대 15 30 35 15 5
전설 10 20 40 20 10
}
# or 이거 2안도 있삼.
# (기획서 상의 내용이 충분치가 않아 2안이 있을 수 있다는 정도만 환기 시키기 위해 써 놓음.
# 부족한 부분은 임의로 정함.)
# 용혼석 등급에 따라 추출할 수 있는 용심이 정해져 있고, 그 확률도 정할 수 있음.
# 만일 이런 방식으로 확정된다면 아래 테이블에서 #을 하나씩 삭제하면 됨.
#Group DragonHeartExtTable
#{
# 등급 일반 화려 희귀 고대 전설
# 용심 종류 5 10 20 30 50
# 확률 60 60 60 60 60
#}
# 용혼석 추출 확률 테이블.
# 이것도 1, 2안이 있어 통합할 수 있는 방안으로 감.
# 추출 확률을 정할 수 있고, 실패 부산물도 정할 수 있음.(0이면 안줌)
Group DragonSoulExtTable
{
# 등급 확률 실패 부산물(vnum)
일반 50 0
화려 40 0
희귀 30 0
고대 30 0
전설 20 10
}
+93
View File
@@ -0,0 +1,93 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef _dbug_h
#define _dbug_h
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(DBUG_OFF) && !defined(_lint)
extern int _db_on_,_no_db_;
extern FILE *_db_fp_;
extern char *_db_process_;
extern int _db_keyword_(const char *keyword);
extern void _db_setjmp_(void);
extern void _db_longjmp_(void);
extern void _db_push_(const char *control);
extern void _db_pop_(void);
extern void _db_enter_(const char *_func_,const char *_file_,uint _line_,
const char **_sfunc_,const char **_sfile_,
uint *_slevel_, char ***);
extern void _db_return_(uint _line_,const char **_sfunc_,const char **_sfile_,
uint *_slevel_);
extern void _db_pargs_(uint _line_,const char *keyword);
extern void _db_doprnt_ _VARARGS((const char *format,...));
extern void _db_dump_(uint _line_,const char *keyword,const char *memory,
uint length);
extern void _db_lock_file();
extern void _db_unlock_file();
#define DBUG_ENTER(a) const char *_db_func_, *_db_file_; uint _db_level_; \
char **_db_framep_; \
_db_enter_ (a,__FILE__,__LINE__,&_db_func_,&_db_file_,&_db_level_, \
&_db_framep_)
#define DBUG_LEAVE \
(_db_return_ (__LINE__, &_db_func_, &_db_file_, &_db_level_))
#define DBUG_RETURN(a1) {DBUG_LEAVE; return(a1);}
#define DBUG_VOID_RETURN {DBUG_LEAVE; return;}
#define DBUG_EXECUTE(keyword,a1) \
{if (_db_on_) {if (_db_keyword_ (keyword)) { a1 }}}
#define DBUG_PRINT(keyword,arglist) \
{if (_db_on_) {_db_pargs_(__LINE__,keyword); _db_doprnt_ arglist;}}
#define DBUG_PUSH(a1) _db_push_ (a1)
#define DBUG_POP() _db_pop_ ()
#define DBUG_PROCESS(a1) (_db_process_ = a1)
#define DBUG_FILE (_db_fp_)
#define DBUG_SETJMP(a1) (_db_setjmp_ (), setjmp (a1))
#define DBUG_LONGJMP(a1,a2) (_db_longjmp_ (), longjmp (a1, a2))
#define DBUG_DUMP(keyword,a1,a2)\
{if (_db_on_) {_db_dump_(__LINE__,keyword,a1,a2);}}
#define DBUG_IN_USE (_db_fp_ && _db_fp_ != stderr)
#define DEBUGGER_OFF _no_db_=1;_db_on_=0;
#define DEBUGGER_ON _no_db_=0
#define DBUG_LOCK_FILE { _db_lock_file(); }
#define DBUG_UNLOCK_FILE { _db_unlock_file(); }
#define DBUG_ASSERT(A) assert(A)
#else /* No debugger */
#define DBUG_ENTER(a1)
#define DBUG_RETURN(a1) return(a1)
#define DBUG_VOID_RETURN return
#define DBUG_EXECUTE(keyword,a1) {}
#define DBUG_PRINT(keyword,arglist) {}
#define DBUG_PUSH(a1) {}
#define DBUG_POP() {}
#define DBUG_PROCESS(a1) {}
#define DBUG_FILE (stderr)
#define DBUG_SETJMP setjmp
#define DBUG_LONGJMP longjmp
#define DBUG_DUMP(keyword,a1,a2) {}
#define DBUG_IN_USE 0
#define DEBUGGER_OFF
#define DEBUGGER_ON
#define DBUG_LOCK_FILE
#define DBUG_UNLOCK_FILE
#define DBUG_ASSERT(A) {}
#endif
#ifdef __cplusplus
}
#endif
#endif
+92
View File
@@ -0,0 +1,92 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/* Error messages for mysql clients */
/* error messages for the demon is in share/language/errmsg.sys */
#ifdef __cplusplus
extern "C" {
#endif
void init_client_errs(void);
extern const char *client_errors[]; /* Error messages */
#ifdef __cplusplus
}
#endif
#define CR_MIN_ERROR 2000 /* For easier client code */
#define CR_MAX_ERROR 2999
#if defined(OS2) && defined(MYSQL_SERVER)
#define CER(X) client_errors[(X)-CR_MIN_ERROR]
#elif !defined(ER)
#define ER(X) client_errors[(X)-CR_MIN_ERROR]
#endif
#define CLIENT_ERRMAP 2 /* Errormap used by my_error() */
#define CR_UNKNOWN_ERROR 2000
#define CR_SOCKET_CREATE_ERROR 2001
#define CR_CONNECTION_ERROR 2002
#define CR_CONN_HOST_ERROR 2003
#define CR_IPSOCK_ERROR 2004
#define CR_UNKNOWN_HOST 2005
#define CR_SERVER_GONE_ERROR 2006
#define CR_VERSION_ERROR 2007
#define CR_OUT_OF_MEMORY 2008
#define CR_WRONG_HOST_INFO 2009
#define CR_LOCALHOST_CONNECTION 2010
#define CR_TCP_CONNECTION 2011
#define CR_SERVER_HANDSHAKE_ERR 2012
#define CR_SERVER_LOST 2013
#define CR_COMMANDS_OUT_OF_SYNC 2014
#define CR_NAMEDPIPE_CONNECTION 2015
#define CR_NAMEDPIPEWAIT_ERROR 2016
#define CR_NAMEDPIPEOPEN_ERROR 2017
#define CR_NAMEDPIPESETSTATE_ERROR 2018
#define CR_CANT_READ_CHARSET 2019
#define CR_NET_PACKET_TOO_LARGE 2020
#define CR_EMBEDDED_CONNECTION 2021
#define CR_PROBE_SLAVE_STATUS 2022
#define CR_PROBE_SLAVE_HOSTS 2023
#define CR_PROBE_SLAVE_CONNECT 2024
#define CR_PROBE_MASTER_CONNECT 2025
#define CR_SSL_CONNECTION_ERROR 2026
#define CR_MALFORMED_PACKET 2027
#define CR_WRONG_LICENSE 2028
/* new 4.1 error codes */
#define CR_NULL_POINTER 2029
#define CR_NO_PREPARE_STMT 2030
#define CR_PARAMS_NOT_BOUND 2031
#define CR_DATA_TRUNCATED 2032
#define CR_NO_PARAMETERS_EXISTS 2033
#define CR_INVALID_PARAMETER_NO 2034
#define CR_INVALID_BUFFER_USE 2035
#define CR_UNSUPPORTED_PARAM_TYPE 2036
#define CR_SHARED_MEMORY_CONNECTION 2037
#define CR_SHARED_MEMORY_CONNECT_REQUEST_ERROR 2038
#define CR_SHARED_MEMORY_CONNECT_ANSWER_ERROR 2039
#define CR_SHARED_MEMORY_CONNECT_FILE_MAP_ERROR 2040
#define CR_SHARED_MEMORY_CONNECT_MAP_ERROR 2041
#define CR_SHARED_MEMORY_FILE_MAP_ERROR 2042
#define CR_SHARED_MEMORY_MAP_ERROR 2043
#define CR_SHARED_MEMORY_EVENT_ERROR 2044
#define CR_SHARED_MEMORY_CONNECT_ABANDODED_ERROR 2045
#define CR_SHARED_MEMORY_CONNECT_SET_ERROR 2046
#define CR_CONN_UNKNOW_PROTOCOL 2047
#define CR_INVALID_CONN_HANDLE 2048
#define CR_SECURE_AUTH 2049
#define CR_FETCH_CANCELLED 2050
#define CR_NO_DATA 2051
+136
View File
@@ -0,0 +1,136 @@
/* Copyright (C) 2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/* Key cache variable structures */
#ifndef _keycache_h
#define _keycache_h
C_MODE_START
/* declare structures that is used by st_key_cache */
struct st_block_link;
typedef struct st_block_link BLOCK_LINK;
struct st_keycache_page;
typedef struct st_keycache_page KEYCACHE_PAGE;
struct st_hash_link;
typedef struct st_hash_link HASH_LINK;
/* info about requests in a waiting queue */
typedef struct st_keycache_wqueue
{
struct st_my_thread_var *last_thread; /* circular list of waiting threads */
} KEYCACHE_WQUEUE;
#define CHANGED_BLOCKS_HASH 128 /* must be power of 2 */
/*
The key cache structure
It also contains read-only statistics parameters.
*/
typedef struct st_key_cache
{
my_bool key_cache_inited;
my_bool resize_in_flush; /* true during flush of resize operation */
my_bool can_be_used; /* usage of cache for read/write is allowed */
uint key_cache_shift;
ulong key_cache_mem_size; /* specified size of the cache memory */
uint key_cache_block_size; /* size of the page buffer of a cache block */
ulong min_warm_blocks; /* min number of warm blocks; */
ulong age_threshold; /* age threshold for hot blocks */
ulonglong keycache_time; /* total number of block link operations */
uint hash_entries; /* max number of entries in the hash table */
int hash_links; /* max number of hash links */
int hash_links_used; /* number of hash links currently used */
int disk_blocks; /* max number of blocks in the cache */
ulong blocks_used; /* maximum number of concurrently used blocks */
ulong blocks_unused; /* number of currently unused blocks */
ulong blocks_changed; /* number of currently dirty blocks */
ulong warm_blocks; /* number of blocks in warm sub-chain */
ulong cnt_for_resize_op; /* counter to block resize operation */
long blocks_available; /* number of blocks available in the LRU chain */
HASH_LINK **hash_root; /* arr. of entries into hash table buckets */
HASH_LINK *hash_link_root; /* memory for hash table links */
HASH_LINK *free_hash_list; /* list of free hash links */
BLOCK_LINK *free_block_list; /* list of free blocks */
BLOCK_LINK *block_root; /* memory for block links */
byte HUGE_PTR *block_mem; /* memory for block buffers */
BLOCK_LINK *used_last; /* ptr to the last block of the LRU chain */
BLOCK_LINK *used_ins; /* ptr to the insertion block in LRU chain */
pthread_mutex_t cache_lock; /* to lock access to the cache structure */
KEYCACHE_WQUEUE resize_queue; /* threads waiting during resize operation */
KEYCACHE_WQUEUE waiting_for_hash_link; /* waiting for a free hash link */
KEYCACHE_WQUEUE waiting_for_block; /* requests waiting for a free block */
BLOCK_LINK *changed_blocks[CHANGED_BLOCKS_HASH]; /* hash for dirty file bl.*/
BLOCK_LINK *file_blocks[CHANGED_BLOCKS_HASH]; /* hash for other file bl.*/
/*
The following variables are and variables used to hold parameters for
initializing the key cache.
*/
ulonglong param_buff_size; /* size the memory allocated for the cache */
ulong param_block_size; /* size of the blocks in the key cache */
ulong param_division_limit; /* min. percentage of warm blocks */
ulong param_age_threshold; /* determines when hot block is downgraded */
/* Statistics variables */
ulong global_blocks_changed; /* number of currently dirty blocks */
ulong global_cache_w_requests;/* number of write requests (write hits) */
ulong global_cache_write; /* number of writes from the cache to files */
ulong global_cache_r_requests;/* number of read requests (read hits) */
ulong global_cache_read; /* number of reads from files to the cache */
int blocks; /* max number of blocks in the cache */
my_bool in_init; /* Set to 1 in MySQL during init/resize */
} KEY_CACHE;
/* The default key cache */
extern KEY_CACHE dflt_key_cache_var, *dflt_key_cache;
extern int init_key_cache(KEY_CACHE *keycache, uint key_cache_block_size,
ulong use_mem, uint division_limit,
uint age_threshold);
extern int resize_key_cache(KEY_CACHE *keycache, uint key_cache_block_size,
ulong use_mem, uint division_limit,
uint age_threshold);
extern void change_key_cache_param(KEY_CACHE *keycache, uint division_limit,
uint age_threshold);
extern byte *key_cache_read(KEY_CACHE *keycache,
File file, my_off_t filepos, int level,
byte *buff, uint length,
uint block_length,int return_buffer);
extern int key_cache_insert(KEY_CACHE *keycache,
File file, my_off_t filepos, int level,
byte *buff, uint length);
extern int key_cache_write(KEY_CACHE *keycache,
File file, my_off_t filepos, int level,
byte *buff, uint length,
uint block_length,int force_write);
extern int flush_key_blocks(KEY_CACHE *keycache,
int file, enum flush_type type);
extern void end_key_cache(KEY_CACHE *keycache, my_bool cleanup);
/* Functions to handle multiple key caches */
extern my_bool multi_keycache_init(void);
extern void multi_keycache_free(void);
extern KEY_CACHE *multi_key_cache_search(byte *key, uint length);
extern my_bool multi_key_cache_set(const byte *key, uint length,
KEY_CACHE *key_cache);
extern void multi_key_cache_change(KEY_CACHE *old_data,
KEY_CACHE *new_data);
C_MODE_END
#endif /* _keycache_h */
+427
View File
@@ -0,0 +1,427 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/*
A better inplementation of the UNIX ctype(3) library.
Notes: my_global.h should be included before ctype.h
*/
#ifndef _m_ctype_h
#define _m_ctype_h
#ifdef __cplusplus
extern "C" {
#endif
#define MY_CS_NAME_SIZE 32
#define MY_CS_CTYPE_TABLE_SIZE 257
#define MY_CS_TO_LOWER_TABLE_SIZE 256
#define MY_CS_TO_UPPER_TABLE_SIZE 256
#define MY_CS_SORT_ORDER_TABLE_SIZE 256
#define MY_CS_TO_UNI_TABLE_SIZE 256
#define CHARSET_DIR "charsets/"
#define my_wc_t ulong
typedef struct unicase_info_st
{
uint16 toupper;
uint16 tolower;
uint16 sort;
} MY_UNICASE_INFO;
#define MY_CS_ILSEQ 0
#define MY_CS_ILUNI 0
#define MY_CS_TOOSMALL -1
#define MY_CS_TOOFEW(n) (-1-(n))
#define MY_SEQ_INTTAIL 1
#define MY_SEQ_SPACES 2
/* My charsets_list flags */
#define MY_CS_COMPILED 1 /* compiled-in sets */
#define MY_CS_CONFIG 2 /* sets that have a *.conf file */
#define MY_CS_INDEX 4 /* sets listed in the Index file */
#define MY_CS_LOADED 8 /* sets that are currently loaded */
#define MY_CS_BINSORT 16 /* if binary sort order */
#define MY_CS_PRIMARY 32 /* if primary collation */
#define MY_CS_STRNXFRM 64 /* if strnxfrm is used for sort */
#define MY_CS_UNICODE 128 /* is a charset is full unicode */
#define MY_CS_READY 256 /* if a charset is initialized */
#define MY_CS_AVAILABLE 512 /* If either compiled-in or loaded*/
#define MY_CHARSET_UNDEFINED 0
typedef struct my_uni_idx_st
{
uint16 from;
uint16 to;
uchar *tab;
} MY_UNI_IDX;
typedef struct
{
uint beg;
uint end;
uint mblen;
} my_match_t;
enum my_lex_states
{
MY_LEX_START, MY_LEX_CHAR, MY_LEX_IDENT,
MY_LEX_IDENT_SEP, MY_LEX_IDENT_START,
MY_LEX_REAL, MY_LEX_HEX_NUMBER,
MY_LEX_CMP_OP, MY_LEX_LONG_CMP_OP, MY_LEX_STRING, MY_LEX_COMMENT, MY_LEX_END,
MY_LEX_OPERATOR_OR_IDENT, MY_LEX_NUMBER_IDENT, MY_LEX_INT_OR_REAL,
MY_LEX_REAL_OR_POINT, MY_LEX_BOOL, MY_LEX_EOL, MY_LEX_ESCAPE,
MY_LEX_LONG_COMMENT, MY_LEX_END_LONG_COMMENT, MY_LEX_SEMICOLON,
MY_LEX_SET_VAR, MY_LEX_USER_END, MY_LEX_HOSTNAME, MY_LEX_SKIP,
MY_LEX_USER_VARIABLE_DELIMITER, MY_LEX_SYSTEM_VAR,
MY_LEX_IDENT_OR_KEYWORD,
MY_LEX_IDENT_OR_HEX, MY_LEX_IDENT_OR_BIN, MY_LEX_IDENT_OR_NCHAR,
MY_LEX_STRING_OR_DELIMITER
};
struct charset_info_st;
typedef struct my_collation_handler_st
{
my_bool (*init)(struct charset_info_st *, void *(*alloc)(uint));
/* Collation routines */
int (*strnncoll)(struct charset_info_st *,
const uchar *, uint, const uchar *, uint, my_bool);
int (*strnncollsp)(struct charset_info_st *,
const uchar *, uint, const uchar *, uint);
int (*strnxfrm)(struct charset_info_st *,
uchar *, uint, const uchar *, uint);
my_bool (*like_range)(struct charset_info_st *,
const char *s, uint s_length,
pchar w_prefix, pchar w_one, pchar w_many,
uint res_length,
char *min_str, char *max_str,
uint *min_len, uint *max_len);
int (*wildcmp)(struct charset_info_st *,
const char *str,const char *str_end,
const char *wildstr,const char *wildend,
int escape,int w_one, int w_many);
int (*strcasecmp)(struct charset_info_st *, const char *, const char *);
uint (*instr)(struct charset_info_st *,
const char *b, uint b_length,
const char *s, uint s_length,
my_match_t *match, uint nmatch);
/* Hash calculation */
void (*hash_sort)(struct charset_info_st *cs, const uchar *key, uint len,
ulong *nr1, ulong *nr2);
} MY_COLLATION_HANDLER;
extern MY_COLLATION_HANDLER my_collation_mb_bin_handler;
extern MY_COLLATION_HANDLER my_collation_8bit_bin_handler;
extern MY_COLLATION_HANDLER my_collation_8bit_simple_ci_handler;
extern MY_COLLATION_HANDLER my_collation_ucs2_uca_handler;
typedef struct my_charset_handler_st
{
my_bool (*init)(struct charset_info_st *, void *(*alloc)(uint));
/* Multibyte routines */
int (*ismbchar)(struct charset_info_st *, const char *, const char *);
int (*mbcharlen)(struct charset_info_st *, uint);
uint (*numchars)(struct charset_info_st *, const char *b, const char *e);
uint (*charpos)(struct charset_info_st *, const char *b, const char *e, uint pos);
uint (*well_formed_len)(struct charset_info_st *,
const char *b,const char *e, uint nchars);
uint (*lengthsp)(struct charset_info_st *, const char *ptr, uint length);
/* Unicode convertion */
int (*mb_wc)(struct charset_info_st *cs,my_wc_t *wc,
const unsigned char *s,const unsigned char *e);
int (*wc_mb)(struct charset_info_st *cs,my_wc_t wc,
unsigned char *s,unsigned char *e);
/* Functions for case and sort convertion */
void (*caseup_str)(struct charset_info_st *, char *);
void (*casedn_str)(struct charset_info_st *, char *);
void (*caseup)(struct charset_info_st *, char *, uint);
void (*casedn)(struct charset_info_st *, char *, uint);
/* Charset dependant snprintf() */
int (*snprintf)(struct charset_info_st *, char *to, uint n, const char *fmt,
...);
int (*long10_to_str)(struct charset_info_st *, char *to, uint n, int radix,
long int val);
int (*longlong10_to_str)(struct charset_info_st *, char *to, uint n,
int radix, longlong val);
void (*fill)(struct charset_info_st *, char *to, uint len, int fill);
/* String-to-number convertion routines */
long (*strntol)(struct charset_info_st *, const char *s, uint l,
int base, char **e, int *err);
ulong (*strntoul)(struct charset_info_st *, const char *s, uint l,
int base, char **e, int *err);
longlong (*strntoll)(struct charset_info_st *, const char *s, uint l,
int base, char **e, int *err);
ulonglong (*strntoull)(struct charset_info_st *, const char *s, uint l,
int base, char **e, int *err);
double (*strntod)(struct charset_info_st *, char *s, uint l, char **e,
int *err);
ulong (*scan)(struct charset_info_st *, const char *b, const char *e,
int sq);
} MY_CHARSET_HANDLER;
extern MY_CHARSET_HANDLER my_charset_8bit_handler;
extern MY_CHARSET_HANDLER my_charset_ucs2_handler;
typedef struct charset_info_st
{
uint number;
uint primary_number;
uint binary_number;
uint state;
const char *csname;
const char *name;
const char *comment;
const char *tailoring;
uchar *ctype;
uchar *to_lower;
uchar *to_upper;
uchar *sort_order;
uint16 *contractions;
uint16 **sort_order_big;
uint16 *tab_to_uni;
MY_UNI_IDX *tab_from_uni;
uchar *state_map;
uchar *ident_map;
uint strxfrm_multiply;
uint mbminlen;
uint mbmaxlen;
uint16 min_sort_char;
uint16 max_sort_char; /* For LIKE optimization */
MY_CHARSET_HANDLER *cset;
MY_COLLATION_HANDLER *coll;
} CHARSET_INFO;
extern CHARSET_INFO my_charset_bin;
extern CHARSET_INFO my_charset_big5_chinese_ci;
extern CHARSET_INFO my_charset_big5_bin;
extern CHARSET_INFO my_charset_euckr_korean_ci;
extern CHARSET_INFO my_charset_euckr_bin;
extern CHARSET_INFO my_charset_gb2312_chinese_ci;
extern CHARSET_INFO my_charset_gb2312_bin;
extern CHARSET_INFO my_charset_gbk_chinese_ci;
extern CHARSET_INFO my_charset_gbk_bin;
extern CHARSET_INFO my_charset_latin1;
extern CHARSET_INFO my_charset_latin1_german2_ci;
extern CHARSET_INFO my_charset_latin1_bin;
extern CHARSET_INFO my_charset_latin2_czech_ci;
extern CHARSET_INFO my_charset_sjis_japanese_ci;
extern CHARSET_INFO my_charset_sjis_bin;
extern CHARSET_INFO my_charset_tis620_thai_ci;
extern CHARSET_INFO my_charset_tis620_bin;
extern CHARSET_INFO my_charset_ucs2_general_ci;
extern CHARSET_INFO my_charset_ucs2_bin;
extern CHARSET_INFO my_charset_ucs2_general_uca;
extern CHARSET_INFO my_charset_ujis_japanese_ci;
extern CHARSET_INFO my_charset_ujis_bin;
extern CHARSET_INFO my_charset_utf8_general_ci;
extern CHARSET_INFO my_charset_utf8_bin;
extern CHARSET_INFO my_charset_cp1250_czech_ci;
/* declarations for simple charsets */
extern int my_strnxfrm_simple(CHARSET_INFO *, uchar *, uint, const uchar *,
uint);
extern int my_strnncoll_simple(CHARSET_INFO *, const uchar *, uint,
const uchar *, uint, my_bool);
extern int my_strnncollsp_simple(CHARSET_INFO *, const uchar *, uint,
const uchar *, uint);
extern void my_hash_sort_simple(CHARSET_INFO *cs,
const uchar *key, uint len,
ulong *nr1, ulong *nr2);
extern uint my_lengthsp_8bit(CHARSET_INFO *cs, const char *ptr, uint length);
extern uint my_instr_simple(struct charset_info_st *,
const char *b, uint b_length,
const char *s, uint s_length,
my_match_t *match, uint nmatch);
/* Functions for 8bit */
extern void my_caseup_str_8bit(CHARSET_INFO *, char *);
extern void my_casedn_str_8bit(CHARSET_INFO *, char *);
extern void my_caseup_8bit(CHARSET_INFO *, char *, uint);
extern void my_casedn_8bit(CHARSET_INFO *, char *, uint);
extern int my_strcasecmp_8bit(CHARSET_INFO * cs, const char *, const char *);
int my_mb_wc_8bit(CHARSET_INFO *cs,my_wc_t *wc, const uchar *s,const uchar *e);
int my_wc_mb_8bit(CHARSET_INFO *cs,my_wc_t wc, uchar *s, uchar *e);
ulong my_scan_8bit(CHARSET_INFO *cs, const char *b, const char *e, int sq);
int my_snprintf_8bit(struct charset_info_st *, char *to, uint n,
const char *fmt, ...);
long my_strntol_8bit(CHARSET_INFO *, const char *s, uint l, int base,
char **e, int *err);
ulong my_strntoul_8bit(CHARSET_INFO *, const char *s, uint l, int base,
char **e, int *err);
longlong my_strntoll_8bit(CHARSET_INFO *, const char *s, uint l, int base,
char **e, int *err);
ulonglong my_strntoull_8bit(CHARSET_INFO *, const char *s, uint l, int base,
char **e, int *err);
double my_strntod_8bit(CHARSET_INFO *, char *s, uint l,char **e,
int *err);
int my_long10_to_str_8bit(CHARSET_INFO *, char *to, uint l, int radix,
long int val);
int my_longlong10_to_str_8bit(CHARSET_INFO *, char *to, uint l, int radix,
longlong val);
void my_fill_8bit(CHARSET_INFO *cs, char* to, uint l, int fill);
my_bool my_like_range_simple(CHARSET_INFO *cs,
const char *ptr, uint ptr_length,
pbool escape, pbool w_one, pbool w_many,
uint res_length,
char *min_str, char *max_str,
uint *min_length, uint *max_length);
my_bool my_like_range_ucs2(CHARSET_INFO *cs,
const char *ptr, uint ptr_length,
pbool escape, pbool w_one, pbool w_many,
uint res_length,
char *min_str, char *max_str,
uint *min_length, uint *max_length);
int my_wildcmp_8bit(CHARSET_INFO *,
const char *str,const char *str_end,
const char *wildstr,const char *wildend,
int escape, int w_one, int w_many);
uint my_numchars_8bit(CHARSET_INFO *, const char *b, const char *e);
uint my_charpos_8bit(CHARSET_INFO *, const char *b, const char *e, uint pos);
uint my_well_formed_len_8bit(CHARSET_INFO *, const char *b, const char *e, uint pos);
int my_mbcharlen_8bit(CHARSET_INFO *, uint c);
/* Functions for multibyte charsets */
extern void my_caseup_str_mb(CHARSET_INFO *, char *);
extern void my_casedn_str_mb(CHARSET_INFO *, char *);
extern void my_caseup_mb(CHARSET_INFO *, char *, uint);
extern void my_casedn_mb(CHARSET_INFO *, char *, uint);
extern int my_strcasecmp_mb(CHARSET_INFO * cs,const char *, const char *);
int my_wildcmp_mb(CHARSET_INFO *,
const char *str,const char *str_end,
const char *wildstr,const char *wildend,
int escape, int w_one, int w_many);
uint my_numchars_mb(CHARSET_INFO *, const char *b, const char *e);
uint my_charpos_mb(CHARSET_INFO *, const char *b, const char *e, uint pos);
uint my_well_formed_len_mb(CHARSET_INFO *, const char *b, const char *e, uint pos);
uint my_instr_mb(struct charset_info_st *,
const char *b, uint b_length,
const char *s, uint s_length,
my_match_t *match, uint nmatch);
extern my_bool my_parse_charset_xml(const char *bug, uint len,
int (*add)(CHARSET_INFO *cs));
#define _MY_U 01 /* Upper case */
#define _MY_L 02 /* Lower case */
#define _MY_NMR 04 /* Numeral (digit) */
#define _MY_SPC 010 /* Spacing character */
#define _MY_PNT 020 /* Punctuation */
#define _MY_CTR 040 /* Control character */
#define _MY_B 0100 /* Blank */
#define _MY_X 0200 /* heXadecimal digit */
#define my_isascii(c) (!((c) & ~0177))
#define my_toascii(c) ((c) & 0177)
#define my_tocntrl(c) ((c) & 31)
#define my_toprint(c) ((c) | 64)
#define my_toupper(s,c) (char) ((s)->to_upper[(uchar) (c)])
#define my_tolower(s,c) (char) ((s)->to_lower[(uchar) (c)])
#define my_isalpha(s, c) (((s)->ctype+1)[(uchar) (c)] & (_MY_U | _MY_L))
#define my_isupper(s, c) (((s)->ctype+1)[(uchar) (c)] & _MY_U)
#define my_islower(s, c) (((s)->ctype+1)[(uchar) (c)] & _MY_L)
#define my_isdigit(s, c) (((s)->ctype+1)[(uchar) (c)] & _MY_NMR)
#define my_isxdigit(s, c) (((s)->ctype+1)[(uchar) (c)] & _MY_X)
#define my_isalnum(s, c) (((s)->ctype+1)[(uchar) (c)] & (_MY_U | _MY_L | _MY_NMR))
#define my_isspace(s, c) (((s)->ctype+1)[(uchar) (c)] & _MY_SPC)
#define my_ispunct(s, c) (((s)->ctype+1)[(uchar) (c)] & _MY_PNT)
#define my_isprint(s, c) (((s)->ctype+1)[(uchar) (c)] & (_MY_PNT | _MY_U | _MY_L | _MY_NMR | _MY_B))
#define my_isgraph(s, c) (((s)->ctype+1)[(uchar) (c)] & (_MY_PNT | _MY_U | _MY_L | _MY_NMR))
#define my_iscntrl(s, c) (((s)->ctype+1)[(uchar) (c)] & _MY_CTR)
/* Some macros that should be cleaned up a little */
#define my_isvar(s,c) (my_isalnum(s,c) || (c) == '_')
#define my_isvar_start(s,c) (my_isalpha(s,c) || (c) == '_')
#define my_binary_compare(s) ((s)->state & MY_CS_BINSORT)
#define use_strnxfrm(s) ((s)->state & MY_CS_STRNXFRM)
#define my_strnxfrm(s, a, b, c, d) ((s)->coll->strnxfrm((s), (a), (b), (c), (d)))
#define my_strnncoll(s, a, b, c, d) ((s)->coll->strnncoll((s), (a), (b), (c), (d), 0))
#define my_like_range(s, a, b, c, d, e, f, g, h, i, j) \
((s)->coll->like_range((s), (a), (b), (c), (d), (e), (f), (g), (h), (i), (j)))
#define my_wildcmp(cs,s,se,w,we,e,o,m) ((cs)->coll->wildcmp((cs),(s),(se),(w),(we),(e),(o),(m)))
#define my_strcasecmp(s, a, b) ((s)->coll->strcasecmp((s), (a), (b)))
#define use_mb(s) ((s)->cset->ismbchar != NULL)
#define my_ismbchar(s, a, b) ((s)->cset->ismbchar((s), (a), (b)))
#ifdef USE_MB
#define my_mbcharlen(s, a) ((s)->cset->mbcharlen((s),(a)))
#else
#define my_mbcharlen(s, a) 1
#endif
#define my_caseup(s, a, l) ((s)->cset->caseup((s), (a), (l)))
#define my_casedn(s, a, l) ((s)->cset->casedn((s), (a), (l)))
#define my_caseup_str(s, a) ((s)->cset->caseup_str((s), (a)))
#define my_casedn_str(s, a) ((s)->cset->casedn_str((s), (a)))
#define my_strntol(s, a, b, c, d, e) ((s)->cset->strntol((s),(a),(b),(c),(d),(e)))
#define my_strntoul(s, a, b, c, d, e) ((s)->cset->strntoul((s),(a),(b),(c),(d),(e)))
#define my_strntoll(s, a, b, c, d, e) ((s)->cset->strntoll((s),(a),(b),(c),(d),(e)))
#define my_strntoull(s, a, b, c,d, e) ((s)->cset->strntoull((s),(a),(b),(c),(d),(e)))
#define my_strntod(s, a, b, c, d) ((s)->cset->strntod((s),(a),(b),(c),(d)))
/* XXX: still need to take care of this one */
#ifdef MY_CHARSET_TIS620
#error The TIS620 charset is broken at the moment. Tell tim to fix it.
#define USE_TIS620
#include "t_ctype.h"
#endif
#ifdef __cplusplus
}
#endif
#endif /* _m_ctype_h */
+261
View File
@@ -0,0 +1,261 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/* There may be prolems include all of theese. Try to test in
configure with ones are needed? */
/* This is needed for the definitions of strchr... on solaris */
#ifndef _m_string_h
#define _m_string_h
#ifndef __USE_GNU
#define __USE_GNU /* We want to use stpcpy */
#endif
#if defined(HAVE_STRINGS_H)
#include <strings.h>
#endif
#if defined(HAVE_STRING_H)
#include <string.h>
#endif
/* need by my_vsnprintf */
#include <stdarg.h>
/* Correct some things for UNIXWARE7 */
#ifdef HAVE_UNIXWARE7_THREADS
#undef HAVE_STRINGS_H
#undef HAVE_MEMORY_H
#define HAVE_MEMCPY
#ifndef HAVE_MEMMOVE
#define HAVE_MEMMOVE
#endif
#undef HAVE_BCMP
#undef bcopy
#undef bcmp
#undef bzero
#endif /* HAVE_UNIXWARE7_THREADS */
#ifdef _AIX
#undef HAVE_BCMP
#endif
/* This is needed for the definitions of bzero... on solaris */
#if defined(HAVE_STRINGS_H) && !defined(HAVE_mit_thread)
#include <strings.h>
#endif
/* This is needed for the definitions of memcpy... on solaris */
#if defined(HAVE_MEMORY_H) && !defined(__cplusplus)
#include <memory.h>
#endif
#if !defined(HAVE_MEMCPY) && !defined(HAVE_MEMMOVE)
# define memcpy(d, s, n) bcopy ((s), (d), (n))
# define memset(A,C,B) bfill((A),(B),(C))
# define memmove(d, s, n) bmove ((d), (s), (n))
#elif defined(HAVE_MEMMOVE)
# define bmove(d, s, n) memmove((d), (s), (n))
#else
# define memmove(d, s, n) bmove((d), (s), (n)) /* our bmove */
#endif
/* Unixware 7 */
#if !defined(HAVE_BFILL)
# define bfill(A,B,C) memset((A),(C),(B))
# define bmove_align(A,B,C) memcpy((A),(B),(C))
#endif
#if !defined(HAVE_BCMP)
# define bcopy(s, d, n) memcpy((d), (s), (n))
# define bcmp(A,B,C) memcmp((A),(B),(C))
# define bzero(A,B) memset((A),0,(B))
# define bmove_align(A,B,C) memcpy((A),(B),(C))
#endif
#if defined(__cplusplus) && !defined(OS2)
extern "C" {
#endif
#if defined(HAVE_STPCPY) && !defined(HAVE_mit_thread)
#define strmov(A,B) stpcpy((A),(B))
#ifndef stpcpy
extern char *stpcpy(char *, const char *); /* For AIX with gcc 2.95.3 */
#endif
#endif
/* Declared in int2str() */
extern char NEAR _dig_vec_upper[];
extern char NEAR _dig_vec_lower[];
#ifdef BAD_STRING_COMPILER
#define strmov(A,B) (memccpy(A,B,0,INT_MAX)-1)
#else
#define strmov_overlapp(A,B) strmov(A,B)
#define strmake_overlapp(A,B,C) strmake(A,B,C)
#endif
#ifdef BAD_MEMCPY /* Problem with gcc on Alpha */
#define memcpy_fixed(A,B,C) bmove((A),(B),(C))
#else
#define memcpy_fixed(A,B,C) memcpy((A),(B),(C))
#endif
#ifdef MSDOS
#undef bmove_align
#define bmove512(A,B,C) bmove_align(A,B,C)
extern void bmove_align(gptr dst,const gptr src,uint len);
#endif
#if (!defined(USE_BMOVE512) || defined(HAVE_purify)) && !defined(bmove512)
#define bmove512(A,B,C) memcpy(A,B,C)
#endif
#ifdef HAVE_purify
#define memcpy_overlap(A,B,C) \
DBUG_ASSERT((A) <= (B) || ((B)+(C)) <= (A)); \
bmove((byte*) (A),(byte*) (B),(size_t) (C));
#else
#define memcpy_overlap(A,B,C) memcpy((A), (B), (C))
#endif /* HAVE_purify */
/* Prototypes for string functions */
#if !defined(bfill) && !defined(HAVE_BFILL)
extern void bfill(gptr dst,uint len,pchar fill);
#endif
#if !defined(bzero) && !defined(HAVE_BZERO)
extern void bzero(gptr dst,uint len);
#endif
#if !defined(bcmp) && !defined(HAVE_BCMP)
extern int bcmp(const char *s1,const char *s2,uint len);
#endif
#ifdef HAVE_purify
extern int my_bcmp(const char *s1,const char *s2,uint len);
#undef bcmp
#define bcmp(A,B,C) my_bcmp((A),(B),(C))
#endif
#ifndef bmove512
extern void bmove512(gptr dst,const gptr src,uint len);
#endif
#if !defined(HAVE_BMOVE) && !defined(bmove)
extern void bmove(char *dst, const char *src,uint len);
#endif
extern void bmove_upp(char *dst,const char *src,uint len);
extern void bchange(char *dst,uint old_len,const char *src,
uint new_len,uint tot_len);
extern void strappend(char *s,uint len,pchar fill);
extern char *strend(const char *s);
extern char *strcend(const char *, pchar);
extern char *strfield(char *src,int fields,int chars,int blanks,
int tabch);
extern char *strfill(my_string s,uint len,pchar fill);
extern uint strinstr(const char *str,const char *search);
extern uint r_strinstr(reg1 my_string str,int from, reg4 my_string search);
extern char *strkey(char *dst,char *head,char *tail,char *flags);
extern char *strmake(char *dst,const char *src,uint length);
#ifndef strmake_overlapp
extern char *strmake_overlapp(char *dst,const char *src, uint length);
#endif
#ifndef strmov
extern char *strmov(char *dst,const char *src);
#endif
extern char *strnmov(char *dst,const char *src,uint n);
extern char *strsuff(const char *src,const char *suffix);
extern char *strcont(const char *src,const char *set);
extern char *strxcat _VARARGS((char *dst,const char *src, ...));
extern char *strxmov _VARARGS((char *dst,const char *src, ...));
extern char *strxcpy _VARARGS((char *dst,const char *src, ...));
extern char *strxncat _VARARGS((char *dst,uint len, const char *src, ...));
extern char *strxnmov _VARARGS((char *dst,uint len, const char *src, ...));
extern char *strxncpy _VARARGS((char *dst,uint len, const char *src, ...));
/* Prototypes of normal stringfunctions (with may ours) */
#ifdef WANT_STRING_PROTOTYPES
extern char *strcat(char *, const char *);
extern char *strchr(const char *, pchar);
extern char *strrchr(const char *, pchar);
extern char *strcpy(char *, const char *);
extern int strcmp(const char *, const char *);
#ifndef __GNUC__
extern size_t strlen(const char *);
#endif
#endif
#ifndef HAVE_STRNLEN
extern uint strnlen(const char *s, uint n);
#endif
#if !defined(__cplusplus)
#ifndef HAVE_STRPBRK
extern char *strpbrk(const char *, const char *);
#endif
#ifndef HAVE_STRSTR
extern char *strstr(const char *, const char *);
#endif
#endif
extern int is_prefix(const char *, const char *);
/* Conversion routines */
double my_strtod(const char *str, char **end);
double my_atof(const char *nptr);
extern char *llstr(longlong value,char *buff);
#ifndef HAVE_STRTOUL
extern long strtol(const char *str, char **ptr, int base);
extern ulong strtoul(const char *str, char **ptr, int base);
#endif
extern char *int2str(long val, char *dst, int radix, int upcase);
extern char *int10_to_str(long val,char *dst,int radix);
extern char *str2int(const char *src,int radix,long lower,long upper,
long *val);
longlong my_strtoll10(const char *nptr, char **endptr, int *error);
#if SIZEOF_LONG == SIZEOF_LONG_LONG
#define longlong2str(A,B,C) int2str((A),(B),(C),1)
#define longlong10_to_str(A,B,C) int10_to_str((A),(B),(C))
#undef strtoll
#define strtoll(A,B,C) strtol((A),(B),(C))
#define strtoull(A,B,C) strtoul((A),(B),(C))
#ifndef HAVE_STRTOULL
#define HAVE_STRTOULL
#endif
#else
#ifdef HAVE_LONG_LONG
extern char *longlong2str(longlong val,char *dst,int radix);
extern char *longlong10_to_str(longlong val,char *dst,int radix);
#if (!defined(HAVE_STRTOULL) || defined(HAVE_mit_thread)) || defined(NO_STRTOLL_PROTO)
extern longlong strtoll(const char *str, char **ptr, int base);
extern ulonglong strtoull(const char *str, char **ptr, int base);
#endif
#endif
#endif
/* my_vsnprintf.c */
extern int my_vsnprintf( char *str, size_t n,
const char *format, va_list ap );
extern int my_snprintf(char* to, size_t n, const char* fmt, ...);
#if defined(__cplusplus) && !defined(OS2)
}
#endif
#endif
+52
View File
@@ -0,0 +1,52 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/*
Data structures for mysys/my_alloc.c (root memory allocator)
*/
#ifndef _my_alloc_h
#define _my_alloc_h
#define ALLOC_MAX_BLOCK_TO_DROP 4096
#define ALLOC_MAX_BLOCK_USAGE_BEFORE_DROP 10
typedef struct st_used_mem
{ /* struct for once_alloc (block) */
struct st_used_mem *next; /* Next block in use */
unsigned int left; /* memory left in block */
unsigned int size; /* size of block */
} USED_MEM;
typedef struct st_mem_root
{
USED_MEM *free; /* blocks with free memory in it */
USED_MEM *used; /* blocks almost without free memory */
USED_MEM *pre_alloc; /* preallocated block */
/* if block have less memory it will be put in 'used' list */
unsigned int min_malloc;
unsigned int block_size; /* initial block size */
unsigned int block_num; /* allocated blocks counter */
/*
first free block in queue test counter (if it exceed
MAX_BLOCK_USAGE_BEFORE_DROP block will be droped in 'used' list)
*/
unsigned int first_block_usage;
void (*error_handler)(void);
} MEM_ROOT;
#endif
File diff suppressed because it is too large Load Diff
+94
View File
@@ -0,0 +1,94 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef _dbug_h
#define _dbug_h
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(DBUG_OFF) && !defined(_lint)
extern int _db_on_,_no_db_;
extern FILE *_db_fp_;
extern char *_db_process_;
extern int _db_keyword_(const char *keyword);
extern void _db_setjmp_(void);
extern void _db_longjmp_(void);
extern void _db_push_(const char *control);
extern void _db_pop_(void);
extern void _db_enter_(const char *_func_,const char *_file_,uint _line_,
const char **_sfunc_,const char **_sfile_,
uint *_slevel_, char ***);
extern void _db_return_(uint _line_,const char **_sfunc_,const char **_sfile_,
uint *_slevel_);
extern void _db_pargs_(uint _line_,const char *keyword);
extern void _db_doprnt_ _VARARGS((const char *format,...));
extern void _db_dump_(uint _line_,const char *keyword,const char *memory,
uint length);
extern void _db_lock_file();
extern void _db_unlock_file();
#define DBUG_ENTER(a) const char *_db_func_, *_db_file_; uint _db_level_; \
char **_db_framep_; \
_db_enter_ (a,__FILE__,__LINE__,&_db_func_,&_db_file_,&_db_level_, \
&_db_framep_)
#define DBUG_LEAVE \
(_db_return_ (__LINE__, &_db_func_, &_db_file_, &_db_level_))
#define DBUG_RETURN(a1) {DBUG_LEAVE; return(a1);}
#define DBUG_VOID_RETURN {DBUG_LEAVE; return;}
#define DBUG_EXECUTE(keyword,a1) \
{if (_db_on_) {if (_db_keyword_ (keyword)) { a1 }}}
#define DBUG_PRINT(keyword,arglist) \
{if (_db_on_) {_db_pargs_(__LINE__,keyword); _db_doprnt_ arglist;}}
#define DBUG_PUSH(a1) _db_push_ (a1)
#define DBUG_POP() _db_pop_ ()
#define DBUG_PROCESS(a1) (_db_process_ = a1)
#define DBUG_FILE (_db_fp_)
#define DBUG_SETJMP(a1) (_db_setjmp_ (), setjmp (a1))
#define DBUG_LONGJMP(a1,a2) (_db_longjmp_ (), longjmp (a1, a2))
#define DBUG_DUMP(keyword,a1,a2)\
{if (_db_on_) {_db_dump_(__LINE__,keyword,a1,a2);}}
#define DBUG_IN_USE (_db_fp_ && _db_fp_ != stderr)
#define DEBUGGER_OFF _no_db_=1;_db_on_=0;
#define DEBUGGER_ON _no_db_=0
#define DBUG_LOCK_FILE { _db_lock_file(); }
#define DBUG_UNLOCK_FILE { _db_unlock_file(); }
#define DBUG_ASSERT(A) assert(A)
#else /* No debugger */
#define DBUG_ENTER(a1)
#define DBUG_RETURN(a1) return(a1)
#define DBUG_VOID_RETURN return
#define DBUG_EXECUTE(keyword,a1) {}
#define DBUG_PRINT(keyword,arglist) {}
#define DBUG_PUSH(a1) {}
#define DBUG_POP() {}
#define DBUG_PROCESS(a1) {}
#define DBUG_FILE (stderr)
#define DBUG_SETJMP setjmp
#define DBUG_LONGJMP longjmp
#define DBUG_DUMP(keyword,a1,a2) {}
#define DBUG_IN_USE 0
#define DEBUGGER_OFF
#define DEBUGGER_ON
#define DBUG_LOCK_FILE
#define DBUG_UNLOCK_FILE
#define DBUG_ASSERT(A) {}
#endif
#ifdef __cplusplus
}
#endif
#endif
+106
View File
@@ -0,0 +1,106 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef _my_dir_h
#define _my_dir_h
#ifdef __cplusplus
extern "C" {
#endif
#ifndef MY_DIR_H
#define MY_DIR_H
#include <sys/stat.h>
/* Defines for my_dir and my_stat */
#define MY_S_IFMT S_IFMT /* type of file */
#define MY_S_IFDIR S_IFDIR /* directory */
#define MY_S_IFCHR S_IFCHR /* character special */
#define MY_S_IFBLK S_IFBLK /* block special */
#define MY_S_IFREG S_IFREG /* regular */
#define MY_S_IFIFO S_IFIFO /* fifo */
#define MY_S_ISUID S_ISUID /* set user id on execution */
#define MY_S_ISGID S_ISGID /* set group id on execution */
#define MY_S_ISVTX S_ISVTX /* save swapped text even after use */
#define MY_S_IREAD S_IREAD /* read permission, owner */
#define MY_S_IWRITE S_IWRITE /* write permission, owner */
#define MY_S_IEXEC S_IEXEC /* execute/search permission, owner */
#define MY_S_ISDIR(m) (((m) & MY_S_IFMT) == MY_S_IFDIR)
#define MY_S_ISCHR(m) (((m) & MY_S_IFMT) == MY_S_IFCHR)
#define MY_S_ISBLK(m) (((m) & MY_S_IFMT) == MY_S_IFBLK)
#define MY_S_ISREG(m) (((m) & MY_S_IFMT) == MY_S_IFREG)
#define MY_S_ISFIFO(m) (((m) & MY_S_IFMT) == MY_S_IFIFO)
#define MY_DONT_SORT 512 /* my_lib; Don't sort files */
#define MY_WANT_STAT 1024 /* my_lib; stat files */
/* typedefs for my_dir & my_stat */
#ifdef USE_MY_STAT_STRUCT
typedef struct my_stat
{
dev_t st_dev; /* major & minor device numbers */
ino_t st_ino; /* inode number */
ushort st_mode; /* file permissons (& suid sgid .. bits) */
short st_nlink; /* number of links to file */
ushort st_uid; /* user id */
ushort st_gid; /* group id */
dev_t st_rdev; /* more major & minor device numbers (???) */
off_t st_size; /* size of file */
time_t st_atime; /* time for last read */
time_t st_mtime; /* time for last contens modify */
time_t st_ctime; /* time for last inode or contents modify */
} MY_STAT;
#else
#define MY_STAT struct stat /* Orginal struct have what we need */
#endif /* USE_MY_STAT_STRUCT */
/* Struct describing one file returned from my_dir */
typedef struct fileinfo
{
char *name;
MY_STAT *mystat;
} FILEINFO;
typedef struct st_my_dir /* Struct returned from my_dir */
{
/*
These members are just copies of parts of DYNAMIC_ARRAY structure,
which is allocated right after the end of MY_DIR structure (MEM_ROOT
for storing names is also resides there). We've left them here because
we don't want to change code that uses my_dir.
*/
struct fileinfo *dir_entry;
uint number_off_files;
} MY_DIR;
extern MY_DIR *my_dir(const char *path,myf MyFlags);
extern void my_dirend(MY_DIR *buffer);
extern MY_STAT *my_stat(const char *path, MY_STAT *stat_area, myf my_flags);
extern int my_fstat(int filenr, MY_STAT *stat_area, myf MyFlags);
#endif /* MY_DIR_H */
#ifdef __cplusplus
}
#endif
#endif
+62
View File
@@ -0,0 +1,62 @@
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
C_MODE_START
enum get_opt_var_type { GET_NO_ARG, GET_BOOL, GET_INT, GET_UINT, GET_LONG,
GET_ULONG, GET_LL, GET_ULL, GET_STR, GET_STR_ALLOC,
GET_DISABLED
};
#define GET_ASK_ADDR 128
#define GET_TYPE_MASK 127
enum get_opt_arg_type { NO_ARG, OPT_ARG, REQUIRED_ARG };
struct my_option
{
const char *name; /* Name of the option */
int id; /* unique id or short option */
const char *comment; /* option comment, for autom. --help */
gptr *value; /* The variable value */
gptr *u_max_value; /* The user def. max variable value */
const char **str_values; /* Pointer to possible values */
enum get_opt_var_type var_type;
enum get_opt_arg_type arg_type;
longlong def_value; /* Default value */
longlong min_value; /* Min allowed value */
longlong max_value; /* Max allowed value */
longlong sub_size; /* Subtract this from given value */
long block_size; /* Value should be a mult. of this */
int app_type; /* To be used by an application */
};
extern char *disabled_my_option;
extern my_bool my_getopt_print_errors;
extern int handle_options (int *argc, char ***argv,
const struct my_option *longopts,
my_bool (*get_one_option)(int,
const struct my_option *,
char *));
extern void my_print_help(const struct my_option *options);
extern void my_print_variables(const struct my_option *options);
extern void my_getopt_register_get_addr(gptr* (*func_addr)(const char *, uint,
const struct my_option *));
ulonglong getopt_ull_limit_value(ulonglong num, const struct my_option *optp);
my_bool getopt_compare_strings(const char *s, const char *t, uint length);
C_MODE_END
File diff suppressed because it is too large Load Diff
+46
View File
@@ -0,0 +1,46 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef _list_h_
#define _list_h_
#ifdef __cplusplus
extern "C" {
#endif
typedef struct st_list {
struct st_list *prev,*next;
void *data;
} LIST;
typedef int (*list_walk_action)(void *,void *);
extern LIST *list_add(LIST *root,LIST *element);
extern LIST *list_delete(LIST *root,LIST *element);
extern LIST *list_cons(void *data,LIST *root);
extern LIST *list_reverse(LIST *root);
extern void list_free(LIST *root,unsigned int free_data);
extern unsigned int list_length(LIST *list);
extern int list_walk(LIST *list,list_walk_action action,gptr argument);
#define rest(a) ((a)->next)
#define list_push(a,b) (a)=list_cons((b),(a))
#define list_pop(A) {LIST *old=(A); (A)=list_delete(old,old) ; my_free((gptr) old,MYF(MY_FAE)); }
#ifdef __cplusplus
}
#endif
#endif
+122
View File
@@ -0,0 +1,122 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/*
thread safe version of some common functions:
my_inet_ntoa
This file is also used to make handling of sockets and ioctl()
portable accross systems.
*/
#ifndef _my_net_h
#define _my_net_h
C_MODE_START
#include <errno.h>
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_POLL
#include <sys/poll.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#if !defined(MSDOS) && !defined(__WIN__) && !defined(HAVE_BROKEN_NETINET_INCLUDES) && !defined(__BEOS__) && !defined(__NETWARE__)
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#if !defined(alpha_linux_port)
#include <netinet/tcp.h>
#endif
#endif
#if defined(__EMX__)
#include <sys/ioctl.h>
#define ioctlsocket(A,B,C) ioctl((A),(B),(void *)(C),sizeof(*(C)))
#undef HAVE_FCNTL
#endif /* defined(__EMX__) */
#if defined(MSDOS) || defined(__WIN__)
#define O_NONBLOCK 1 /* For emulation of fcntl() */
#endif
/*
On OSes which don't have the in_addr_t, we guess that using uint32 is the best
possible choice. We guess this from the fact that on HP-UX64bit & FreeBSD64bit
& Solaris64bit, in_addr_t is equivalent to uint32. And on Linux32bit too.
*/
#ifndef HAVE_IN_ADDR_T
#define in_addr_t uint32
#endif
/* Thread safe or portable version of some functions */
void my_inet_ntoa(struct in_addr in, char *buf);
/*
Handling of gethostbyname_r()
*/
#if !defined(HPUX10)
struct hostent;
#endif /* HPUX */
#if !defined(HAVE_GETHOSTBYNAME_R)
struct hostent *my_gethostbyname_r(const char *name,
struct hostent *result, char *buffer,
int buflen, int *h_errnop);
void my_gethostbyname_r_free();
#elif defined(HAVE_PTHREAD_ATTR_CREATE) || defined(_AIX) || defined(HAVE_GETHOSTBYNAME_R_GLIBC2_STYLE)
struct hostent *my_gethostbyname_r(const char *name,
struct hostent *result, char *buffer,
int buflen, int *h_errnop);
#define my_gethostbyname_r_free()
#if !defined(HAVE_GETHOSTBYNAME_R_GLIBC2_STYLE) && !defined(HPUX10)
#define GETHOSTBYNAME_BUFF_SIZE sizeof(struct hostent_data)
#endif /* !defined(HAVE_GETHOSTBYNAME_R_GLIBC2_STYLE) */
#elif defined(HAVE_GETHOSTBYNAME_R_RETURN_INT)
#define GETHOSTBYNAME_BUFF_SIZE sizeof(struct hostent_data)
struct hostent *my_gethostbyname_r(const char *name,
struct hostent *result, char *buffer,
int buflen, int *h_errnop);
#define my_gethostbyname_r_free()
#else
#define my_gethostbyname_r(A,B,C,D,E) gethostbyname_r((A),(B),(C),(D),(E))
#define my_gethostbyname_r_free()
#endif /* !defined(HAVE_GETHOSTBYNAME_R) */
#ifndef GETHOSTBYNAME_BUFF_SIZE
#define GETHOSTBYNAME_BUFF_SIZE 2048
#endif
/* On SCO you get a link error when refering to h_errno */
#ifdef SCO
#undef h_errno
#define h_errno errno
#endif
C_MODE_END
#endif
+35
View File
@@ -0,0 +1,35 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/*
This undefs some pthread mutex locks when one isn't using threads
to make thread safe code, that should also work in single thread
environment, easier to use.
*/
#if !defined(_my_no_pthread_h) && !defined(THREAD)
#define _my_no_pthread_h
#define pthread_mutex_init(A,B)
#define pthread_mutex_lock(A)
#define pthread_mutex_unlock(A)
#define pthread_mutex_destroy(A)
#define my_rwlock_init(A,B)
#define rw_rdlock(A)
#define rw_wrlock(A)
#define rw_unlock(A)
#define rwlock_destroy(A)
#endif
+701
View File
@@ -0,0 +1,701 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/* Defines to make different thread packages compatible */
#ifndef _my_pthread_h
#define _my_pthread_h
#include <errno.h>
#ifndef ETIME
#define ETIME ETIMEDOUT /* For FreeBSD */
#endif
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#if defined(__WIN__) || defined(OS2)
#ifdef OS2
typedef ULONG HANDLE;
typedef ULONG DWORD;
typedef int sigset_t;
#endif
#ifdef OS2
typedef HMTX pthread_mutex_t;
#else
typedef CRITICAL_SECTION pthread_mutex_t;
#endif
typedef HANDLE pthread_t;
typedef struct thread_attr {
DWORD dwStackSize ;
DWORD dwCreatingFlag ;
int priority ;
} pthread_attr_t ;
typedef struct { int dummy; } pthread_condattr_t;
/* Implementation of posix conditions */
typedef struct st_pthread_link {
DWORD thread_id;
struct st_pthread_link *next;
} pthread_link;
typedef struct {
uint32 waiting;
#ifdef OS2
HEV semaphore;
#else
HANDLE semaphore;
#endif
} pthread_cond_t;
#ifndef OS2
struct timespec { /* For pthread_cond_timedwait() */
time_t tv_sec;
long tv_nsec;
};
#endif
typedef int pthread_mutexattr_t;
#define win_pthread_self my_thread_var->pthread_self
#ifdef OS2
#define pthread_handler_decl(A,B) void * _Optlink A(void *B)
typedef void * (_Optlink *pthread_handler)(void *);
#else
#define pthread_handler_decl(A,B) void * __cdecl A(void *B)
typedef void * (__cdecl *pthread_handler)(void *);
#endif
void win_pthread_init(void);
int win_pthread_setspecific(void *A,void *B,uint length);
int pthread_create(pthread_t *,pthread_attr_t *,pthread_handler,void *);
int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr);
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex,
struct timespec *abstime);
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_attr_init(pthread_attr_t *connect_att);
int pthread_attr_setstacksize(pthread_attr_t *connect_att,DWORD stack);
int pthread_attr_setprio(pthread_attr_t *connect_att,int priority);
int pthread_attr_destroy(pthread_attr_t *connect_att);
struct tm *localtime_r(const time_t *timep,struct tm *tmp);
struct tm *gmtime_r(const time_t *timep,struct tm *tmp);
void pthread_exit(void *a); /* was #define pthread_exit(A) ExitThread(A)*/
#ifndef OS2
#define ETIMEDOUT 145 /* Win32 doesn't have this */
#define getpid() GetCurrentThreadId()
#endif
#define pthread_self() win_pthread_self
#define HAVE_LOCALTIME_R 1
#define _REENTRANT 1
#define HAVE_PTHREAD_ATTR_SETSTACKSIZE 1
#ifdef USE_TLS /* For LIBMYSQL.DLL */
#undef SAFE_MUTEX /* This will cause conflicts */
#define pthread_key(T,V) DWORD V
#define pthread_key_create(A,B) ((*A=TlsAlloc())==0xFFFFFFFF)
#define pthread_key_delete(A) TlsFree(A)
#define pthread_getspecific(A) (TlsGetValue(A))
#define my_pthread_getspecific(T,A) ((T) TlsGetValue(A))
#define my_pthread_getspecific_ptr(T,V) ((T) TlsGetValue(V))
#define my_pthread_setspecific_ptr(T,V) (!TlsSetValue((T),(V)))
#define pthread_setspecific(A,B) (!TlsSetValue((A),(B)))
#else
#define pthread_key(T,V) __declspec(thread) T V
#define pthread_key_create(A,B) pthread_dummy(0)
#define pthread_key_delete(A) pthread_dummy(0)
#define pthread_getspecific(A) (&(A))
#define my_pthread_getspecific(T,A) (&(A))
#define my_pthread_getspecific_ptr(T,V) (V)
#define my_pthread_setspecific_ptr(T,V) ((T)=(V),0)
#define pthread_setspecific(A,B) win_pthread_setspecific(&(A),(B),sizeof(A))
#endif /* USE_TLS */
#define pthread_equal(A,B) ((A) == (B))
#ifdef OS2
extern int pthread_mutex_init (pthread_mutex_t *, const pthread_mutexattr_t *);
extern int pthread_mutex_lock (pthread_mutex_t *);
extern int pthread_mutex_unlock (pthread_mutex_t *);
extern int pthread_mutex_destroy (pthread_mutex_t *);
#define my_pthread_setprio(A,B) DosSetPriority(PRTYS_THREAD,PRTYC_NOCHANGE, B, A)
#define pthread_kill(A,B) raise(B)
#define pthread_exit(A) pthread_dummy()
#else
#define pthread_mutex_init(A,B) InitializeCriticalSection(A)
#define pthread_mutex_lock(A) (EnterCriticalSection(A),0)
#define pthread_mutex_trylock(A) (WaitForSingleObject((A), 0) == WAIT_TIMEOUT)
#define pthread_mutex_unlock(A) LeaveCriticalSection(A)
#define pthread_mutex_destroy(A) DeleteCriticalSection(A)
#define my_pthread_setprio(A,B) SetThreadPriority(GetCurrentThread(), (B))
#define pthread_kill(A,B) pthread_dummy(0)
#endif /* OS2 */
/* Dummy defines for easier code */
#define pthread_attr_setdetachstate(A,B) pthread_dummy(0)
#define my_pthread_attr_setprio(A,B) pthread_attr_setprio(A,B)
#define pthread_attr_setscope(A,B)
#define pthread_detach_this_thread()
#define pthread_condattr_init(A)
#define pthread_condattr_destroy(A)
/*Irena: compiler does not like this: */
/*#define my_pthread_getprio(pthread_t thread_id) pthread_dummy(0) */
#define my_pthread_getprio(thread_id) pthread_dummy(0)
#elif defined(HAVE_UNIXWARE7_THREADS)
#include <thread.h>
#include <synch.h>
#ifndef _REENTRANT
#define _REENTRANT
#endif
#define HAVE_NONPOSIX_SIGWAIT
#define pthread_t thread_t
#define pthread_cond_t cond_t
#define pthread_mutex_t mutex_t
#define pthread_key_t thread_key_t
typedef int pthread_attr_t; /* Needed by Unixware 7.0.0 */
#define pthread_key_create(A,B) thr_keycreate((A),(B))
#define pthread_key_delete(A) thr_keydelete(A)
#define pthread_handler_decl(A,B) void *A(void *B)
#define pthread_key(T,V) pthread_key_t V
void * my_pthread_getspecific_imp(pthread_key_t key);
#define my_pthread_getspecific(A,B) ((A) my_pthread_getspecific_imp(B))
#define my_pthread_getspecific_ptr(T,V) my_pthread_getspecific(T,V)
#define pthread_setspecific(A,B) thr_setspecific(A,B)
#define my_pthread_setspecific_ptr(T,V) pthread_setspecific(T,V)
#define pthread_create(A,B,C,D) thr_create(NULL,65536L,(C),(D),THR_DETACHED,(A))
#define pthread_cond_init(a,b) cond_init((a),USYNC_THREAD,NULL)
#define pthread_cond_destroy(a) cond_destroy(a)
#define pthread_cond_signal(a) cond_signal(a)
#define pthread_cond_wait(a,b) cond_wait((a),(b))
#define pthread_cond_timedwait(a,b,c) cond_timedwait((a),(b),(c))
#define pthread_cond_broadcast(a) cond_broadcast(a)
#define pthread_mutex_init(a,b) mutex_init((a),USYNC_THREAD,NULL)
#define pthread_mutex_lock(a) mutex_lock(a)
#define pthread_mutex_unlock(a) mutex_unlock(a)
#define pthread_mutex_destroy(a) mutex_destroy(a)
#define pthread_self() thr_self()
#define pthread_exit(A) thr_exit(A)
#define pthread_equal(A,B) (((A) == (B)) ? 1 : 0)
#define pthread_kill(A,B) thr_kill((A),(B))
#define HAVE_PTHREAD_KILL
#define pthread_sigmask(A,B,C) thr_sigsetmask((A),(B),(C))
extern int my_sigwait(const sigset_t *set,int *sig);
#define pthread_detach_this_thread() pthread_dummy(0)
#define pthread_attr_init(A) pthread_dummy(0)
#define pthread_attr_destroy(A) pthread_dummy(0)
#define pthread_attr_setscope(A,B) pthread_dummy(0)
#define pthread_attr_setdetachstate(A,B) pthread_dummy(0)
#define my_pthread_setprio(A,B) pthread_dummy (0)
#define my_pthread_getprio(A) pthread_dummy (0)
#define my_pthread_attr_setprio(A,B) pthread_dummy(0)
#else /* Normal threads */
#ifdef HAVE_rts_threads
#define sigwait org_sigwait
#include <signal.h>
#undef sigwait
#endif
#undef _REENTRANT /* Fix if _REENTRANT is in pthread.h */
#include <pthread.h>
#ifndef _REENTRANT
#define _REENTRANT
#endif
#ifdef HAVE_THR_SETCONCURRENCY
#include <thread.h> /* Probably solaris */
#endif
#ifdef HAVE_SCHED_H
#include <sched.h>
#endif
#ifdef HAVE_SYNCH_H
#include <synch.h>
#endif
#if defined(__EMX__) && (!defined(EMX_PTHREAD_REV) || (EMX_PTHREAD_REV < 2))
#error Requires at least rev 2 of EMX pthreads library.
#endif
#ifdef __NETWARE__
void my_pthread_exit(void *status);
#define pthread_exit(A) my_pthread_exit(A)
#endif
extern int my_pthread_getprio(pthread_t thread_id);
#define pthread_key(T,V) pthread_key_t V
#define my_pthread_getspecific_ptr(T,V) my_pthread_getspecific(T,(V))
#define my_pthread_setspecific_ptr(T,V) pthread_setspecific(T,(void*) (V))
#define pthread_detach_this_thread()
#define pthread_handler_decl(A,B) void *A(void *B)
typedef void *(* pthread_handler)(void *);
/* Test first for RTS or FSU threads */
#if defined(PTHREAD_SCOPE_GLOBAL) && !defined(PTHREAD_SCOPE_SYSTEM)
#define HAVE_rts_threads
extern int my_pthread_create_detached;
#define pthread_sigmask(A,B,C) sigprocmask((A),(B),(C))
#define PTHREAD_CREATE_DETACHED &my_pthread_create_detached
#define PTHREAD_SCOPE_SYSTEM PTHREAD_SCOPE_GLOBAL
#define PTHREAD_SCOPE_PROCESS PTHREAD_SCOPE_LOCAL
#define USE_ALARM_THREAD
#elif defined(HAVE_mit_thread)
#define USE_ALARM_THREAD
#undef HAVE_LOCALTIME_R
#define HAVE_LOCALTIME_R
#undef HAVE_GMTIME_R
#define HAVE_GMTIME_R
#undef HAVE_PTHREAD_ATTR_SETSCOPE
#define HAVE_PTHREAD_ATTR_SETSCOPE
#undef HAVE_GETHOSTBYNAME_R_GLIBC2_STYLE /* If we are running linux */
#undef HAVE_RWLOCK_T
#undef HAVE_RWLOCK_INIT
#undef HAVE_PTHREAD_RWLOCK_RDLOCK
#undef HAVE_SNPRINTF
#define sigset(A,B) pthread_signal((A),(void (*)(int)) (B))
#define signal(A,B) pthread_signal((A),(void (*)(int)) (B))
#define my_pthread_attr_setprio(A,B)
#endif /* defined(PTHREAD_SCOPE_GLOBAL) && !defined(PTHREAD_SCOPE_SYSTEM) */
#if defined(_BSDI_VERSION) && _BSDI_VERSION < 199910
int sigwait(sigset_t *set, int *sig);
#endif
#if defined(HAVE_UNIXWARE7_POSIX)
#undef HAVE_NONPOSIX_SIGWAIT
#define HAVE_NONPOSIX_SIGWAIT /* sigwait takes only 1 argument */
#endif
#ifndef HAVE_NONPOSIX_SIGWAIT
#define my_sigwait(A,B) sigwait((A),(B))
#else
int my_sigwait(const sigset_t *set,int *sig);
#endif
#ifdef HAVE_NONPOSIX_PTHREAD_MUTEX_INIT
#ifndef SAFE_MUTEX
#define pthread_mutex_init(a,b) my_pthread_mutex_init((a),(b))
extern int my_pthread_mutex_init(pthread_mutex_t *mp,
const pthread_mutexattr_t *attr);
#endif /* SAFE_MUTEX */
#define pthread_cond_init(a,b) my_pthread_cond_init((a),(b))
extern int my_pthread_cond_init(pthread_cond_t *mp,
const pthread_condattr_t *attr);
#endif /* HAVE_NONPOSIX_PTHREAD_MUTEX_INIT */
#if defined(HAVE_SIGTHREADMASK) && !defined(HAVE_PTHREAD_SIGMASK)
#define pthread_sigmask(A,B,C) sigthreadmask((A),(B),(C))
#endif
#if !defined(HAVE_SIGWAIT) && !defined(HAVE_mit_thread) && !defined(HAVE_rts_threads) && !defined(sigwait) && !defined(alpha_linux_port) && !defined(HAVE_NONPOSIX_SIGWAIT) && !defined(HAVE_DEC_3_2_THREADS) && !defined(_AIX)
int sigwait(sigset_t *setp, int *sigp); /* Use our implemention */
#endif
#if !defined(HAVE_SIGSET) && !defined(HAVE_mit_thread) && !defined(sigset)
#define sigset(A,B) do { struct sigaction s; sigset_t set; \
sigemptyset(&set); \
s.sa_handler = (B); \
s.sa_mask = set; \
s.sa_flags = 0; \
sigaction((A), &s, (struct sigaction *) NULL); \
} while (0)
#endif
#ifndef my_pthread_setprio
#if defined(HAVE_PTHREAD_SETPRIO_NP) /* FSU threads */
#define my_pthread_setprio(A,B) pthread_setprio_np((A),(B))
#elif defined(HAVE_PTHREAD_SETPRIO)
#define my_pthread_setprio(A,B) pthread_setprio((A),(B))
#else
extern void my_pthread_setprio(pthread_t thread_id,int prior);
#endif
#endif
#ifndef my_pthread_attr_setprio
#ifdef HAVE_PTHREAD_ATTR_SETPRIO
#define my_pthread_attr_setprio(A,B) pthread_attr_setprio((A),(B))
#else
extern void my_pthread_attr_setprio(pthread_attr_t *attr, int priority);
#endif
#endif
#if !defined(HAVE_PTHREAD_ATTR_SETSCOPE) || defined(HAVE_DEC_3_2_THREADS)
#define pthread_attr_setscope(A,B)
#undef HAVE_GETHOSTBYADDR_R /* No definition */
#endif
#if defined(HAVE_BROKEN_PTHREAD_COND_TIMEDWAIT) && !defined(SAFE_MUTEX)
extern int my_pthread_cond_timedwait(pthread_cond_t *cond,
pthread_mutex_t *mutex,
struct timespec *abstime);
#define pthread_cond_timedwait(A,B,C) my_pthread_cond_timedwait((A),(B),(C))
#endif
#if defined(OS2)
#define my_pthread_getspecific(T,A) ((T) &(A))
#define pthread_setspecific(A,B) win_pthread_setspecific(&(A),(B),sizeof(A))
#elif !defined( HAVE_NONPOSIX_PTHREAD_GETSPECIFIC)
#define my_pthread_getspecific(A,B) ((A) pthread_getspecific(B))
#else
#define my_pthread_getspecific(A,B) ((A) my_pthread_getspecific_imp(B))
void *my_pthread_getspecific_imp(pthread_key_t key);
#endif /* OS2 */
#ifndef HAVE_LOCALTIME_R
struct tm *localtime_r(const time_t *clock, struct tm *res);
#endif
#ifndef HAVE_GMTIME_R
struct tm *gmtime_r(const time_t *clock, struct tm *res);
#endif
#ifdef HAVE_PTHREAD_CONDATTR_CREATE
/* DCE threads on HPUX 10.20 */
#define pthread_condattr_init pthread_condattr_create
#define pthread_condattr_destroy pthread_condattr_delete
#endif
/* FSU THREADS */
#if !defined(HAVE_PTHREAD_KEY_DELETE) && !defined(pthread_key_delete)
#define pthread_key_delete(A) pthread_dummy(0)
#endif
#ifdef HAVE_CTHREADS_WRAPPER /* For MacOSX */
#define pthread_cond_destroy(A) pthread_dummy(0)
#define pthread_mutex_destroy(A) pthread_dummy(0)
#define pthread_attr_delete(A) pthread_dummy(0)
#define pthread_condattr_delete(A) pthread_dummy(0)
#define pthread_attr_setstacksize(A,B) pthread_dummy(0)
#define pthread_equal(A,B) ((A) == (B))
#define pthread_cond_timedwait(a,b,c) pthread_cond_wait((a),(b))
#define pthread_attr_init(A) pthread_attr_create(A)
#define pthread_attr_destroy(A) pthread_attr_delete(A)
#define pthread_attr_setdetachstate(A,B) pthread_dummy(0)
#define pthread_create(A,B,C,D) pthread_create((A),*(B),(C),(D))
#define pthread_sigmask(A,B,C) sigprocmask((A),(B),(C))
#define pthread_kill(A,B) pthread_dummy(0)
#undef pthread_detach_this_thread
#define pthread_detach_this_thread() { pthread_t tmp=pthread_self() ; pthread_detach(&tmp); }
#endif
#ifdef HAVE_DARWIN_THREADS
#define pthread_sigmask(A,B,C) sigprocmask((A),(B),(C))
#define pthread_kill(A,B) pthread_dummy(0)
#define pthread_condattr_init(A) pthread_dummy(0)
#define pthread_condattr_destroy(A) pthread_dummy(0)
#define pthread_signal(A,B) pthread_dummy(0)
#undef pthread_detach_this_thread
#define pthread_detach_this_thread() { pthread_t tmp=pthread_self() ; pthread_detach(tmp); }
#undef sigset
#define sigset(A,B) pthread_signal((A),(void (*)(int)) (B))
#endif
#if ((defined(HAVE_PTHREAD_ATTR_CREATE) && !defined(HAVE_SIGWAIT)) || defined(HAVE_DEC_3_2_THREADS)) && !defined(HAVE_CTHREADS_WRAPPER)
/* This is set on AIX_3_2 and Siemens unix (and DEC OSF/1 3.2 too) */
#define pthread_key_create(A,B) \
pthread_keycreate(A,(B) ?\
(pthread_destructor_t) (B) :\
(pthread_destructor_t) pthread_dummy)
#define pthread_attr_init(A) pthread_attr_create(A)
#define pthread_attr_destroy(A) pthread_attr_delete(A)
#define pthread_attr_setdetachstate(A,B) pthread_dummy(0)
#define pthread_create(A,B,C,D) pthread_create((A),*(B),(C),(D))
#ifndef pthread_sigmask
#define pthread_sigmask(A,B,C) sigprocmask((A),(B),(C))
#endif
#define pthread_kill(A,B) pthread_dummy(0)
#undef pthread_detach_this_thread
#define pthread_detach_this_thread() { pthread_t tmp=pthread_self() ; pthread_detach(&tmp); }
#elif !defined(__NETWARE__) /* HAVE_PTHREAD_ATTR_CREATE && !HAVE_SIGWAIT */
#define HAVE_PTHREAD_KILL
#endif
#endif /* defined(__WIN__) */
#if defined(HPUX10) && !defined(DONT_REMAP_PTHREAD_FUNCTIONS)
#undef pthread_cond_timedwait
#define pthread_cond_timedwait(a,b,c) my_pthread_cond_timedwait((a),(b),(c))
int my_pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex,
struct timespec *abstime);
#endif
#if defined(HPUX10)
#define pthread_attr_getstacksize(A,B) my_pthread_attr_getstacksize(A,B)
void my_pthread_attr_getstacksize(pthread_attr_t *attrib, size_t *size);
#endif
#if defined(HAVE_POSIX1003_4a_MUTEX) && !defined(DONT_REMAP_PTHREAD_FUNCTIONS)
#undef pthread_mutex_trylock
#define pthread_mutex_trylock(a) my_pthread_mutex_trylock((a))
int my_pthread_mutex_trylock(pthread_mutex_t *mutex);
#endif
/* safe_mutex adds checking to mutex for easier debugging */
#if defined(__NETWARE__) && !defined(SAFE_MUTEX_DETECT_DESTROY)
#define SAFE_MUTEX_DETECT_DESTROY
#endif
typedef struct st_safe_mutex_t
{
pthread_mutex_t global,mutex;
const char *file;
uint line,count;
pthread_t thread;
#ifdef SAFE_MUTEX_DETECT_DESTROY
struct st_safe_mutex_info_t *info; /* to track destroying of mutexes */
#endif
} safe_mutex_t;
#ifdef SAFE_MUTEX_DETECT_DESTROY
/*
Used to track the destroying of mutexes. This needs to be a seperate
structure because the safe_mutex_t structure could be freed before
the mutexes are destroyed.
*/
typedef struct st_safe_mutex_info_t
{
struct st_safe_mutex_info_t *next;
struct st_safe_mutex_info_t *prev;
const char *init_file;
uint32 init_line;
} safe_mutex_info_t;
#endif /* SAFE_MUTEX_DETECT_DESTROY */
int safe_mutex_init(safe_mutex_t *mp, const pthread_mutexattr_t *attr,
const char *file, uint line);
int safe_mutex_lock(safe_mutex_t *mp,const char *file, uint line);
int safe_mutex_unlock(safe_mutex_t *mp,const char *file, uint line);
int safe_mutex_destroy(safe_mutex_t *mp,const char *file, uint line);
int safe_cond_wait(pthread_cond_t *cond, safe_mutex_t *mp,const char *file,
uint line);
int safe_cond_timedwait(pthread_cond_t *cond, safe_mutex_t *mp,
struct timespec *abstime, const char *file, uint line);
void safe_mutex_global_init(void);
void safe_mutex_end(FILE *file);
/* Wrappers if safe mutex is actually used */
#ifdef SAFE_MUTEX
#undef pthread_mutex_init
#undef pthread_mutex_lock
#undef pthread_mutex_unlock
#undef pthread_mutex_destroy
#undef pthread_mutex_wait
#undef pthread_mutex_timedwait
#undef pthread_mutex_t
#undef pthread_cond_wait
#undef pthread_cond_timedwait
#undef pthread_mutex_trylock
#define pthread_mutex_init(A,B) safe_mutex_init((A),(B),__FILE__,__LINE__)
#define pthread_mutex_lock(A) safe_mutex_lock((A),__FILE__,__LINE__)
#define pthread_mutex_unlock(A) safe_mutex_unlock((A),__FILE__,__LINE__)
#define pthread_mutex_destroy(A) safe_mutex_destroy((A),__FILE__,__LINE__)
#define pthread_cond_wait(A,B) safe_cond_wait((A),(B),__FILE__,__LINE__)
#define pthread_cond_timedwait(A,B,C) safe_cond_timedwait((A),(B),(C),__FILE__,__LINE__)
#define pthread_mutex_trylock(A) pthread_mutex_lock(A)
#define pthread_mutex_t safe_mutex_t
#define safe_mutex_assert_owner(mp) DBUG_ASSERT((mp)->count > 0 && pthread_equal(pthread_self(),(mp)->thread))
#else
#define safe_mutex_assert_owner(mp)
#endif /* SAFE_MUTEX */
/* READ-WRITE thread locking */
#ifdef HAVE_BROKEN_RWLOCK /* For OpenUnix */
#undef HAVE_PTHREAD_RWLOCK_RDLOCK
#undef HAVE_RWLOCK_INIT
#undef HAVE_RWLOCK_T
#endif
#if defined(USE_MUTEX_INSTEAD_OF_RW_LOCKS)
/* use these defs for simple mutex locking */
#define rw_lock_t pthread_mutex_t
#define my_rwlock_init(A,B) pthread_mutex_init((A),(B))
#define rw_rdlock(A) pthread_mutex_lock((A))
#define rw_wrlock(A) pthread_mutex_lock((A))
#define rw_tryrdlock(A) pthread_mutex_trylock((A))
#define rw_trywrlock(A) pthread_mutex_trylock((A))
#define rw_unlock(A) pthread_mutex_unlock((A))
#define rwlock_destroy(A) pthread_mutex_destroy((A))
#elif defined(HAVE_PTHREAD_RWLOCK_RDLOCK)
#define rw_lock_t pthread_rwlock_t
#define my_rwlock_init(A,B) pthread_rwlock_init((A),(B))
#define rw_rdlock(A) pthread_rwlock_rdlock(A)
#define rw_wrlock(A) pthread_rwlock_wrlock(A)
#define rw_tryrdlock(A) pthread_rwlock_tryrdlock((A))
#define rw_trywrlock(A) pthread_rwlock_trywrlock((A))
#define rw_unlock(A) pthread_rwlock_unlock(A)
#define rwlock_destroy(A) pthread_rwlock_destroy(A)
#elif defined(HAVE_RWLOCK_INIT)
#ifdef HAVE_RWLOCK_T /* For example Solaris 2.6-> */
#define rw_lock_t rwlock_t
#endif
#define my_rwlock_init(A,B) rwlock_init((A),USYNC_THREAD,0)
#else
/* Use our own version of read/write locks */
typedef struct _my_rw_lock_t {
pthread_mutex_t lock; /* lock for structure */
pthread_cond_t readers; /* waiting readers */
pthread_cond_t writers; /* waiting writers */
int state; /* -1:writer,0:free,>0:readers */
int waiters; /* number of waiting writers */
} my_rw_lock_t;
#define rw_lock_t my_rw_lock_t
#define rw_rdlock(A) my_rw_rdlock((A))
#define rw_wrlock(A) my_rw_wrlock((A))
#define rw_tryrdlock(A) my_rw_tryrdlock((A))
#define rw_trywrlock(A) my_rw_trywrlock((A))
#define rw_unlock(A) my_rw_unlock((A))
#define rwlock_destroy(A) my_rwlock_destroy((A))
extern int my_rwlock_init(my_rw_lock_t *, void *);
extern int my_rwlock_destroy(my_rw_lock_t *);
extern int my_rw_rdlock(my_rw_lock_t *);
extern int my_rw_wrlock(my_rw_lock_t *);
extern int my_rw_unlock(my_rw_lock_t *);
extern int my_rw_tryrdlock(my_rw_lock_t *);
extern int my_rw_trywrlock(my_rw_lock_t *);
#endif /* USE_MUTEX_INSTEAD_OF_RW_LOCKS */
#define GETHOSTBYADDR_BUFF_SIZE 2048
#ifndef HAVE_THR_SETCONCURRENCY
#define thr_setconcurrency(A) pthread_dummy(0)
#endif
#if !defined(HAVE_PTHREAD_ATTR_SETSTACKSIZE) && ! defined(pthread_attr_setstacksize)
#define pthread_attr_setstacksize(A,B) pthread_dummy(0)
#endif
/* Define mutex types */
#define MY_MUTEX_INIT_SLOW NULL
#define MY_MUTEX_INIT_FAST NULL
#define MY_MUTEX_INIT_ERRCHK NULL
#ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
extern pthread_mutexattr_t my_fast_mutexattr;
#undef MY_MUTEX_INIT_FAST
#define MY_MUTEX_INIT_FAST &my_fast_mutexattr
#endif
#ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
extern pthread_mutexattr_t my_errchk_mutexattr;
#undef MY_INIT_MUTEX_ERRCHK
#define MY_INIT_MUTEX_ERRCHK &my_errchk_mutexattr
#endif
extern my_bool my_thread_global_init(void);
extern void my_thread_global_end(void);
extern my_bool my_thread_init(void);
extern void my_thread_end(void);
extern const char *my_thread_name(void);
extern long my_thread_id(void);
extern int pthread_no_free(void *);
extern int pthread_dummy(int);
/* All thread specific variables are in the following struct */
#define THREAD_NAME_SIZE 10
#if defined(__ia64__)
/*
MySQL can survive with 32K, but some glibc libraries require > 128K stack
To resolve hostnames
*/
#define DEFAULT_THREAD_STACK (192*1024L)
#else
#define DEFAULT_THREAD_STACK (192*1024)
#endif
struct st_my_thread_var
{
int thr_errno;
pthread_cond_t suspend;
pthread_mutex_t mutex;
pthread_mutex_t * volatile current_mutex;
pthread_cond_t * volatile current_cond;
pthread_t pthread_self;
long id;
int cmp_length;
int volatile abort;
my_bool init;
struct st_my_thread_var *next,**prev;
void *opt_info;
#ifndef DBUG_OFF
gptr dbug;
char name[THREAD_NAME_SIZE+1];
#endif
};
extern struct st_my_thread_var *_my_thread_var(void) __attribute__ ((const));
#define my_thread_var (_my_thread_var())
#define my_errno my_thread_var->thr_errno
/*
Keep track of shutdown,signal, and main threads so that my_end() will not
report errors with them
*/
extern pthread_t shutdown_th, main_th, signal_th;
/* statistics_xxx functions are for not essential statistic */
#ifndef thread_safe_increment
#ifdef HAVE_ATOMIC_ADD
#define thread_safe_increment(V,L) atomic_add(1,(atomic_t*) &V);
#define thread_safe_add(V,C,L) atomic_add((C),(atomic_t*) &V);
#define thread_safe_sub(V,C,L) atomic_sub((C),(atomic_t*) &V);
#else
#define thread_safe_increment(V,L) \
pthread_mutex_lock((L)); (V)++; pthread_mutex_unlock((L));
#define thread_safe_add(V,C,L) \
pthread_mutex_lock((L)); (V)+=(C); pthread_mutex_unlock((L));
#define thread_safe_sub(V,C,L) \
pthread_mutex_lock((L)); (V)-=(C); pthread_mutex_unlock((L));
#endif /* HAVE_ATOMIC_ADD */
#ifdef SAFE_STATISTICS
#define statistic_increment(V,L) thread_safe_increment((V),(L))
#define statistic_add(V,C,L) thread_safe_add((V),(C),(L))
#else
#define statistic_increment(V,L) (V)++
#define statistic_add(V,C,L) (V)+=(C)
#endif /* SAFE_STATISTICS */
#endif /* thread_safe_increment */
#ifdef __cplusplus
}
#endif
#endif /* _my_ptread_h */
+64
View File
@@ -0,0 +1,64 @@
/*
* Module: semaphore.h
*
* Purpose:
* Semaphores aren't actually part of the PThreads standard.
* They are defined by the POSIX Standard:
*
* POSIX 1003.1b-1993 (POSIX.1b)
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright (C) 1998
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA
*/
/* This is hacked by Monty to be included in mysys library */
#ifndef _my_semaphore_h_
#define _my_semaphore_h_
#ifdef THREAD
C_MODE_START
#ifdef HAVE_SEMAPHORE_H
#include <semaphore.h>
#elif !defined(__bsdi__)
#ifdef __WIN__
typedef HANDLE sem_t;
#else
typedef struct {
pthread_mutex_t mutex;
pthread_cond_t cond;
uint count;
} sem_t;
#endif /* __WIN__ */
int sem_init(sem_t * sem, int pshared, unsigned int value);
int sem_destroy(sem_t * sem);
int sem_trywait(sem_t * sem);
int sem_wait(sem_t * sem);
int sem_post(sem_t * sem);
int sem_post_multiple(sem_t * sem, unsigned int count);
int sem_getvalue(sem_t * sem, unsigned int * sval);
#endif /* !__bsdi__ */
C_MODE_END
#endif /* THREAD */
#endif /* !_my_semaphore_h_ */
+778
View File
@@ -0,0 +1,778 @@
/* Copyright (C) 2000-2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef _my_sys_h
#define _my_sys_h
C_MODE_START
#ifdef HAVE_AIOWAIT
#include <sys/asynch.h> /* Used by record-cache */
typedef struct my_aio_result {
aio_result_t result;
int pending;
} my_aio_result;
#endif
#ifndef THREAD
extern int NEAR my_errno; /* Last error in mysys */
#else
#include <my_pthread.h>
#endif
#ifndef _m_ctype_h
#include <m_ctype.h> /* for CHARSET_INFO */
#endif
#include <stdarg.h>
#include <typelib.h>
#define MYSYS_PROGRAM_USES_CURSES() { error_handler_hook = my_message_curses; mysys_uses_curses=1; }
#define MYSYS_PROGRAM_DONT_USE_CURSES() { error_handler_hook = my_message_no_curses; mysys_uses_curses=0;}
#define MY_INIT(name); { my_progname= name; my_init(); }
#define MAXMAPS (4) /* Number of error message maps */
#define ERRMOD (1000) /* Max number of errors in a map */
#define ERRMSGSIZE (SC_MAXWIDTH) /* Max length of a error message */
#define NRERRBUFFS (2) /* Buffers for parameters */
#define MY_FILE_ERROR ((uint) ~0)
/* General bitmaps for my_func's */
#define MY_FFNF 1 /* Fatal if file not found */
#define MY_FNABP 2 /* Fatal if not all bytes read/writen */
#define MY_NABP 4 /* Error if not all bytes read/writen */
#define MY_FAE 8 /* Fatal if any error */
#define MY_WME 16 /* Write message on error */
#define MY_WAIT_IF_FULL 32 /* Wait and try again if disk full error */
#define MY_RAID 64 /* Support for RAID (not the "Johnson&Johnson"-s one ;) */
#define MY_FULL_IO 512 /* For my_read - loop intil I/O
is complete
*/
#define MY_DONT_CHECK_FILESIZE 128 /* Option to init_io_cache() */
#define MY_LINK_WARNING 32 /* my_redel() gives warning if links */
#define MY_COPYTIME 64 /* my_redel() copys time */
#define MY_DELETE_OLD 256 /* my_create_with_symlink() */
#define MY_RESOLVE_LINK 128 /* my_realpath(); Only resolve links */
#define MY_HOLD_ORIGINAL_MODES 128 /* my_copy() holds to file modes */
#define MY_REDEL_MAKE_BACKUP 256
#define MY_SEEK_NOT_DONE 32 /* my_lock may have to do a seek */
#define MY_DONT_WAIT 64 /* my_lock() don't wait if can't lock */
#define MY_ZEROFILL 32 /* my_malloc(), fill array with zero */
#define MY_ALLOW_ZERO_PTR 64 /* my_realloc() ; zero ptr -> malloc */
#define MY_FREE_ON_ERROR 128 /* my_realloc() ; Free old ptr on error */
#define MY_HOLD_ON_ERROR 256 /* my_realloc() ; Return old ptr on error */
#define MY_THREADSAFE 128 /* pread/pwrite: Don't allow interrupts */
#define MY_DONT_OVERWRITE_FILE 1024 /* my_copy; Don't overwrite file */
#define MY_CHECK_ERROR 1 /* Params to my_end; Check open-close */
#define MY_GIVE_INFO 2 /* Give time info about process*/
#define ME_HIGHBYTE 8 /* Shift for colours */
#define ME_NOCUR 1 /* Don't use curses message */
#define ME_OLDWIN 2 /* Use old window */
#define ME_BELL 4 /* Ring bell then printing message */
#define ME_HOLDTANG 8 /* Don't delete last keys */
#define ME_WAITTOT 16 /* Wait for errtime secs of for a action */
#define ME_WAITTANG 32 /* Wait for a user action */
#define ME_NOREFRESH 64 /* Dont refresh screen */
#define ME_NOINPUT 128 /* Dont use the input libary */
#define ME_COLOUR1 ((1 << ME_HIGHBYTE)) /* Possibly error-colours */
#define ME_COLOUR2 ((2 << ME_HIGHBYTE))
#define ME_COLOUR3 ((3 << ME_HIGHBYTE))
/* Bits in last argument to fn_format */
#define MY_REPLACE_DIR 1 /* replace dir in name with 'dir' */
#define MY_REPLACE_EXT 2 /* replace extension with 'ext' */
#define MY_UNPACK_FILENAME 4 /* Unpack name (~ -> home) */
#define MY_PACK_FILENAME 8 /* Pack name (home -> ~) */
#define MY_RESOLVE_SYMLINKS 16 /* Resolve all symbolic links */
#define MY_RETURN_REAL_PATH 32 /* return full path for file */
#define MY_SAFE_PATH 64 /* Return NULL if too long path */
#define MY_RELATIVE_PATH 128 /* name is relative to 'dir' */
/* My seek flags */
#define MY_SEEK_SET 0
#define MY_SEEK_CUR 1
#define MY_SEEK_END 2
/* Some constants */
#define MY_WAIT_FOR_USER_TO_FIX_PANIC 60 /* in seconds */
#define MY_WAIT_GIVE_USER_A_MESSAGE 10 /* Every 10 times of prev */
#define MIN_COMPRESS_LENGTH 50 /* Don't compress small bl. */
#define DFLT_INIT_HITS 3
/* root_alloc flags */
#define MY_KEEP_PREALLOC 1
#define MY_MARK_BLOCKS_FREE 2 /* move used to free list and reuse them */
/* Internal error numbers (for assembler functions) */
#define MY_ERRNO_EDOM 33
#define MY_ERRNO_ERANGE 34
/* defines when allocating data */
#ifdef SAFEMALLOC
#define my_malloc(SZ,FLAG) _mymalloc((SZ), __FILE__, __LINE__, FLAG )
#define my_malloc_ci(SZ,FLAG) _mymalloc((SZ), sFile, uLine, FLAG )
#define my_realloc(PTR,SZ,FLAG) _myrealloc((PTR), (SZ), __FILE__, __LINE__, FLAG )
#define my_checkmalloc() _sanity( __FILE__, __LINE__ )
#define my_free(PTR,FLAG) _myfree((PTR), __FILE__, __LINE__,FLAG)
#define my_memdup(A,B,C) _my_memdup((A),(B), __FILE__,__LINE__,C)
#define my_strdup(A,C) _my_strdup((A), __FILE__,__LINE__,C)
#define my_strdup_with_length(A,B,C) _my_strdup_with_length((A),(B),__FILE__,__LINE__,C)
#define QUICK_SAFEMALLOC sf_malloc_quick=1
#define NORMAL_SAFEMALLOC sf_malloc_quick=0
extern uint sf_malloc_prehunc,sf_malloc_endhunc,sf_malloc_quick;
extern ulonglong sf_malloc_mem_limit;
#define CALLER_INFO_PROTO , const char *sFile, uint uLine
#define CALLER_INFO , __FILE__, __LINE__
#define ORIG_CALLER_INFO , sFile, uLine
#else
#define my_checkmalloc()
#undef TERMINATE
#define TERMINATE(A) {}
#define QUICK_SAFEMALLOC
#define NORMAL_SAFEMALLOC
extern gptr my_malloc(uint Size,myf MyFlags);
#define my_malloc_ci(SZ,FLAG) my_malloc( SZ, FLAG )
extern gptr my_realloc(gptr oldpoint,uint Size,myf MyFlags);
extern void my_no_flags_free(gptr ptr);
extern gptr my_memdup(const byte *from,uint length,myf MyFlags);
extern char *my_strdup(const char *from,myf MyFlags);
extern char *my_strdup_with_length(const byte *from, uint length,
myf MyFlags);
#define my_free(PTR,FG) my_no_flags_free(PTR)
#define CALLER_INFO_PROTO /* nothing */
#define CALLER_INFO /* nothing */
#define ORIG_CALLER_INFO /* nothing */
#endif
#ifdef HAVE_ALLOCA
#if defined(_AIX) && !defined(__GNUC__) && !defined(_AIX43)
#pragma alloca
#endif /* _AIX */
#if defined(__GNUC__) && !defined(HAVE_ALLOCA_H) && ! defined(alloca)
#define alloca __builtin_alloca
#endif /* GNUC */
#define my_alloca(SZ) alloca((size_t) (SZ))
#define my_afree(PTR) {}
#else
#define my_alloca(SZ) my_malloc(SZ,MYF(0))
#define my_afree(PTR) my_free(PTR,MYF(MY_WME))
#endif /* HAVE_ALLOCA */
#ifdef MSDOS
#ifdef __ZTC__
void * __CDECL halloc(long count,size_t length);
void __CDECL hfree(void *ptr);
#endif
#if defined(USE_HALLOC)
#if defined(_VCM_) || defined(M_IC80386)
#undef USE_HALLOC
#endif
#endif
#ifdef USE_HALLOC
#define malloc(a) halloc((long) (a),1)
#define free(a) hfree(a)
#endif
#endif /* MSDOS */
#ifdef HAVE_ERRNO_AS_DEFINE
#include <errno.h> /* errno is a define */
#else
extern int errno; /* declare errno */
#endif
extern const char ** NEAR my_errmsg[];
extern char NEAR errbuff[NRERRBUFFS][ERRMSGSIZE];
extern char *home_dir; /* Home directory for user */
extern char *my_progname; /* program-name (printed in errors) */
extern char NEAR curr_dir[]; /* Current directory for user */
extern int (*error_handler_hook)(uint my_err, const char *str,myf MyFlags);
extern int (*fatal_error_handler_hook)(uint my_err, const char *str,
myf MyFlags);
extern uint my_file_limit;
/* charsets */
extern CHARSET_INFO *default_charset_info;
extern CHARSET_INFO *all_charsets[256];
extern CHARSET_INFO compiled_charsets[];
/* statistics */
extern ulong my_cache_w_requests, my_cache_write, my_cache_r_requests,
my_cache_read;
extern ulong my_blocks_used, my_blocks_changed;
extern ulong my_file_opened,my_stream_opened, my_tmp_file_created;
extern my_bool my_init_done;
/* Point to current my_message() */
extern void (*my_sigtstp_cleanup)(void),
/* Executed before jump to shell */
(*my_sigtstp_restart)(void),
(*my_abort_hook)(int);
/* Executed when comming from shell */
extern int NEAR my_umask, /* Default creation mask */
NEAR my_umask_dir,
NEAR my_recived_signals, /* Signals we have got */
NEAR my_safe_to_handle_signal, /* Set when allowed to SIGTSTP */
NEAR my_dont_interrupt; /* call remember_intr when set */
extern my_bool NEAR mysys_uses_curses, my_use_symdir;
extern ulong sf_malloc_cur_memory, sf_malloc_max_memory;
extern ulong my_default_record_cache_size;
extern my_bool NEAR my_disable_locking,NEAR my_disable_async_io,
NEAR my_disable_flush_key_blocks, NEAR my_disable_symlinks;
extern char wild_many,wild_one,wild_prefix;
extern const char *charsets_dir;
extern char *defaults_extra_file;
typedef struct wild_file_pack /* Struct to hold info when selecting files */
{
uint wilds; /* How many wildcards */
uint not_pos; /* Start of not-theese-files */
my_string *wild; /* Pointer to wildcards */
} WF_PACK;
enum cache_type
{
READ_CACHE,WRITE_CACHE,
SEQ_READ_APPEND /* sequential read or append */,
READ_FIFO, READ_NET,WRITE_NET};
enum flush_type
{
FLUSH_KEEP, FLUSH_RELEASE, FLUSH_IGNORE_CHANGED, FLUSH_FORCE_WRITE
};
typedef struct st_record_cache /* Used when cacheing records */
{
File file;
int rc_seek,error,inited;
uint rc_length,read_length,reclength;
my_off_t rc_record_pos,end_of_file;
byte *rc_buff,*rc_buff2,*rc_pos,*rc_end,*rc_request_pos;
#ifdef HAVE_AIOWAIT
int use_async_io;
my_aio_result aio_result;
#endif
enum cache_type type;
} RECORD_CACHE;
enum file_type
{
UNOPEN = 0, FILE_BY_OPEN, FILE_BY_CREATE, STREAM_BY_FOPEN, STREAM_BY_FDOPEN,
FILE_BY_MKSTEMP, FILE_BY_DUP
};
struct st_my_file_info
{
my_string name;
enum file_type type;
#if defined(THREAD) && !defined(HAVE_PREAD)
pthread_mutex_t mutex;
#endif
};
extern struct st_my_file_info *my_file_info;
typedef struct st_my_tmpdir
{
char **list;
uint cur, max;
#ifdef THREAD
pthread_mutex_t mutex;
#endif
} MY_TMPDIR;
typedef struct st_dynamic_array
{
char *buffer;
uint elements,max_element;
uint alloc_increment;
uint size_of_element;
} DYNAMIC_ARRAY;
typedef struct st_dynamic_string
{
char *str;
uint length,max_length,alloc_increment;
} DYNAMIC_STRING;
struct st_io_cache;
typedef int (*IO_CACHE_CALLBACK)(struct st_io_cache*);
#ifdef THREAD
typedef struct st_io_cache_share
{
/* to sync on reads into buffer */
pthread_mutex_t mutex;
pthread_cond_t cond;
int count, total;
/* actual IO_CACHE that filled the buffer */
struct st_io_cache *active;
#ifdef NOT_YET_IMPLEMENTED
/* whether the structure should be free'd */
my_bool alloced;
#endif
} IO_CACHE_SHARE;
#endif
typedef struct st_io_cache /* Used when cacheing files */
{
/* Offset in file corresponding to the first byte of byte* buffer. */
my_off_t pos_in_file;
/*
The offset of end of file for READ_CACHE and WRITE_CACHE.
For SEQ_READ_APPEND it the maximum of the actual end of file and
the position represented by read_end.
*/
my_off_t end_of_file;
/* Points to current read position in the buffer */
byte *read_pos;
/* the non-inclusive boundary in the buffer for the currently valid read */
byte *read_end;
byte *buffer; /* The read buffer */
/* Used in ASYNC_IO */
byte *request_pos;
/* Only used in WRITE caches and in SEQ_READ_APPEND to buffer writes */
byte *write_buffer;
/*
Only used in SEQ_READ_APPEND, and points to the current read position
in the write buffer. Note that reads in SEQ_READ_APPEND caches can
happen from both read buffer (byte* buffer) and write buffer
(byte* write_buffer).
*/
byte *append_read_pos;
/* Points to current write position in the write buffer */
byte *write_pos;
/* The non-inclusive boundary of the valid write area */
byte *write_end;
/*
Current_pos and current_end are convenience variables used by
my_b_tell() and other routines that need to know the current offset
current_pos points to &write_pos, and current_end to &write_end in a
WRITE_CACHE, and &read_pos and &read_end respectively otherwise
*/
byte **current_pos, **current_end;
#ifdef THREAD
/*
The lock is for append buffer used in SEQ_READ_APPEND cache
need mutex copying from append buffer to read buffer.
*/
pthread_mutex_t append_buffer_lock;
/*
The following is used when several threads are reading the
same file in parallel. They are synchronized on disk
accesses reading the cached part of the file asynchronously.
It should be set to NULL to disable the feature. Only
READ_CACHE mode is supported.
*/
IO_CACHE_SHARE *share;
#endif
/*
A caller will use my_b_read() macro to read from the cache
if the data is already in cache, it will be simply copied with
memcpy() and internal variables will be accordinging updated with
no functions invoked. However, if the data is not fully in the cache,
my_b_read() will call read_function to fetch the data. read_function
must never be invoked directly.
*/
int (*read_function)(struct st_io_cache *,byte *,uint);
/*
Same idea as in the case of read_function, except my_b_write() needs to
be replaced with my_b_append() for a SEQ_READ_APPEND cache
*/
int (*write_function)(struct st_io_cache *,const byte *,uint);
/*
Specifies the type of the cache. Depending on the type of the cache
certain operations might not be available and yield unpredicatable
results. Details to be documented later
*/
enum cache_type type;
/*
Callbacks when the actual read I/O happens. These were added and
are currently used for binary logging of LOAD DATA INFILE - when a
block is read from the file, we create a block create/append event, and
when IO_CACHE is closed, we create an end event. These functions could,
of course be used for other things
*/
IO_CACHE_CALLBACK pre_read;
IO_CACHE_CALLBACK post_read;
IO_CACHE_CALLBACK pre_close;
/*
Counts the number of times, when we were forced to use disk. We use it to
increase the binlog_cache_disk_use status variable.
*/
ulong disk_writes;
void* arg; /* for use by pre/post_read */
char *file_name; /* if used with 'open_cached_file' */
char *dir,*prefix;
File file; /* file descriptor */
/*
seek_not_done is set by my_b_seek() to inform the upcoming read/write
operation that a seek needs to be preformed prior to the actual I/O
error is 0 if the cache operation was successful, -1 if there was a
"hard" error, and the actual number of I/O-ed bytes if the read/write was
partial.
*/
int seek_not_done,error;
/* buffer_length is memory size allocated for buffer or write_buffer */
uint buffer_length;
/* read_length is the same as buffer_length except when we use async io */
uint read_length;
myf myflags; /* Flags used to my_read/my_write */
/*
alloced_buffer is 1 if the buffer was allocated by init_io_cache() and
0 if it was supplied by the user.
Currently READ_NET is the only one that will use a buffer allocated
somewhere else
*/
my_bool alloced_buffer;
#ifdef HAVE_AIOWAIT
/*
As inidicated by ifdef, this is for async I/O, which is not currently
used (because it's not reliable on all systems)
*/
uint inited;
my_off_t aio_read_pos;
my_aio_result aio_result;
#endif
} IO_CACHE;
typedef int (*qsort2_cmp)(const void *, const void *, const void *);
/* defines for mf_iocache */
/* Test if buffer is inited */
#define my_b_clear(info) (info)->buffer=0
#define my_b_inited(info) (info)->buffer
#define my_b_EOF INT_MIN
#define my_b_read(info,Buffer,Count) \
((info)->read_pos + (Count) <= (info)->read_end ?\
(memcpy(Buffer,(info)->read_pos,(size_t) (Count)), \
((info)->read_pos+=(Count)),0) :\
(*(info)->read_function)((info),Buffer,Count))
#define my_b_write(info,Buffer,Count) \
((info)->write_pos + (Count) <=(info)->write_end ?\
(memcpy((info)->write_pos, (Buffer), (size_t)(Count)),\
((info)->write_pos+=(Count)),0) : \
(*(info)->write_function)((info),(Buffer),(Count)))
#define my_b_get(info) \
((info)->read_pos != (info)->read_end ?\
((info)->read_pos++, (int) (uchar) (info)->read_pos[-1]) :\
_my_b_get(info))
/* my_b_write_byte dosn't have any err-check */
#define my_b_write_byte(info,chr) \
(((info)->write_pos < (info)->write_end) ?\
((*(info)->write_pos++)=(chr)) :\
(_my_b_write(info,0,0) , ((*(info)->write_pos++)=(chr))))
#define my_b_fill_cache(info) \
(((info)->read_end=(info)->read_pos),(*(info)->read_function)(info,0,0))
#define my_b_tell(info) ((info)->pos_in_file + \
(uint) (*(info)->current_pos - (info)->request_pos))
/* tell write offset in the SEQ_APPEND cache */
my_off_t my_b_append_tell(IO_CACHE* info);
#define my_b_bytes_in_cache(info) (uint) (*(info)->current_end - \
*(info)->current_pos)
typedef uint32 ha_checksum;
#include <my_alloc.h>
/* Prototypes for mysys and my_func functions */
extern int my_copy(const char *from,const char *to,myf MyFlags);
extern int my_append(const char *from,const char *to,myf MyFlags);
extern int my_delete(const char *name,myf MyFlags);
extern int my_getwd(my_string buf,uint size,myf MyFlags);
extern int my_setwd(const char *dir,myf MyFlags);
extern int my_lock(File fd,int op,my_off_t start, my_off_t length,myf MyFlags);
extern gptr my_once_alloc(uint Size,myf MyFlags);
extern void my_once_free(void);
extern char *my_once_strdup(const char *src,myf myflags);
extern char *my_once_memdup(const char *src, uint len, myf myflags);
extern my_string my_tempnam(const char *dir,const char *pfx,myf MyFlags);
extern File my_open(const char *FileName,int Flags,myf MyFlags);
extern File my_register_filename(File fd, const char *FileName,
enum file_type type_of_file,
uint error_message_number, myf MyFlags);
extern File my_create(const char *FileName,int CreateFlags,
int AccsesFlags, myf MyFlags);
extern int my_close(File Filedes,myf MyFlags);
extern File my_dup(File file, myf MyFlags);
extern int my_mkdir(const char *dir, int Flags, myf MyFlags);
extern int my_readlink(char *to, const char *filename, myf MyFlags);
extern int my_realpath(char *to, const char *filename, myf MyFlags);
extern File my_create_with_symlink(const char *linkname, const char *filename,
int createflags, int access_flags,
myf MyFlags);
extern int my_delete_with_symlink(const char *name, myf MyFlags);
extern int my_rename_with_symlink(const char *from,const char *to,myf MyFlags);
extern int my_symlink(const char *content, const char *linkname, myf MyFlags);
extern uint my_read(File Filedes,byte *Buffer,uint Count,myf MyFlags);
extern uint my_pread(File Filedes,byte *Buffer,uint Count,my_off_t offset,
myf MyFlags);
extern int my_rename(const char *from,const char *to,myf MyFlags);
extern my_off_t my_seek(File fd,my_off_t pos,int whence,myf MyFlags);
extern my_off_t my_tell(File fd,myf MyFlags);
extern uint my_write(File Filedes,const byte *Buffer,uint Count,
myf MyFlags);
extern uint my_pwrite(File Filedes,const byte *Buffer,uint Count,
my_off_t offset,myf MyFlags);
extern uint my_fread(FILE *stream,byte *Buffer,uint Count,myf MyFlags);
extern uint my_fwrite(FILE *stream,const byte *Buffer,uint Count,
myf MyFlags);
extern my_off_t my_fseek(FILE *stream,my_off_t pos,int whence,myf MyFlags);
extern my_off_t my_ftell(FILE *stream,myf MyFlags);
extern gptr _mymalloc(uint uSize,const char *sFile,
uint uLine, myf MyFlag);
extern gptr _myrealloc(gptr pPtr,uint uSize,const char *sFile,
uint uLine, myf MyFlag);
extern gptr my_multi_malloc _VARARGS((myf MyFlags, ...));
extern void _myfree(gptr pPtr,const char *sFile,uint uLine, myf MyFlag);
extern int _sanity(const char *sFile,unsigned int uLine);
extern gptr _my_memdup(const byte *from,uint length,
const char *sFile, uint uLine,myf MyFlag);
extern my_string _my_strdup(const char *from, const char *sFile, uint uLine,
myf MyFlag);
extern char *_my_strdup_with_length(const byte *from, uint length,
const char *sFile, uint uLine,
myf MyFlag);
#ifndef TERMINATE
extern void TERMINATE(FILE *file);
#endif
extern void init_glob_errs(void);
extern FILE *my_fopen(const char *FileName,int Flags,myf MyFlags);
extern FILE *my_fdopen(File Filedes,const char *name, int Flags,myf MyFlags);
extern int my_fclose(FILE *fd,myf MyFlags);
extern int my_chsize(File fd,my_off_t newlength, int filler, myf MyFlags);
extern int my_sync(File fd, myf my_flags);
extern int my_error _VARARGS((int nr,myf MyFlags, ...));
extern int my_printf_error _VARARGS((uint my_err, const char *format,
myf MyFlags, ...)
__attribute__ ((format (printf, 2, 4))));
extern int my_message(uint my_err, const char *str,myf MyFlags);
extern int my_message_no_curses(uint my_err, const char *str,myf MyFlags);
extern int my_message_curses(uint my_err, const char *str,myf MyFlags);
extern my_bool my_init(void);
extern void my_end(int infoflag);
extern int my_redel(const char *from, const char *to, int MyFlags);
extern int my_copystat(const char *from, const char *to, int MyFlags);
extern my_string my_filename(File fd);
#ifndef THREAD
extern void dont_break(void);
extern void allow_break(void);
#else
#define dont_break()
#define allow_break()
#endif
extern my_bool init_tmpdir(MY_TMPDIR *tmpdir, const char *pathlist);
extern char *my_tmpdir(MY_TMPDIR *tmpdir);
extern void free_tmpdir(MY_TMPDIR *tmpdir);
extern void my_remember_signal(int signal_number,sig_handler (*func)(int));
extern uint dirname_part(my_string to,const char *name);
extern uint dirname_length(const char *name);
#define base_name(A) (A+dirname_length(A))
extern int test_if_hard_path(const char *dir_name);
extern char *convert_dirname(char *to, const char *from, const char *from_end);
extern void to_unix_path(my_string name);
extern my_string fn_ext(const char *name);
extern my_string fn_same(my_string toname,const char *name,int flag);
extern my_string fn_format(my_string to,const char *name,const char *dir,
const char *form, uint flag);
extern size_s strlength(const char *str);
extern void pack_dirname(my_string to,const char *from);
extern uint unpack_dirname(my_string to,const char *from);
extern uint cleanup_dirname(my_string to,const char *from);
extern uint system_filename(my_string to,const char *from);
extern uint unpack_filename(my_string to,const char *from);
extern my_string intern_filename(my_string to,const char *from);
extern my_string directory_file_name(my_string dst, const char *src);
extern int pack_filename(my_string to, const char *name, size_s max_length);
extern my_string my_path(my_string to,const char *progname,
const char *own_pathname_part);
extern my_string my_load_path(my_string to, const char *path,
const char *own_path_prefix);
extern int wild_compare(const char *str,const char *wildstr,pbool str_is_pattern);
extern WF_PACK *wf_comp(my_string str);
extern int wf_test(struct wild_file_pack *wf_pack,const char *name);
extern void wf_end(struct wild_file_pack *buffer);
extern size_s strip_sp(my_string str);
extern void get_date(my_string to,int timeflag,time_t use_time);
extern void soundex(CHARSET_INFO *, my_string out_pntr, my_string in_pntr,pbool remove_garbage);
extern int init_record_cache(RECORD_CACHE *info,uint cachesize,File file,
uint reclength,enum cache_type type,
pbool use_async_io);
extern int read_cache_record(RECORD_CACHE *info,byte *to);
extern int end_record_cache(RECORD_CACHE *info);
extern int write_cache_record(RECORD_CACHE *info,my_off_t filepos,
const byte *record,uint length);
extern int flush_write_cache(RECORD_CACHE *info);
extern long my_clock(void);
extern sig_handler sigtstp_handler(int signal_number);
extern void handle_recived_signals(void);
extern sig_handler my_set_alarm_variable(int signo);
extern void my_string_ptr_sort(void *base,uint items,size_s size);
extern void radixsort_for_str_ptr(uchar* base[], uint number_of_elements,
size_s size_of_element,uchar *buffer[]);
extern qsort_t qsort2(void *base_ptr, size_t total_elems, size_t size,
qsort2_cmp cmp, void *cmp_argument);
extern qsort2_cmp get_ptr_compare(uint);
extern int init_io_cache(IO_CACHE *info,File file,uint cachesize,
enum cache_type type,my_off_t seek_offset,
pbool use_async_io, myf cache_myflags);
extern my_bool reinit_io_cache(IO_CACHE *info,enum cache_type type,
my_off_t seek_offset,pbool use_async_io,
pbool clear_cache);
extern int _my_b_read(IO_CACHE *info,byte *Buffer,uint Count);
#ifdef THREAD
extern int _my_b_read_r(IO_CACHE *info,byte *Buffer,uint Count);
extern void init_io_cache_share(IO_CACHE *info,
IO_CACHE_SHARE *s, uint num_threads);
extern void remove_io_thread(IO_CACHE *info);
#endif
extern int _my_b_seq_read(IO_CACHE *info,byte *Buffer,uint Count);
extern int _my_b_net_read(IO_CACHE *info,byte *Buffer,uint Count);
extern int _my_b_get(IO_CACHE *info);
extern int _my_b_async_read(IO_CACHE *info,byte *Buffer,uint Count);
extern int _my_b_write(IO_CACHE *info,const byte *Buffer,uint Count);
extern int my_b_append(IO_CACHE *info,const byte *Buffer,uint Count);
extern int my_b_safe_write(IO_CACHE *info,const byte *Buffer,uint Count);
extern int my_block_write(IO_CACHE *info, const byte *Buffer,
uint Count, my_off_t pos);
extern int my_b_flush_io_cache(IO_CACHE *info, int need_append_buffer_lock);
#define flush_io_cache(info) my_b_flush_io_cache((info),1)
extern int end_io_cache(IO_CACHE *info);
extern uint my_b_fill(IO_CACHE *info);
extern void my_b_seek(IO_CACHE *info,my_off_t pos);
extern uint my_b_gets(IO_CACHE *info, char *to, uint max_length);
extern my_off_t my_b_filelength(IO_CACHE *info);
extern uint my_b_printf(IO_CACHE *info, const char* fmt, ...);
extern uint my_b_vprintf(IO_CACHE *info, const char* fmt, va_list ap);
extern my_bool open_cached_file(IO_CACHE *cache,const char *dir,
const char *prefix, uint cache_size,
myf cache_myflags);
extern my_bool real_open_cached_file(IO_CACHE *cache);
extern void close_cached_file(IO_CACHE *cache);
File create_temp_file(char *to, const char *dir, const char *pfx,
int mode, myf MyFlags);
#define my_init_dynamic_array(A,B,C,D) init_dynamic_array(A,B,C,D CALLER_INFO)
#define my_init_dynamic_array_ci(A,B,C,D) init_dynamic_array(A,B,C,D ORIG_CALLER_INFO)
extern my_bool init_dynamic_array(DYNAMIC_ARRAY *array,uint element_size,
uint init_alloc,uint alloc_increment CALLER_INFO_PROTO);
extern my_bool insert_dynamic(DYNAMIC_ARRAY *array,gptr element);
extern byte *alloc_dynamic(DYNAMIC_ARRAY *array);
extern byte *pop_dynamic(DYNAMIC_ARRAY*);
extern my_bool set_dynamic(DYNAMIC_ARRAY *array,gptr element,uint array_index);
extern void get_dynamic(DYNAMIC_ARRAY *array,gptr element,uint array_index);
extern void delete_dynamic(DYNAMIC_ARRAY *array);
extern void delete_dynamic_element(DYNAMIC_ARRAY *array, uint array_index);
extern void freeze_size(DYNAMIC_ARRAY *array);
#define dynamic_array_ptr(array,array_index) ((array)->buffer+(array_index)*(array)->size_of_element)
#define dynamic_element(array,array_index,type) ((type)((array)->buffer) +(array_index))
#define push_dynamic(A,B) insert_dynamic(A,B)
#define reset_dynamic(array) ((array)->elements= 0)
extern my_bool init_dynamic_string(DYNAMIC_STRING *str, const char *init_str,
uint init_alloc,uint alloc_increment);
extern my_bool dynstr_append(DYNAMIC_STRING *str, const char *append);
my_bool dynstr_append_mem(DYNAMIC_STRING *str, const char *append,
uint length);
extern my_bool dynstr_set(DYNAMIC_STRING *str, const char *init_str);
extern my_bool dynstr_realloc(DYNAMIC_STRING *str, ulong additional_size);
extern void dynstr_free(DYNAMIC_STRING *str);
#ifdef HAVE_MLOCK
extern byte *my_malloc_lock(uint length,myf flags);
extern void my_free_lock(byte *ptr,myf flags);
#else
#define my_malloc_lock(A,B) my_malloc((A),(B))
#define my_free_lock(A,B) my_free((A),(B))
#endif
#define alloc_root_inited(A) ((A)->min_malloc != 0)
#define clear_alloc_root(A) bzero((void *) (A), sizeof(MEM_ROOT))
extern void init_alloc_root(MEM_ROOT *mem_root, uint block_size,
uint pre_alloc_size);
extern gptr alloc_root(MEM_ROOT *mem_root,unsigned int Size);
extern void free_root(MEM_ROOT *root, myf MyFLAGS);
extern void set_prealloc_root(MEM_ROOT *root, char *ptr);
extern void reset_root_defaults(MEM_ROOT *mem_root, uint block_size,
uint prealloc_size);
extern char *strdup_root(MEM_ROOT *root,const char *str);
extern char *strmake_root(MEM_ROOT *root,const char *str,uint len);
extern char *memdup_root(MEM_ROOT *root,const char *str,uint len);
extern int load_defaults(const char *conf_file, const char **groups,
int *argc, char ***argv);
extern void free_defaults(char **argv);
extern void print_defaults(const char *conf_file, const char **groups);
extern my_bool my_compress(byte *, ulong *, ulong *);
extern my_bool my_uncompress(byte *, ulong *, ulong *);
extern byte *my_compress_alloc(const byte *packet, ulong *len, ulong *complen);
extern ha_checksum my_checksum(ha_checksum crc, const byte *mem, uint count);
extern uint my_bit_log2(ulong value);
extern uint my_count_bits(ulonglong v);
extern void my_sleep(ulong m_seconds);
extern ulong crc32(ulong crc, const uchar *buf, uint len);
extern uint my_set_max_open_files(uint files);
void my_free_open_file_info(void);
ulonglong my_getsystime(void);
my_bool my_gethwaddr(uchar *to);
/* character sets */
extern uint get_charset_number(const char *cs_name, uint cs_flags);
extern uint get_collation_number(const char *name);
extern const char *get_charset_name(uint cs_number);
extern CHARSET_INFO *get_charset(uint cs_number, myf flags);
extern CHARSET_INFO *get_charset_by_name(const char *cs_name, myf flags);
extern CHARSET_INFO *get_charset_by_csname(const char *cs_name,
uint cs_flags, myf my_flags);
extern void free_charsets(void);
extern char *get_charsets_dir(char *buf);
extern my_bool my_charset_same(CHARSET_INFO *cs1, CHARSET_INFO *cs2);
extern my_bool init_compiled_charsets(myf flags);
extern void add_compiled_collation(CHARSET_INFO *cs);
extern ulong escape_string_for_mysql(CHARSET_INFO *charset_info, char *to,
const char *from, ulong length);
#ifdef __WIN__
extern my_bool have_tcpip; /* Is set if tcpip is used */
#endif
#ifdef __NETWARE__
void netware_reg_user(const char *ip, const char *user,
const char *application);
#endif
C_MODE_END
#include "raid.h"
#endif /* _my_sys_h */
+67
View File
@@ -0,0 +1,67 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef _my_xml_h
#define _my_xml_h
#ifdef __cplusplus
extern "C" {
#endif
#define MY_XML_OK 0
#define MY_XML_ERROR 1
typedef struct xml_stack_st
{
char errstr[128];
char attr[128];
char *attrend;
const char *beg;
const char *cur;
const char *end;
void *user_data;
int (*enter)(struct xml_stack_st *st,const char *val, uint len);
int (*value)(struct xml_stack_st *st,const char *val, uint len);
int (*leave_xml)(struct xml_stack_st *st,const char *val, uint len);
} MY_XML_PARSER;
void my_xml_parser_create(MY_XML_PARSER *st);
void my_xml_parser_free(MY_XML_PARSER *st);
int my_xml_parse(MY_XML_PARSER *st,const char *str, uint len);
void my_xml_set_value_handler(MY_XML_PARSER *st, int (*)(MY_XML_PARSER *,
const char *,
uint len));
void my_xml_set_enter_handler(MY_XML_PARSER *st, int (*)(MY_XML_PARSER *,
const char *,
uint len));
void my_xml_set_leave_handler(MY_XML_PARSER *st, int (*)(MY_XML_PARSER *,
const char *,
uint len));
void my_xml_set_user_data(MY_XML_PARSER *st, void *);
uint my_xml_error_pos(MY_XML_PARSER *st);
uint my_xml_error_lineno(MY_XML_PARSER *st);
const char *my_xml_error_string(MY_XML_PARSER *st);
#ifdef __cplusplus
}
#endif
#endif /* _my_xml_h */
+740
View File
@@ -0,0 +1,740 @@
/* Copyright (C) 2000-2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef _mysql_h
#define _mysql_h
#ifdef __CYGWIN__ /* CYGWIN implements a UNIX API */
#undef WIN
#undef _WIN
#undef _WIN32
#undef _WIN64
#undef __WIN__
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _global_h /* If not standard header */
#include <sys/types.h>
#ifdef __LCC__
#include <winsock.h> /* For windows */
#endif
typedef char my_bool;
#if (defined(_WIN32) || defined(_WIN64)) && !defined(__WIN__)
#define __WIN__
#endif
#if !defined(__WIN__)
#define STDCALL
#else
#define STDCALL __stdcall
#endif
typedef char * gptr;
#ifndef my_socket_defined
#ifdef __WIN__
#define my_socket SOCKET
#else
typedef int my_socket;
#endif /* __WIN__ */
#endif /* my_socket_defined */
#endif /* _global_h */
#include "mysql_com.h"
#include "mysql_time.h"
#include "mysql_version.h"
#include "typelib.h"
#include "my_list.h" /* for LISTs used in 'MYSQL' and 'MYSQL_STMT' */
extern unsigned int mysql_port;
extern char *mysql_unix_port;
#define CLIENT_NET_READ_TIMEOUT 365*24*3600 /* Timeout on read */
#define CLIENT_NET_WRITE_TIMEOUT 365*24*3600 /* Timeout on write */
#ifdef __NETWARE__
#pragma pack(push, 8) /* 8 byte alignment */
#endif
#define IS_PRI_KEY(n) ((n) & PRI_KEY_FLAG)
#define IS_NOT_NULL(n) ((n) & NOT_NULL_FLAG)
#define IS_BLOB(n) ((n) & BLOB_FLAG)
#define IS_NUM(t) ((t) <= FIELD_TYPE_INT24 || (t) == FIELD_TYPE_YEAR)
#define IS_NUM_FIELD(f) ((f)->flags & NUM_FLAG)
#define INTERNAL_NUM_FIELD(f) (((f)->type <= FIELD_TYPE_INT24 && ((f)->type != FIELD_TYPE_TIMESTAMP || (f)->length == 14 || (f)->length == 8)) || (f)->type == FIELD_TYPE_YEAR)
typedef struct st_mysql_field {
char *name; /* Name of column */
char *org_name; /* Original column name, if an alias */
char *table; /* Table of column if column was a field */
char *org_table; /* Org table name, if table was an alias */
char *db; /* Database for table */
char *catalog; /* Catalog for table */
char *def; /* Default value (set by mysql_list_fields) */
unsigned long length; /* Width of column (create length) */
unsigned long max_length; /* Max width for selected set */
unsigned int name_length;
unsigned int org_name_length;
unsigned int table_length;
unsigned int org_table_length;
unsigned int db_length;
unsigned int catalog_length;
unsigned int def_length;
unsigned int flags; /* Div flags */
unsigned int decimals; /* Number of decimals in field */
unsigned int charsetnr; /* Character set */
enum enum_field_types type; /* Type of field. Se mysql_com.h for types */
} MYSQL_FIELD;
typedef char **MYSQL_ROW; /* return data as array of strings */
typedef unsigned int MYSQL_FIELD_OFFSET; /* offset to current field */
#ifndef _global_h
#if defined(NO_CLIENT_LONG_LONG)
typedef unsigned long my_ulonglong;
#elif defined (__WIN__)
typedef unsigned __int64 my_ulonglong;
#else
typedef unsigned long long my_ulonglong;
#endif
#endif
#define MYSQL_COUNT_ERROR (~(my_ulonglong) 0)
typedef struct st_mysql_rows {
struct st_mysql_rows *next; /* list of rows */
MYSQL_ROW data;
unsigned long length;
} MYSQL_ROWS;
typedef MYSQL_ROWS *MYSQL_ROW_OFFSET; /* offset to current row */
#include "my_alloc.h"
typedef struct st_mysql_data {
my_ulonglong rows;
unsigned int fields;
MYSQL_ROWS *data;
MEM_ROOT alloc;
#if !defined(CHECK_EMBEDDED_DIFFERENCES) || defined(EMBEDDED_LIBRARY)
MYSQL_ROWS **prev_ptr;
#endif
} MYSQL_DATA;
enum mysql_option
{
MYSQL_OPT_CONNECT_TIMEOUT, MYSQL_OPT_COMPRESS, MYSQL_OPT_NAMED_PIPE,
MYSQL_INIT_COMMAND, MYSQL_READ_DEFAULT_FILE, MYSQL_READ_DEFAULT_GROUP,
MYSQL_SET_CHARSET_DIR, MYSQL_SET_CHARSET_NAME, MYSQL_OPT_LOCAL_INFILE,
MYSQL_OPT_PROTOCOL, MYSQL_SHARED_MEMORY_BASE_NAME, MYSQL_OPT_READ_TIMEOUT,
MYSQL_OPT_WRITE_TIMEOUT, MYSQL_OPT_USE_RESULT,
MYSQL_OPT_USE_REMOTE_CONNECTION, MYSQL_OPT_USE_EMBEDDED_CONNECTION,
MYSQL_OPT_GUESS_CONNECTION, MYSQL_SET_CLIENT_IP, MYSQL_SECURE_AUTH
};
struct st_mysql_options {
unsigned int connect_timeout, read_timeout, write_timeout;
unsigned int port, protocol;
unsigned long client_flag;
char *host,*user,*password,*unix_socket,*db;
struct st_dynamic_array *init_commands;
char *my_cnf_file,*my_cnf_group, *charset_dir, *charset_name;
char *ssl_key; /* PEM key file */
char *ssl_cert; /* PEM cert file */
char *ssl_ca; /* PEM CA file */
char *ssl_capath; /* PEM directory of CA-s? */
char *ssl_cipher; /* cipher to use */
char *shared_memory_base_name;
unsigned long max_allowed_packet;
my_bool use_ssl; /* if to use SSL or not */
my_bool compress,named_pipe;
/*
On connect, find out the replication role of the server, and
establish connections to all the peers
*/
my_bool rpl_probe;
/*
Each call to mysql_real_query() will parse it to tell if it is a read
or a write, and direct it to the slave or the master
*/
my_bool rpl_parse;
/*
If set, never read from a master,only from slave, when doing
a read that is replication-aware
*/
my_bool no_master_reads;
#if !defined(CHECK_EMBEDDED_DIFFERENCES) || defined(EMBEDDED_LIBRARY)
my_bool separate_thread;
#endif
enum mysql_option methods_to_use;
char *client_ip;
/* Refuse client connecting to server if it uses old (pre-4.1.1) protocol */
my_bool secure_auth;
/* function pointers for local infile support */
int (*local_infile_init)(void **, const char *, void *);
int (*local_infile_read)(void *, char *, unsigned int);
void (*local_infile_end)(void *);
int (*local_infile_error)(void *, char *, unsigned int);
void *local_infile_userdata;
};
enum mysql_status
{
MYSQL_STATUS_READY,MYSQL_STATUS_GET_RESULT,MYSQL_STATUS_USE_RESULT
};
enum mysql_protocol_type
{
MYSQL_PROTOCOL_DEFAULT, MYSQL_PROTOCOL_TCP, MYSQL_PROTOCOL_SOCKET,
MYSQL_PROTOCOL_PIPE, MYSQL_PROTOCOL_MEMORY
};
/*
There are three types of queries - the ones that have to go to
the master, the ones that go to a slave, and the adminstrative
type which must happen on the pivot connectioin
*/
enum mysql_rpl_type
{
MYSQL_RPL_MASTER, MYSQL_RPL_SLAVE, MYSQL_RPL_ADMIN
};
struct st_mysql_methods;
typedef struct st_mysql
{
NET net; /* Communication parameters */
gptr connector_fd; /* ConnectorFd for SSL */
char *host,*user,*passwd,*unix_socket,*server_version,*host_info,*info;
char *db;
struct charset_info_st *charset;
MYSQL_FIELD *fields;
MEM_ROOT field_alloc;
my_ulonglong affected_rows;
my_ulonglong insert_id; /* id if insert on table with NEXTNR */
my_ulonglong extra_info; /* Used by mysqlshow */
unsigned long thread_id; /* Id for connection in server */
unsigned long packet_length;
unsigned int port;
unsigned long client_flag,server_capabilities;
unsigned int protocol_version;
unsigned int field_count;
unsigned int server_status;
unsigned int server_language;
unsigned int warning_count;
struct st_mysql_options options;
enum mysql_status status;
my_bool free_me; /* If free in mysql_close */
my_bool reconnect; /* set to 1 if automatic reconnect */
/* session-wide random string */
char scramble[SCRAMBLE_LENGTH+1];
/*
Set if this is the original connection, not a master or a slave we have
added though mysql_rpl_probe() or mysql_set_master()/ mysql_add_slave()
*/
my_bool rpl_pivot;
/*
Pointers to the master, and the next slave connections, points to
itself if lone connection.
*/
struct st_mysql* master, *next_slave;
struct st_mysql* last_used_slave; /* needed for round-robin slave pick */
/* needed for send/read/store/use result to work correctly with replication */
struct st_mysql* last_used_con;
LIST *stmts; /* list of all statements */
const struct st_mysql_methods *methods;
void *thd;
/*
Points to boolean flag in MYSQL_RES or MYSQL_STMT. We set this flag
from mysql_stmt_close if close had to cancel result set of this object.
*/
my_bool *unbuffered_fetch_owner;
} MYSQL;
typedef struct st_mysql_res {
my_ulonglong row_count;
MYSQL_FIELD *fields;
MYSQL_DATA *data;
MYSQL_ROWS *data_cursor;
unsigned long *lengths; /* column lengths of current row */
MYSQL *handle; /* for unbuffered reads */
MEM_ROOT field_alloc;
unsigned int field_count, current_field;
MYSQL_ROW row; /* If unbuffered read */
MYSQL_ROW current_row; /* buffer to current row */
my_bool eof; /* Used by mysql_fetch_row */
/* mysql_stmt_close() had to cancel this result */
my_bool unbuffered_fetch_cancelled;
const struct st_mysql_methods *methods;
} MYSQL_RES;
#define MAX_MYSQL_MANAGER_ERR 256
#define MAX_MYSQL_MANAGER_MSG 256
#define MANAGER_OK 200
#define MANAGER_INFO 250
#define MANAGER_ACCESS 401
#define MANAGER_CLIENT_ERR 450
#define MANAGER_INTERNAL_ERR 500
#if !defined(MYSQL_SERVER) && !defined(MYSQL_CLIENT)
#define MYSQL_CLIENT
#endif
typedef struct st_mysql_manager
{
NET net;
char *host,*user,*passwd;
unsigned int port;
my_bool free_me;
my_bool eof;
int cmd_status;
int last_errno;
char* net_buf,*net_buf_pos,*net_data_end;
int net_buf_size;
char last_error[MAX_MYSQL_MANAGER_ERR];
} MYSQL_MANAGER;
typedef struct st_mysql_parameters
{
unsigned long *p_max_allowed_packet;
unsigned long *p_net_buffer_length;
} MYSQL_PARAMETERS;
#if !defined(MYSQL_SERVER) && !defined(EMBEDDED_LIBRARY)
#define max_allowed_packet (*mysql_get_parameters()->p_max_allowed_packet)
#define net_buffer_length (*mysql_get_parameters()->p_net_buffer_length)
#endif
/*
Set up and bring down the server; to ensure that applications will
work when linked against either the standard client library or the
embedded server library, these functions should be called.
*/
int STDCALL mysql_server_init(int argc, char **argv, char **groups);
void STDCALL mysql_server_end(void);
MYSQL_PARAMETERS *STDCALL mysql_get_parameters(void);
/*
Set up and bring down a thread; these function should be called
for each thread in an application which opens at least one MySQL
connection. All uses of the connection(s) should be between these
function calls.
*/
my_bool STDCALL mysql_thread_init(void);
void STDCALL mysql_thread_end(void);
/*
Functions to get information from the MYSQL and MYSQL_RES structures
Should definitely be used if one uses shared libraries.
*/
my_ulonglong STDCALL mysql_num_rows(MYSQL_RES *res);
unsigned int STDCALL mysql_num_fields(MYSQL_RES *res);
my_bool STDCALL mysql_eof(MYSQL_RES *res);
MYSQL_FIELD *STDCALL mysql_fetch_field_direct(MYSQL_RES *res,
unsigned int fieldnr);
MYSQL_FIELD * STDCALL mysql_fetch_fields(MYSQL_RES *res);
MYSQL_ROW_OFFSET STDCALL mysql_row_tell(MYSQL_RES *res);
MYSQL_FIELD_OFFSET STDCALL mysql_field_tell(MYSQL_RES *res);
unsigned int STDCALL mysql_field_count(MYSQL *mysql);
my_ulonglong STDCALL mysql_affected_rows(MYSQL *mysql);
my_ulonglong STDCALL mysql_insert_id(MYSQL *mysql);
unsigned int STDCALL mysql_errno(MYSQL *mysql);
const char * STDCALL mysql_error(MYSQL *mysql);
const char *STDCALL mysql_sqlstate(MYSQL *mysql);
unsigned int STDCALL mysql_warning_count(MYSQL *mysql);
const char * STDCALL mysql_info(MYSQL *mysql);
unsigned long STDCALL mysql_thread_id(MYSQL *mysql);
const char * STDCALL mysql_character_set_name(MYSQL *mysql);
MYSQL * STDCALL mysql_init(MYSQL *mysql);
my_bool STDCALL mysql_ssl_set(MYSQL *mysql, const char *key,
const char *cert, const char *ca,
const char *capath, const char *cipher);
my_bool STDCALL mysql_change_user(MYSQL *mysql, const char *user,
const char *passwd, const char *db);
MYSQL * STDCALL mysql_real_connect(MYSQL *mysql, const char *host,
const char *user,
const char *passwd,
const char *db,
unsigned int port,
const char *unix_socket,
unsigned long clientflag);
int STDCALL mysql_select_db(MYSQL *mysql, const char *db);
int STDCALL mysql_query(MYSQL *mysql, const char *q);
int STDCALL mysql_send_query(MYSQL *mysql, const char *q,
unsigned long length);
int STDCALL mysql_real_query(MYSQL *mysql, const char *q,
unsigned long length);
MYSQL_RES * STDCALL mysql_store_result(MYSQL *mysql);
MYSQL_RES * STDCALL mysql_use_result(MYSQL *mysql);
/* perform query on master */
my_bool STDCALL mysql_master_query(MYSQL *mysql, const char *q,
unsigned long length);
my_bool STDCALL mysql_master_send_query(MYSQL *mysql, const char *q,
unsigned long length);
/* perform query on slave */
my_bool STDCALL mysql_slave_query(MYSQL *mysql, const char *q,
unsigned long length);
my_bool STDCALL mysql_slave_send_query(MYSQL *mysql, const char *q,
unsigned long length);
/* local infile support */
#define LOCAL_INFILE_ERROR_LEN 512
void
mysql_set_local_infile_handler(MYSQL *mysql,
int (*local_infile_init)(void **, const char *,
void *),
int (*local_infile_read)(void *, char *,
unsigned int),
void (*local_infile_end)(void *),
int (*local_infile_error)(void *, char*,
unsigned int),
void *);
void
mysql_set_local_infile_default(MYSQL *mysql);
/*
enable/disable parsing of all queries to decide if they go on master or
slave
*/
void STDCALL mysql_enable_rpl_parse(MYSQL* mysql);
void STDCALL mysql_disable_rpl_parse(MYSQL* mysql);
/* get the value of the parse flag */
int STDCALL mysql_rpl_parse_enabled(MYSQL* mysql);
/* enable/disable reads from master */
void STDCALL mysql_enable_reads_from_master(MYSQL* mysql);
void STDCALL mysql_disable_reads_from_master(MYSQL* mysql);
/* get the value of the master read flag */
my_bool STDCALL mysql_reads_from_master_enabled(MYSQL* mysql);
enum mysql_rpl_type STDCALL mysql_rpl_query_type(const char* q, int len);
/* discover the master and its slaves */
my_bool STDCALL mysql_rpl_probe(MYSQL* mysql);
/* set the master, close/free the old one, if it is not a pivot */
int STDCALL mysql_set_master(MYSQL* mysql, const char* host,
unsigned int port,
const char* user,
const char* passwd);
int STDCALL mysql_add_slave(MYSQL* mysql, const char* host,
unsigned int port,
const char* user,
const char* passwd);
int STDCALL mysql_shutdown(MYSQL *mysql,
enum enum_shutdown_level
shutdown_level);
int STDCALL mysql_dump_debug_info(MYSQL *mysql);
int STDCALL mysql_refresh(MYSQL *mysql,
unsigned int refresh_options);
int STDCALL mysql_kill(MYSQL *mysql,unsigned long pid);
int STDCALL mysql_set_server_option(MYSQL *mysql,
enum enum_mysql_set_option
option);
int STDCALL mysql_ping(MYSQL *mysql);
const char * STDCALL mysql_stat(MYSQL *mysql);
const char * STDCALL mysql_get_server_info(MYSQL *mysql);
const char * STDCALL mysql_get_client_info(void);
unsigned long STDCALL mysql_get_client_version(void);
const char * STDCALL mysql_get_host_info(MYSQL *mysql);
unsigned long STDCALL mysql_get_server_version(MYSQL *mysql);
unsigned int STDCALL mysql_get_proto_info(MYSQL *mysql);
MYSQL_RES * STDCALL mysql_list_dbs(MYSQL *mysql,const char *wild);
MYSQL_RES * STDCALL mysql_list_tables(MYSQL *mysql,const char *wild);
MYSQL_RES * STDCALL mysql_list_processes(MYSQL *mysql);
int STDCALL mysql_options(MYSQL *mysql,enum mysql_option option,
const char *arg);
void STDCALL mysql_free_result(MYSQL_RES *result);
void STDCALL mysql_data_seek(MYSQL_RES *result,
my_ulonglong offset);
MYSQL_ROW_OFFSET STDCALL mysql_row_seek(MYSQL_RES *result,
MYSQL_ROW_OFFSET offset);
MYSQL_FIELD_OFFSET STDCALL mysql_field_seek(MYSQL_RES *result,
MYSQL_FIELD_OFFSET offset);
MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result);
unsigned long * STDCALL mysql_fetch_lengths(MYSQL_RES *result);
MYSQL_FIELD * STDCALL mysql_fetch_field(MYSQL_RES *result);
MYSQL_RES * STDCALL mysql_list_fields(MYSQL *mysql, const char *table,
const char *wild);
unsigned long STDCALL mysql_escape_string(char *to,const char *from,
unsigned long from_length);
unsigned long STDCALL mysql_real_escape_string(MYSQL *mysql,
char *to,const char *from,
unsigned long length);
void STDCALL mysql_debug(const char *debug);
char * STDCALL mysql_odbc_escape_string(MYSQL *mysql,
char *to,
unsigned long to_length,
const char *from,
unsigned long from_length,
void *param,
char *
(*extend_buffer)
(void *, char *to,
unsigned long *length));
void STDCALL myodbc_remove_escape(MYSQL *mysql,char *name);
unsigned int STDCALL mysql_thread_safe(void);
MYSQL_MANAGER* STDCALL mysql_manager_init(MYSQL_MANAGER* con);
MYSQL_MANAGER* STDCALL mysql_manager_connect(MYSQL_MANAGER* con,
const char* host,
const char* user,
const char* passwd,
unsigned int port);
void STDCALL mysql_manager_close(MYSQL_MANAGER* con);
int STDCALL mysql_manager_command(MYSQL_MANAGER* con,
const char* cmd, int cmd_len);
int STDCALL mysql_manager_fetch_line(MYSQL_MANAGER* con,
char* res_buf,
int res_buf_size);
my_bool STDCALL mysql_read_query_result(MYSQL *mysql);
/*
The following definitions are added for the enhanced
client-server protocol
*/
/* statement state */
enum enum_mysql_stmt_state
{
MYSQL_STMT_INIT_DONE= 1, MYSQL_STMT_PREPARE_DONE, MYSQL_STMT_EXECUTE_DONE,
MYSQL_STMT_FETCH_DONE
};
/* bind structure */
typedef struct st_mysql_bind
{
unsigned long *length; /* output length pointer */
my_bool *is_null; /* Pointer to null indicators */
void *buffer; /* buffer to get/put data */
enum enum_field_types buffer_type; /* buffer type */
unsigned long buffer_length; /* buffer length, must be set for str/binary */
/* Following are for internal use. Set by mysql_stmt_bind_param */
unsigned char *inter_buffer; /* for the current data position */
unsigned long offset; /* offset position for char/binary fetch */
unsigned long internal_length; /* Used if length is 0 */
unsigned int param_number; /* For null count and error messages */
unsigned int pack_length; /* Internal length for packed data */
my_bool is_unsigned; /* set if integer type is unsigned */
my_bool long_data_used; /* If used with mysql_send_long_data */
my_bool internal_is_null; /* Used if is_null is 0 */
void (*store_param_func)(NET *net, struct st_mysql_bind *param);
void (*fetch_result)(struct st_mysql_bind *, unsigned char **row);
void (*skip_result)(struct st_mysql_bind *, MYSQL_FIELD *,
unsigned char **row);
} MYSQL_BIND;
/* statement handler */
typedef struct st_mysql_stmt
{
MEM_ROOT mem_root; /* root allocations */
LIST list; /* list to keep track of all stmts */
MYSQL *mysql; /* connection handle */
MYSQL_BIND *params; /* input parameters */
MYSQL_BIND *bind; /* output parameters */
MYSQL_FIELD *fields; /* result set metadata */
MYSQL_DATA result; /* cached result set */
MYSQL_ROWS *data_cursor; /* current row in cached result */
/* copy of mysql->affected_rows after statement execution */
my_ulonglong affected_rows;
my_ulonglong insert_id; /* copy of mysql->insert_id */
/*
mysql_stmt_fetch() calls this function to fetch one row (it's different
for buffered, unbuffered and cursor fetch).
*/
int (*read_row_func)(struct st_mysql_stmt *stmt,
unsigned char **row);
unsigned long stmt_id; /* Id for prepared statement */
unsigned int last_errno; /* error code */
unsigned int param_count; /* inpute parameters count */
unsigned int field_count; /* number of columns in result set */
enum enum_mysql_stmt_state state; /* statement state */
char last_error[MYSQL_ERRMSG_SIZE]; /* error message */
char sqlstate[SQLSTATE_LENGTH+1];
/* Types of input parameters should be sent to server */
my_bool send_types_to_server;
my_bool bind_param_done; /* input buffers were supplied */
my_bool bind_result_done; /* output buffers were supplied */
/* mysql_stmt_close() had to cancel this result */
my_bool unbuffered_fetch_cancelled;
/*
Is set to true if we need to calculate field->max_length for
metadata fields when doing mysql_stmt_store_result.
*/
my_bool update_max_length;
} MYSQL_STMT;
enum enum_stmt_attr_type
{
/*
When doing mysql_stmt_store_result calculate max_length attribute
of statement metadata. This is to be consistent with the old API,
where this was done automatically.
In the new API we do that only by request because it slows down
mysql_stmt_store_result sufficiently.
*/
STMT_ATTR_UPDATE_MAX_LENGTH
};
typedef struct st_mysql_methods
{
my_bool (*read_query_result)(MYSQL *mysql);
my_bool (*advanced_command)(MYSQL *mysql,
enum enum_server_command command,
const char *header,
unsigned long header_length,
const char *arg,
unsigned long arg_length,
my_bool skip_check);
MYSQL_DATA *(*read_rows)(MYSQL *mysql,MYSQL_FIELD *mysql_fields,
unsigned int fields);
MYSQL_RES * (*use_result)(MYSQL *mysql);
void (*fetch_lengths)(unsigned long *to,
MYSQL_ROW column, unsigned int field_count);
#if !defined(MYSQL_SERVER) || defined(EMBEDDED_LIBRARY)
MYSQL_FIELD * (*list_fields)(MYSQL *mysql);
my_bool (*read_prepare_result)(MYSQL *mysql, MYSQL_STMT *stmt);
int (*stmt_execute)(MYSQL_STMT *stmt);
int (*read_binary_rows)(MYSQL_STMT *stmt);
int (*unbuffered_fetch)(MYSQL *mysql, char **row);
void (*free_embedded_thd)(MYSQL *mysql);
const char *(*read_statistics)(MYSQL *mysql);
my_bool (*next_result)(MYSQL *mysql);
int (*read_change_user_result)(MYSQL *mysql, char *buff, const char *passwd);
#endif
} MYSQL_METHODS;
#ifdef HAVE_DEPRECATED_411_API
/* Deprecated calls (since MySQL 4.1.2) */
/* Use mysql_stmt_init + mysql_stmt_prepare instead */
MYSQL_STMT * STDCALL mysql_prepare(MYSQL * mysql, const char *query,
unsigned long length);
#define mysql_execute mysql_stmt_execute
#define mysql_fetch mysql_stmt_fetch
#define mysql_fetch_column mysql_stmt_fetch_column
#define mysql_bind_param mysql_stmt_bind_param
#define mysql_bind_result mysql_stmt_bind_result
#define mysql_param_count mysql_stmt_param_count
#define mysql_param_result mysql_stmt_param_metadata
#define mysql_get_metadata mysql_stmt_result_metadata
#define mysql_send_long_data mysql_stmt_send_long_data
#endif /* HAVE_DEPRECATED_411_API */
MYSQL_STMT * STDCALL mysql_stmt_init(MYSQL *mysql);
int STDCALL mysql_stmt_prepare(MYSQL_STMT *stmt, const char *query,
unsigned long length);
int STDCALL mysql_stmt_execute(MYSQL_STMT *stmt);
int STDCALL mysql_stmt_fetch(MYSQL_STMT *stmt);
int STDCALL mysql_stmt_fetch_column(MYSQL_STMT *stmt, MYSQL_BIND *bind,
unsigned int column,
unsigned long offset);
int STDCALL mysql_stmt_store_result(MYSQL_STMT *stmt);
unsigned long STDCALL mysql_stmt_param_count(MYSQL_STMT * stmt);
my_bool STDCALL mysql_stmt_attr_set(MYSQL_STMT *stmt,
enum enum_stmt_attr_type attr_type,
const void *attr);
my_bool STDCALL mysql_stmt_attr_get(MYSQL_STMT *stmt,
enum enum_stmt_attr_type attr_type,
void *attr);
my_bool STDCALL mysql_stmt_bind_param(MYSQL_STMT * stmt, MYSQL_BIND * bnd);
my_bool STDCALL mysql_stmt_bind_result(MYSQL_STMT * stmt, MYSQL_BIND * bnd);
my_bool STDCALL mysql_stmt_close(MYSQL_STMT * stmt);
my_bool STDCALL mysql_stmt_reset(MYSQL_STMT * stmt);
my_bool STDCALL mysql_stmt_free_result(MYSQL_STMT *stmt);
my_bool STDCALL mysql_stmt_send_long_data(MYSQL_STMT *stmt,
unsigned int param_number,
const char *data,
unsigned long length);
MYSQL_RES *STDCALL mysql_stmt_result_metadata(MYSQL_STMT *stmt);
MYSQL_RES *STDCALL mysql_stmt_param_metadata(MYSQL_STMT *stmt);
unsigned int STDCALL mysql_stmt_errno(MYSQL_STMT * stmt);
const char *STDCALL mysql_stmt_error(MYSQL_STMT * stmt);
const char *STDCALL mysql_stmt_sqlstate(MYSQL_STMT * stmt);
MYSQL_ROW_OFFSET STDCALL mysql_stmt_row_seek(MYSQL_STMT *stmt,
MYSQL_ROW_OFFSET offset);
MYSQL_ROW_OFFSET STDCALL mysql_stmt_row_tell(MYSQL_STMT *stmt);
void STDCALL mysql_stmt_data_seek(MYSQL_STMT *stmt, my_ulonglong offset);
my_ulonglong STDCALL mysql_stmt_num_rows(MYSQL_STMT *stmt);
my_ulonglong STDCALL mysql_stmt_affected_rows(MYSQL_STMT *stmt);
my_ulonglong STDCALL mysql_stmt_insert_id(MYSQL_STMT *stmt);
unsigned int STDCALL mysql_stmt_field_count(MYSQL_STMT *stmt);
my_bool STDCALL mysql_commit(MYSQL * mysql);
my_bool STDCALL mysql_rollback(MYSQL * mysql);
my_bool STDCALL mysql_autocommit(MYSQL * mysql, my_bool auto_mode);
my_bool STDCALL mysql_more_results(MYSQL *mysql);
int STDCALL mysql_next_result(MYSQL *mysql);
void STDCALL mysql_close(MYSQL *sock);
/* status return codes */
#define MYSQL_NO_DATA 100
#define mysql_reload(mysql) mysql_refresh((mysql),REFRESH_GRANT)
#ifdef USE_OLD_FUNCTIONS
MYSQL * STDCALL mysql_connect(MYSQL *mysql, const char *host,
const char *user, const char *passwd);
int STDCALL mysql_create_db(MYSQL *mysql, const char *DB);
int STDCALL mysql_drop_db(MYSQL *mysql, const char *DB);
#define mysql_reload(mysql) mysql_refresh((mysql),REFRESH_GRANT)
#endif
#define HAVE_MYSQL_REAL_CONNECT
/*
The following functions are mainly exported because of mysqlbinlog;
They are not for general usage
*/
#define simple_command(mysql, command, arg, length, skip_check) \
(*(mysql)->methods->advanced_command)(mysql, command, \
NullS, 0, arg, length, skip_check)
unsigned long net_safe_read(MYSQL* mysql);
#ifdef __NETWARE__
#pragma pack(pop) /* restore alignment */
#endif
#ifdef __cplusplus
}
#endif
#endif /* _mysql_h */
+387
View File
@@ -0,0 +1,387 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/*
** Common definition between mysql server & client
*/
#ifndef _mysql_com_h
#define _mysql_com_h
#define NAME_LEN 64 /* Field/table name length */
#define HOSTNAME_LENGTH 60
#define USERNAME_LENGTH 16
#define SERVER_VERSION_LENGTH 60
#define SQLSTATE_LENGTH 5
#define LOCAL_HOST "localhost"
#define LOCAL_HOST_NAMEDPIPE "."
#if defined(__WIN__) && !defined( _CUSTOMCONFIG_)
#define MYSQL_NAMEDPIPE "MySQL"
#define MYSQL_SERVICENAME "MySQL"
#endif /* __WIN__ */
enum enum_server_command
{
COM_SLEEP, COM_QUIT, COM_INIT_DB, COM_QUERY, COM_FIELD_LIST,
COM_CREATE_DB, COM_DROP_DB, COM_REFRESH, COM_SHUTDOWN, COM_STATISTICS,
COM_PROCESS_INFO, COM_CONNECT, COM_PROCESS_KILL, COM_DEBUG, COM_PING,
COM_TIME, COM_DELAYED_INSERT, COM_CHANGE_USER, COM_BINLOG_DUMP,
COM_TABLE_DUMP, COM_CONNECT_OUT, COM_REGISTER_SLAVE,
COM_PREPARE, COM_EXECUTE, COM_LONG_DATA, COM_CLOSE_STMT,
COM_RESET_STMT, COM_SET_OPTION,
COM_END /* Must be last */
};
/*
Length of random string sent by server on handshake; this is also length of
obfuscated password, recieved from client
*/
#define SCRAMBLE_LENGTH 20
#define SCRAMBLE_LENGTH_323 8
/* length of password stored in the db: new passwords are preceeded with '*' */
#define SCRAMBLED_PASSWORD_CHAR_LENGTH (SCRAMBLE_LENGTH*2+1)
#define SCRAMBLED_PASSWORD_CHAR_LENGTH_323 (SCRAMBLE_LENGTH_323*2)
#define NOT_NULL_FLAG 1 /* Field can't be NULL */
#define PRI_KEY_FLAG 2 /* Field is part of a primary key */
#define UNIQUE_KEY_FLAG 4 /* Field is part of a unique key */
#define MULTIPLE_KEY_FLAG 8 /* Field is part of a key */
#define BLOB_FLAG 16 /* Field is a blob */
#define UNSIGNED_FLAG 32 /* Field is unsigned */
#define ZEROFILL_FLAG 64 /* Field is zerofill */
#define BINARY_FLAG 128 /* Field is binary */
/* The following are only sent to new clients */
#define ENUM_FLAG 256 /* field is an enum */
#define AUTO_INCREMENT_FLAG 512 /* field is a autoincrement field */
#define TIMESTAMP_FLAG 1024 /* Field is a timestamp */
#define SET_FLAG 2048 /* field is a set */
#define NUM_FLAG 32768 /* Field is num (for clients) */
#define PART_KEY_FLAG 16384 /* Intern; Part of some key */
#define GROUP_FLAG 32768 /* Intern: Group field */
#define UNIQUE_FLAG 65536 /* Intern: Used by sql_yacc */
#define BINCMP_FLAG 131072 /* Intern: Used by sql_yacc */
#define REFRESH_GRANT 1 /* Refresh grant tables */
#define REFRESH_LOG 2 /* Start on new log file */
#define REFRESH_TABLES 4 /* close all tables */
#define REFRESH_HOSTS 8 /* Flush host cache */
#define REFRESH_STATUS 16 /* Flush status variables */
#define REFRESH_THREADS 32 /* Flush thread cache */
#define REFRESH_SLAVE 64 /* Reset master info and restart slave
thread */
#define REFRESH_MASTER 128 /* Remove all bin logs in the index
and truncate the index */
/* The following can't be set with mysql_refresh() */
#define REFRESH_READ_LOCK 16384 /* Lock tables for read */
#define REFRESH_FAST 32768 /* Intern flag */
/* RESET (remove all queries) from query cache */
#define REFRESH_QUERY_CACHE 65536
#define REFRESH_QUERY_CACHE_FREE 0x20000L /* pack query cache */
#define REFRESH_DES_KEY_FILE 0x40000L
#define REFRESH_USER_RESOURCES 0x80000L
#define CLIENT_LONG_PASSWORD 1 /* new more secure passwords */
#define CLIENT_FOUND_ROWS 2 /* Found instead of affected rows */
#define CLIENT_LONG_FLAG 4 /* Get all column flags */
#define CLIENT_CONNECT_WITH_DB 8 /* One can specify db on connect */
#define CLIENT_NO_SCHEMA 16 /* Don't allow database.table.column */
#define CLIENT_COMPRESS 32 /* Can use compression protocol */
#define CLIENT_ODBC 64 /* Odbc client */
#define CLIENT_LOCAL_FILES 128 /* Can use LOAD DATA LOCAL */
#define CLIENT_IGNORE_SPACE 256 /* Ignore spaces before '(' */
#define CLIENT_PROTOCOL_41 512 /* New 4.1 protocol */
#define CLIENT_INTERACTIVE 1024 /* This is an interactive client */
#define CLIENT_SSL 2048 /* Switch to SSL after handshake */
#define CLIENT_IGNORE_SIGPIPE 4096 /* IGNORE sigpipes */
#define CLIENT_TRANSACTIONS 8192 /* Client knows about transactions */
#define CLIENT_RESERVED 16384 /* Old flag for 4.1 protocol */
#define CLIENT_SECURE_CONNECTION 32768 /* New 4.1 authentication */
#define CLIENT_MULTI_STATEMENTS 65536 /* Enable/disable multi-stmt support */
#define CLIENT_MULTI_RESULTS 131072 /* Enable/disable multi-results */
#define CLIENT_REMEMBER_OPTIONS (((ulong) 1) << 31)
#define SERVER_STATUS_IN_TRANS 1 /* Transaction has started */
#define SERVER_STATUS_AUTOCOMMIT 2 /* Server in auto_commit mode */
#define SERVER_STATUS_MORE_RESULTS 4 /* More results on server */
#define SERVER_MORE_RESULTS_EXISTS 8 /* Multi query - next query exists */
#define SERVER_QUERY_NO_GOOD_INDEX_USED 16
#define SERVER_QUERY_NO_INDEX_USED 32
#define MYSQL_ERRMSG_SIZE 512
#define NET_READ_TIMEOUT 30 /* Timeout on read */
#define NET_WRITE_TIMEOUT 60 /* Timeout on write */
#define NET_WAIT_TIMEOUT 8*60*60 /* Wait for new query */
struct st_vio; /* Only C */
typedef struct st_vio Vio;
#define MAX_CHAR_WIDTH 255 /* Max length for a CHAR colum */
#define MAX_BLOB_WIDTH 8192 /* Default width for blob */
typedef struct st_net {
#if !defined(CHECK_EMBEDDED_DIFFERENCES) || !defined(EMBEDDED_LIBRARY)
Vio* vio;
unsigned char *buff,*buff_end,*write_pos,*read_pos;
my_socket fd; /* For Perl DBI/dbd */
unsigned long max_packet,max_packet_size;
unsigned int pkt_nr,compress_pkt_nr;
unsigned int write_timeout, read_timeout, retry_count;
int fcntl;
my_bool compress;
/*
The following variable is set if we are doing several queries in one
command ( as in LOAD TABLE ... FROM MASTER ),
and do not want to confuse the client with OK at the wrong time
*/
unsigned long remain_in_buf,length, buf_length, where_b;
unsigned int *return_status;
unsigned char reading_or_writing;
char save_char;
my_bool no_send_ok;
/*
Pointer to query object in query cache, do not equal NULL (0) for
queries in cache that have not stored its results yet
*/
#endif
char last_error[MYSQL_ERRMSG_SIZE], sqlstate[SQLSTATE_LENGTH+1];
unsigned int last_errno;
unsigned char error;
gptr query_cache_query;
my_bool report_error; /* We should report error (we have unreported error) */
my_bool return_errno;
} NET;
#define packet_error (~(unsigned long) 0)
enum enum_field_types { MYSQL_TYPE_DECIMAL, MYSQL_TYPE_TINY,
MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG,
MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE,
MYSQL_TYPE_NULL, MYSQL_TYPE_TIMESTAMP,
MYSQL_TYPE_LONGLONG,MYSQL_TYPE_INT24,
MYSQL_TYPE_DATE, MYSQL_TYPE_TIME,
MYSQL_TYPE_DATETIME, MYSQL_TYPE_YEAR,
MYSQL_TYPE_NEWDATE,
MYSQL_TYPE_ENUM=247,
MYSQL_TYPE_SET=248,
MYSQL_TYPE_TINY_BLOB=249,
MYSQL_TYPE_MEDIUM_BLOB=250,
MYSQL_TYPE_LONG_BLOB=251,
MYSQL_TYPE_BLOB=252,
MYSQL_TYPE_VAR_STRING=253,
MYSQL_TYPE_STRING=254,
MYSQL_TYPE_GEOMETRY=255
};
/* For backward compatibility */
#define CLIENT_MULTI_QUERIES CLIENT_MULTI_STATEMENTS
#define FIELD_TYPE_DECIMAL MYSQL_TYPE_DECIMAL
#define FIELD_TYPE_TINY MYSQL_TYPE_TINY
#define FIELD_TYPE_SHORT MYSQL_TYPE_SHORT
#define FIELD_TYPE_LONG MYSQL_TYPE_LONG
#define FIELD_TYPE_FLOAT MYSQL_TYPE_FLOAT
#define FIELD_TYPE_DOUBLE MYSQL_TYPE_DOUBLE
#define FIELD_TYPE_NULL MYSQL_TYPE_NULL
#define FIELD_TYPE_TIMESTAMP MYSQL_TYPE_TIMESTAMP
#define FIELD_TYPE_LONGLONG MYSQL_TYPE_LONGLONG
#define FIELD_TYPE_INT24 MYSQL_TYPE_INT24
#define FIELD_TYPE_DATE MYSQL_TYPE_DATE
#define FIELD_TYPE_TIME MYSQL_TYPE_TIME
#define FIELD_TYPE_DATETIME MYSQL_TYPE_DATETIME
#define FIELD_TYPE_YEAR MYSQL_TYPE_YEAR
#define FIELD_TYPE_NEWDATE MYSQL_TYPE_NEWDATE
#define FIELD_TYPE_ENUM MYSQL_TYPE_ENUM
#define FIELD_TYPE_SET MYSQL_TYPE_SET
#define FIELD_TYPE_TINY_BLOB MYSQL_TYPE_TINY_BLOB
#define FIELD_TYPE_MEDIUM_BLOB MYSQL_TYPE_MEDIUM_BLOB
#define FIELD_TYPE_LONG_BLOB MYSQL_TYPE_LONG_BLOB
#define FIELD_TYPE_BLOB MYSQL_TYPE_BLOB
#define FIELD_TYPE_VAR_STRING MYSQL_TYPE_VAR_STRING
#define FIELD_TYPE_STRING MYSQL_TYPE_STRING
#define FIELD_TYPE_CHAR MYSQL_TYPE_TINY
#define FIELD_TYPE_INTERVAL MYSQL_TYPE_ENUM
#define FIELD_TYPE_GEOMETRY MYSQL_TYPE_GEOMETRY
enum enum_shutdown_level {
/*
We want levels to be in growing order of hardness. So we leave room
for future intermediate levels. For now, escalating one level is += 10;
later if we insert new levels in between we will need a function
next_shutdown_level(level). Note that DEFAULT does not respect the
growing property.
*/
SHUTDOWN_DEFAULT= 0, /* mapped to WAIT_ALL_BUFFERS for now */
/*
Here is the list in growing order (the next does the previous plus
something). WAIT_ALL_BUFFERS is what we have now. Others are "this MySQL
server does not support this shutdown level yet".
*/
SHUTDOWN_WAIT_CONNECTIONS= 10, /* wait for existing connections to finish */
SHUTDOWN_WAIT_TRANSACTIONS= 20, /* wait for existing trans to finish */
SHUTDOWN_WAIT_STATEMENTS= 30, /* wait for existing updating stmts to finish */
SHUTDOWN_WAIT_ALL_BUFFERS= 40, /* flush InnoDB buffers */
SHUTDOWN_WAIT_CRITICAL_BUFFERS= 50, /* flush MyISAM buffs (no corruption) */
/* Now the 2 levels of the KILL command */
#if MYSQL_VERSION_ID >= 50000
KILL_QUERY= 254,
#endif
KILL_CONNECTION= 255
};
/* options for mysql_set_option */
enum enum_mysql_set_option
{
MYSQL_OPTION_MULTI_STATEMENTS_ON,
MYSQL_OPTION_MULTI_STATEMENTS_OFF
};
#define net_new_transaction(net) ((net)->pkt_nr=0)
#ifdef __cplusplus
extern "C" {
#endif
my_bool my_net_init(NET *net, Vio* vio);
void my_net_local_init(NET *net);
void net_end(NET *net);
void net_clear(NET *net);
my_bool net_realloc(NET *net, unsigned long length);
#ifndef EMBEDDED_LIBRARY /* To be removed by HF */
my_bool net_flush(NET *net);
#else
#define net_flush(A)
#endif
my_bool my_net_write(NET *net,const char *packet,unsigned long len);
my_bool net_write_command(NET *net,unsigned char command,
const char *header, unsigned long head_len,
const char *packet, unsigned long len);
int net_real_write(NET *net,const char *packet,unsigned long len);
unsigned long my_net_read(NET *net);
/*
The following function is not meant for normal usage
Currently it's used internally by manager.c
*/
struct sockaddr;
int my_connect(my_socket s, const struct sockaddr *name, unsigned int namelen,
unsigned int timeout);
struct rand_struct {
unsigned long seed1,seed2,max_value;
double max_value_dbl;
};
#ifdef __cplusplus
}
#endif
/* The following is for user defined functions */
enum Item_result {STRING_RESULT, REAL_RESULT, INT_RESULT, ROW_RESULT};
typedef struct st_udf_args
{
unsigned int arg_count; /* Number of arguments */
enum Item_result *arg_type; /* Pointer to item_results */
char **args; /* Pointer to argument */
unsigned long *lengths; /* Length of string arguments */
char *maybe_null; /* Set to 1 for all maybe_null args */
} UDF_ARGS;
/* This holds information about the result */
typedef struct st_udf_init
{
my_bool maybe_null; /* 1 if function can return NULL */
unsigned int decimals; /* for real functions */
unsigned long max_length; /* For string functions */
char *ptr; /* free pointer for function data */
my_bool const_item; /* 0 if result is independent of arguments */
} UDF_INIT;
/* Constants when using compression */
#define NET_HEADER_SIZE 4 /* standard header size */
#define COMP_HEADER_SIZE 3 /* compression header extra size */
/* Prototypes to password functions */
#ifdef __cplusplus
extern "C" {
#endif
/*
These functions are used for authentication by client and server and
implemented in sql/password.c
*/
void randominit(struct rand_struct *, unsigned long seed1,
unsigned long seed2);
double my_rnd(struct rand_struct *);
void create_random_string(char *to, unsigned int length, struct rand_struct *rand_st);
void hash_password(unsigned long *to, const char *password, unsigned int password_len);
void make_scrambled_password_323(char *to, const char *password);
void scramble_323(char *to, const char *message, const char *password);
my_bool check_scramble_323(const char *, const char *message,
unsigned long *salt);
void get_salt_from_password_323(unsigned long *res, const char *password);
void make_password_from_salt_323(char *to, const unsigned long *salt);
void make_scrambled_password(char *to, const char *password);
void scramble(char *to, const char *message, const char *password);
my_bool check_scramble(const char *reply, const char *message,
const unsigned char *hash_stage2);
void get_salt_from_password(unsigned char *res, const char *password);
void make_password_from_salt(char *to, const unsigned char *hash_stage2);
/* end of password.c */
char *get_tty_password(char *opt_message);
const char *mysql_errno_to_sqlstate(unsigned int mysql_errno);
/* Some other useful functions */
my_bool my_init(void);
int load_defaults(const char *conf_file, const char **groups,
int *argc, char ***argv);
my_bool my_thread_init(void);
void my_thread_end(void);
#ifdef _global_h
ulong STDCALL net_field_length(uchar **packet);
my_ulonglong net_field_length_ll(uchar **packet);
char *net_store_length(char *pkg, ulonglong length);
#endif
#ifdef __cplusplus
}
#endif
#define NULL_LENGTH ((unsigned long) ~0) /* For net_store_length */
#define MYSQL_STMT_HEADER 4
#define MYSQL_LONG_DATA_HEADER 6
#endif
+33
View File
@@ -0,0 +1,33 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/* Defines that are unique to the embedded version of MySQL */
#ifdef EMBEDDED_LIBRARY
/* Things we don't need in the embedded version of MySQL */
/* TODO HF add #undef HAVE_VIO if we don't want client in embedded library */
#undef HAVE_PSTACK /* No stacktrace */
#undef HAVE_DLOPEN /* No udf functions */
#undef HAVE_OPENSSL
#undef HAVE_ISAM
#undef HAVE_SMEM /* No shared memory */
#undef HAVE_NDBCLUSTER_DB /* No NDB cluster */
#define DONT_USE_RAID
#endif /* EMBEDDED_LIBRARY */
+37
View File
@@ -0,0 +1,37 @@
/* Copyright (C) 2004 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef _mysql_time_h_
#define _mysql_time_h_
/* Time declarations shared between server and client library */
enum enum_mysql_timestamp_type
{
MYSQL_TIMESTAMP_NONE= -2, MYSQL_TIMESTAMP_ERROR= -1,
MYSQL_TIMESTAMP_DATE= 0, MYSQL_TIMESTAMP_DATETIME= 1, MYSQL_TIMESTAMP_TIME= 2
};
typedef struct st_mysql_time
{
unsigned int year, month, day, hour, minute, second;
unsigned long second_part;
my_bool neg;
enum enum_mysql_timestamp_type time_type;
} MYSQL_TIME;
#endif /* _mysql_time_h_ */
+29
View File
@@ -0,0 +1,29 @@
/* Copyright Abandoned 1996, 1999, 2001 MySQL AB
This file is public domain and comes with NO WARRANTY of any kind */
/* Version numbers for protocol & mysqld */
#ifndef _mysql_version_h
#define _mysql_version_h
#ifdef _CUSTOMCONFIG_
#include <custom_conf.h>
#else
#define PROTOCOL_VERSION 10
#define MYSQL_SERVER_VERSION "4.1.3-beta"
#define MYSQL_BASE_VERSION "mysqld-4.1"
#define MYSQL_SERVER_SUFFIX_DEF ""
#define FRM_VER 6
#define MYSQL_VERSION_ID 40103
#define MYSQL_PORT 3306
#define MYSQL_UNIX_ADDR "/tmp/mysql.sock"
#define MYSQL_CONFIG_NAME "my"
#define MYSQL_COMPILATION_COMMENT "FreeBSD port: mysql-client-4.1.3"
/* mysqld compile time options */
#endif /* _CUSTOMCONFIG_ */
#ifndef LICENSE
#define LICENSE GPL
#endif /* LICENSE */
#endif /* _mysql_version_h */
+319
View File
@@ -0,0 +1,319 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/* Definefile for error messagenumbers */
#define ER_HASHCHK 1000
#define ER_NISAMCHK 1001
#define ER_NO 1002
#define ER_YES 1003
#define ER_CANT_CREATE_FILE 1004
#define ER_CANT_CREATE_TABLE 1005
#define ER_CANT_CREATE_DB 1006
#define ER_DB_CREATE_EXISTS 1007
#define ER_DB_DROP_EXISTS 1008
#define ER_DB_DROP_DELETE 1009
#define ER_DB_DROP_RMDIR 1010
#define ER_CANT_DELETE_FILE 1011
#define ER_CANT_FIND_SYSTEM_REC 1012
#define ER_CANT_GET_STAT 1013
#define ER_CANT_GET_WD 1014
#define ER_CANT_LOCK 1015
#define ER_CANT_OPEN_FILE 1016
#define ER_FILE_NOT_FOUND 1017
#define ER_CANT_READ_DIR 1018
#define ER_CANT_SET_WD 1019
#define ER_CHECKREAD 1020
#define ER_DISK_FULL 1021
#define ER_DUP_KEY 1022
#define ER_ERROR_ON_CLOSE 1023
#define ER_ERROR_ON_READ 1024
#define ER_ERROR_ON_RENAME 1025
#define ER_ERROR_ON_WRITE 1026
#define ER_FILE_USED 1027
#define ER_FILSORT_ABORT 1028
#define ER_FORM_NOT_FOUND 1029
#define ER_GET_ERRNO 1030
#define ER_ILLEGAL_HA 1031
#define ER_KEY_NOT_FOUND 1032
#define ER_NOT_FORM_FILE 1033
#define ER_NOT_KEYFILE 1034
#define ER_OLD_KEYFILE 1035
#define ER_OPEN_AS_READONLY 1036
#define ER_OUTOFMEMORY 1037
#define ER_OUT_OF_SORTMEMORY 1038
#define ER_UNEXPECTED_EOF 1039
#define ER_CON_COUNT_ERROR 1040
#define ER_OUT_OF_RESOURCES 1041
#define ER_BAD_HOST_ERROR 1042
#define ER_HANDSHAKE_ERROR 1043
#define ER_DBACCESS_DENIED_ERROR 1044
#define ER_ACCESS_DENIED_ERROR 1045
#define ER_NO_DB_ERROR 1046
#define ER_UNKNOWN_COM_ERROR 1047
#define ER_BAD_NULL_ERROR 1048
#define ER_BAD_DB_ERROR 1049
#define ER_TABLE_EXISTS_ERROR 1050
#define ER_BAD_TABLE_ERROR 1051
#define ER_NON_UNIQ_ERROR 1052
#define ER_SERVER_SHUTDOWN 1053
#define ER_BAD_FIELD_ERROR 1054
#define ER_WRONG_FIELD_WITH_GROUP 1055
#define ER_WRONG_GROUP_FIELD 1056
#define ER_WRONG_SUM_SELECT 1057
#define ER_WRONG_VALUE_COUNT 1058
#define ER_TOO_LONG_IDENT 1059
#define ER_DUP_FIELDNAME 1060
#define ER_DUP_KEYNAME 1061
#define ER_DUP_ENTRY 1062
#define ER_WRONG_FIELD_SPEC 1063
#define ER_PARSE_ERROR 1064
#define ER_EMPTY_QUERY 1065
#define ER_NONUNIQ_TABLE 1066
#define ER_INVALID_DEFAULT 1067
#define ER_MULTIPLE_PRI_KEY 1068
#define ER_TOO_MANY_KEYS 1069
#define ER_TOO_MANY_KEY_PARTS 1070
#define ER_TOO_LONG_KEY 1071
#define ER_KEY_COLUMN_DOES_NOT_EXITS 1072
#define ER_BLOB_USED_AS_KEY 1073
#define ER_TOO_BIG_FIELDLENGTH 1074
#define ER_WRONG_AUTO_KEY 1075
#define ER_READY 1076
#define ER_NORMAL_SHUTDOWN 1077
#define ER_GOT_SIGNAL 1078
#define ER_SHUTDOWN_COMPLETE 1079
#define ER_FORCING_CLOSE 1080
#define ER_IPSOCK_ERROR 1081
#define ER_NO_SUCH_INDEX 1082
#define ER_WRONG_FIELD_TERMINATORS 1083
#define ER_BLOBS_AND_NO_TERMINATED 1084
#define ER_TEXTFILE_NOT_READABLE 1085
#define ER_FILE_EXISTS_ERROR 1086
#define ER_LOAD_INFO 1087
#define ER_ALTER_INFO 1088
#define ER_WRONG_SUB_KEY 1089
#define ER_CANT_REMOVE_ALL_FIELDS 1090
#define ER_CANT_DROP_FIELD_OR_KEY 1091
#define ER_INSERT_INFO 1092
#define ER_UPDATE_TABLE_USED 1093
#define ER_NO_SUCH_THREAD 1094
#define ER_KILL_DENIED_ERROR 1095
#define ER_NO_TABLES_USED 1096
#define ER_TOO_BIG_SET 1097
#define ER_NO_UNIQUE_LOGFILE 1098
#define ER_TABLE_NOT_LOCKED_FOR_WRITE 1099
#define ER_TABLE_NOT_LOCKED 1100
#define ER_BLOB_CANT_HAVE_DEFAULT 1101
#define ER_WRONG_DB_NAME 1102
#define ER_WRONG_TABLE_NAME 1103
#define ER_TOO_BIG_SELECT 1104
#define ER_UNKNOWN_ERROR 1105
#define ER_UNKNOWN_PROCEDURE 1106
#define ER_WRONG_PARAMCOUNT_TO_PROCEDURE 1107
#define ER_WRONG_PARAMETERS_TO_PROCEDURE 1108
#define ER_UNKNOWN_TABLE 1109
#define ER_FIELD_SPECIFIED_TWICE 1110
#define ER_INVALID_GROUP_FUNC_USE 1111
#define ER_UNSUPPORTED_EXTENSION 1112
#define ER_TABLE_MUST_HAVE_COLUMNS 1113
#define ER_RECORD_FILE_FULL 1114
#define ER_UNKNOWN_CHARACTER_SET 1115
#define ER_TOO_MANY_TABLES 1116
#define ER_TOO_MANY_FIELDS 1117
#define ER_TOO_BIG_ROWSIZE 1118
#define ER_STACK_OVERRUN 1119
#define ER_WRONG_OUTER_JOIN 1120
#define ER_NULL_COLUMN_IN_INDEX 1121
#define ER_CANT_FIND_UDF 1122
#define ER_CANT_INITIALIZE_UDF 1123
#define ER_UDF_NO_PATHS 1124
#define ER_UDF_EXISTS 1125
#define ER_CANT_OPEN_LIBRARY 1126
#define ER_CANT_FIND_DL_ENTRY 1127
#define ER_FUNCTION_NOT_DEFINED 1128
#define ER_HOST_IS_BLOCKED 1129
#define ER_HOST_NOT_PRIVILEGED 1130
#define ER_PASSWORD_ANONYMOUS_USER 1131
#define ER_PASSWORD_NOT_ALLOWED 1132
#define ER_PASSWORD_NO_MATCH 1133
#define ER_UPDATE_INFO 1134
#define ER_CANT_CREATE_THREAD 1135
#define ER_WRONG_VALUE_COUNT_ON_ROW 1136
#define ER_CANT_REOPEN_TABLE 1137
#define ER_INVALID_USE_OF_NULL 1138
#define ER_REGEXP_ERROR 1139
#define ER_MIX_OF_GROUP_FUNC_AND_FIELDS 1140
#define ER_NONEXISTING_GRANT 1141
#define ER_TABLEACCESS_DENIED_ERROR 1142
#define ER_COLUMNACCESS_DENIED_ERROR 1143
#define ER_ILLEGAL_GRANT_FOR_TABLE 1144
#define ER_GRANT_WRONG_HOST_OR_USER 1145
#define ER_NO_SUCH_TABLE 1146
#define ER_NONEXISTING_TABLE_GRANT 1147
#define ER_NOT_ALLOWED_COMMAND 1148
#define ER_SYNTAX_ERROR 1149
#define ER_DELAYED_CANT_CHANGE_LOCK 1150
#define ER_TOO_MANY_DELAYED_THREADS 1151
#define ER_ABORTING_CONNECTION 1152
#define ER_NET_PACKET_TOO_LARGE 1153
#define ER_NET_READ_ERROR_FROM_PIPE 1154
#define ER_NET_FCNTL_ERROR 1155
#define ER_NET_PACKETS_OUT_OF_ORDER 1156
#define ER_NET_UNCOMPRESS_ERROR 1157
#define ER_NET_READ_ERROR 1158
#define ER_NET_READ_INTERRUPTED 1159
#define ER_NET_ERROR_ON_WRITE 1160
#define ER_NET_WRITE_INTERRUPTED 1161
#define ER_TOO_LONG_STRING 1162
#define ER_TABLE_CANT_HANDLE_BLOB 1163
#define ER_TABLE_CANT_HANDLE_AUTO_INCREMENT 1164
#define ER_DELAYED_INSERT_TABLE_LOCKED 1165
#define ER_WRONG_COLUMN_NAME 1166
#define ER_WRONG_KEY_COLUMN 1167
#define ER_WRONG_MRG_TABLE 1168
#define ER_DUP_UNIQUE 1169
#define ER_BLOB_KEY_WITHOUT_LENGTH 1170
#define ER_PRIMARY_CANT_HAVE_NULL 1171
#define ER_TOO_MANY_ROWS 1172
#define ER_REQUIRES_PRIMARY_KEY 1173
#define ER_NO_RAID_COMPILED 1174
#define ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE 1175
#define ER_KEY_DOES_NOT_EXITS 1176
#define ER_CHECK_NO_SUCH_TABLE 1177
#define ER_CHECK_NOT_IMPLEMENTED 1178
#define ER_CANT_DO_THIS_DURING_AN_TRANSACTION 1179
#define ER_ERROR_DURING_COMMIT 1180
#define ER_ERROR_DURING_ROLLBACK 1181
#define ER_ERROR_DURING_FLUSH_LOGS 1182
#define ER_ERROR_DURING_CHECKPOINT 1183
#define ER_NEW_ABORTING_CONNECTION 1184
#define ER_DUMP_NOT_IMPLEMENTED 1185
#define ER_FLUSH_MASTER_BINLOG_CLOSED 1186
#define ER_INDEX_REBUILD 1187
#define ER_MASTER 1188
#define ER_MASTER_NET_READ 1189
#define ER_MASTER_NET_WRITE 1190
#define ER_FT_MATCHING_KEY_NOT_FOUND 1191
#define ER_LOCK_OR_ACTIVE_TRANSACTION 1192
#define ER_UNKNOWN_SYSTEM_VARIABLE 1193
#define ER_CRASHED_ON_USAGE 1194
#define ER_CRASHED_ON_REPAIR 1195
#define ER_WARNING_NOT_COMPLETE_ROLLBACK 1196
#define ER_TRANS_CACHE_FULL 1197
#define ER_SLAVE_MUST_STOP 1198
#define ER_SLAVE_NOT_RUNNING 1199
#define ER_BAD_SLAVE 1200
#define ER_MASTER_INFO 1201
#define ER_SLAVE_THREAD 1202
#define ER_TOO_MANY_USER_CONNECTIONS 1203
#define ER_SET_CONSTANTS_ONLY 1204
#define ER_LOCK_WAIT_TIMEOUT 1205
#define ER_LOCK_TABLE_FULL 1206
#define ER_READ_ONLY_TRANSACTION 1207
#define ER_DROP_DB_WITH_READ_LOCK 1208
#define ER_CREATE_DB_WITH_READ_LOCK 1209
#define ER_WRONG_ARGUMENTS 1210
#define ER_NO_PERMISSION_TO_CREATE_USER 1211
#define ER_UNION_TABLES_IN_DIFFERENT_DIR 1212
#define ER_LOCK_DEADLOCK 1213
#define ER_TABLE_CANT_HANDLE_FT 1214
#define ER_CANNOT_ADD_FOREIGN 1215
#define ER_NO_REFERENCED_ROW 1216
#define ER_ROW_IS_REFERENCED 1217
#define ER_CONNECT_TO_MASTER 1218
#define ER_QUERY_ON_MASTER 1219
#define ER_ERROR_WHEN_EXECUTING_COMMAND 1220
#define ER_WRONG_USAGE 1221
#define ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT 1222
#define ER_CANT_UPDATE_WITH_READLOCK 1223
#define ER_MIXING_NOT_ALLOWED 1224
#define ER_DUP_ARGUMENT 1225
#define ER_USER_LIMIT_REACHED 1226
#define ER_SPECIFIC_ACCESS_DENIED_ERROR 1227
#define ER_LOCAL_VARIABLE 1228
#define ER_GLOBAL_VARIABLE 1229
#define ER_NO_DEFAULT 1230
#define ER_WRONG_VALUE_FOR_VAR 1231
#define ER_WRONG_TYPE_FOR_VAR 1232
#define ER_VAR_CANT_BE_READ 1233
#define ER_CANT_USE_OPTION_HERE 1234
#define ER_NOT_SUPPORTED_YET 1235
#define ER_MASTER_FATAL_ERROR_READING_BINLOG 1236
#define ER_SLAVE_IGNORED_TABLE 1237
#define ER_INCORRECT_GLOBAL_LOCAL_VAR 1238
#define ER_WRONG_FK_DEF 1239
#define ER_KEY_REF_DO_NOT_MATCH_TABLE_REF 1240
#define ER_OPERAND_COLUMNS 1241
#define ER_SUBQUERY_NO_1_ROW 1242
#define ER_UNKNOWN_STMT_HANDLER 1243
#define ER_CORRUPT_HELP_DB 1244
#define ER_CYCLIC_REFERENCE 1245
#define ER_AUTO_CONVERT 1246
#define ER_ILLEGAL_REFERENCE 1247
#define ER_DERIVED_MUST_HAVE_ALIAS 1248
#define ER_SELECT_REDUCED 1249
#define ER_TABLENAME_NOT_ALLOWED_HERE 1250
#define ER_NOT_SUPPORTED_AUTH_MODE 1251
#define ER_SPATIAL_CANT_HAVE_NULL 1252
#define ER_COLLATION_CHARSET_MISMATCH 1253
#define ER_SLAVE_WAS_RUNNING 1254
#define ER_SLAVE_WAS_NOT_RUNNING 1255
#define ER_TOO_BIG_FOR_UNCOMPRESS 1256
#define ER_ZLIB_Z_MEM_ERROR 1257
#define ER_ZLIB_Z_BUF_ERROR 1258
#define ER_ZLIB_Z_DATA_ERROR 1259
#define ER_CUT_VALUE_GROUP_CONCAT 1260
#define ER_WARN_TOO_FEW_RECORDS 1261
#define ER_WARN_TOO_MANY_RECORDS 1262
#define ER_WARN_NULL_TO_NOTNULL 1263
#define ER_WARN_DATA_OUT_OF_RANGE 1264
#define ER_WARN_DATA_TRUNCATED 1265
#define ER_WARN_USING_OTHER_HANDLER 1266
#define ER_CANT_AGGREGATE_2COLLATIONS 1267
#define ER_DROP_USER 1268
#define ER_REVOKE_GRANTS 1269
#define ER_CANT_AGGREGATE_3COLLATIONS 1270
#define ER_CANT_AGGREGATE_NCOLLATIONS 1271
#define ER_VARIABLE_IS_NOT_STRUCT 1272
#define ER_UNKNOWN_COLLATION 1273
#define ER_SLAVE_IGNORED_SSL_PARAMS 1274
#define ER_SERVER_IS_IN_SECURE_AUTH_MODE 1275
#define ER_WARN_FIELD_RESOLVED 1276
#define ER_BAD_SLAVE_UNTIL_COND 1277
#define ER_MISSING_SKIP_SLAVE 1278
#define ER_UNTIL_COND_IGNORED 1279
#define ER_WRONG_NAME_FOR_INDEX 1280
#define ER_WRONG_NAME_FOR_CATALOG 1281
#define ER_WARN_QC_RESIZE 1282
#define ER_BAD_FT_COLUMN 1283
#define ER_UNKNOWN_KEY_CACHE 1284
#define ER_WARN_HOSTNAME_WONT_WORK 1285
#define ER_UNKNOWN_STORAGE_ENGINE 1286
#define ER_WARN_DEPRECATED_SYNTAX 1287
#define ER_NON_UPDATABLE_TABLE 1288
#define ER_FEATURE_DISABLED 1289
#define ER_OPTION_PREVENTS_STATEMENT 1290
#define ER_DUPLICATED_VALUE_IN_TYPE 1291
#define ER_TRUNCATED_WRONG_VALUE 1292
#define ER_TOO_MUCH_AUTO_TIMESTAMP_COLS 1293
#define ER_INVALID_ON_UPDATE 1294
#define ER_UNSUPPORTED_PS 1295
#define ER_GET_ERRMSG 1296
#define ER_GET_TEMPORARY_ERRMSG 1297
#define ER_UNKNOWN_TIME_ZONE 1298
#define ER_WARN_INVALID_TIMESTAMP 1299
#define ER_ERROR_MESSAGES 300
+158
View File
@@ -0,0 +1,158 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/* Parser needs these defines always, even if USE_RAID is not defined */
#define RAID_TYPE_0 1 /* Striping */
#define RAID_TYPE_x 2 /* Some new modes */
#define RAID_TYPE_y 3
#define RAID_DEFAULT_CHUNKS 4
#define RAID_DEFAULT_CHUNKSIZE 256*1024 /* 256kB */
C_MODE_START
#define my_raid_type(raid_type) raid_type_string[(int)(raid_type)]
extern const char *raid_type_string[];
C_MODE_END
#ifdef DONT_USE_RAID
#undef USE_RAID
#endif
#if defined(USE_RAID)
#ifdef __GNUC__
#pragma interface /* gcc class implementation */
#endif
#include "my_dir.h"
/* Trap all occurences of my_...() in source and use our wrapper around this function */
#ifdef MAP_TO_USE_RAID
#define my_read(A,B,C,D) my_raid_read(A,B,C,D)
#define my_write(A,B,C,D) my_raid_write(A,B,C,D)
#define my_pwrite(A,B,C,D,E) my_raid_pwrite(A,B,C,D,E)
#define my_pread(A,B,C,D,E) my_raid_pread(A,B,C,D,E)
#define my_chsize(A,B,C,D) my_raid_chsize(A,B,C,D)
#define my_close(A,B) my_raid_close(A,B)
#define my_tell(A,B) my_raid_tell(A,B)
#define my_seek(A,B,C,D) my_raid_seek(A,B,C,D)
#define my_lock(A,B,C,D,E) my_raid_lock(A,B,C,D,E)
#define my_fstat(A,B,C) my_raid_fstat(A,B,C)
#endif /* MAP_TO_USE_RAID */
#ifdef __cplusplus
extern "C" {
#endif
void init_raid(void);
void end_raid(void);
bool is_raid(File fd);
File my_raid_create(const char *FileName, int CreateFlags, int access_flags,
uint raid_type, uint raid_chunks, ulong raid_chunksize,
myf MyFlags);
File my_raid_open(const char *FileName, int Flags,
uint raid_type, uint raid_chunks, ulong raid_chunksize,
myf MyFlags);
int my_raid_rename(const char *from, const char *to, uint raid_chunks,
myf MyFlags);
int my_raid_delete(const char *from, uint raid_chunks, myf MyFlags);
int my_raid_redel(const char *old_name, const char *new_name,
uint raid_chunks, myf MyFlags);
my_off_t my_raid_seek(File fd, my_off_t pos, int whence, myf MyFlags);
my_off_t my_raid_tell(File fd, myf MyFlags);
uint my_raid_write(File,const byte *Buffer, uint Count, myf MyFlags);
uint my_raid_read(File Filedes, byte *Buffer, uint Count, myf MyFlags);
uint my_raid_pread(File Filedes, byte *Buffer, uint Count, my_off_t offset,
myf MyFlags);
uint my_raid_pwrite(int Filedes, const byte *Buffer, uint Count,
my_off_t offset, myf MyFlags);
int my_raid_lock(File,int locktype, my_off_t start, my_off_t length,
myf MyFlags);
int my_raid_chsize(File fd, my_off_t newlength, int filler, myf MyFlags);
int my_raid_close(File, myf MyFlags);
int my_raid_fstat(int Filedes, struct stat *buf, myf MyFlags);
#ifdef __cplusplus
}
class RaidName {
public:
RaidName(const char *FileName);
~RaidName();
bool IsRaid();
int Rename(const char * from, const char * to, myf MyFlags);
private:
uint _raid_type; /* RAID_TYPE_0 or RAID_TYPE_1 or RAID_TYPE_5 */
uint _raid_chunks; /* 1..n */
ulong _raid_chunksize; /* 1..n in bytes */
};
class RaidFd {
public:
RaidFd(uint raid_type, uint raid_chunks , ulong raid_chunksize);
~RaidFd();
File Create(const char *FileName, int CreateFlags, int access_flags,
myf MyFlags);
File Open(const char *FileName, int Flags, myf MyFlags);
my_off_t Seek(my_off_t pos,int whence,myf MyFlags);
my_off_t Tell(myf MyFlags);
int Write(const byte *Buffer, uint Count, myf MyFlags);
int Read(const byte *Buffer, uint Count, myf MyFlags);
int Lock(int locktype, my_off_t start, my_off_t length, myf MyFlags);
int Chsize(File fd, my_off_t newlength, int filler, myf MyFlags);
int Fstat(int fd, MY_STAT *stat_area, myf MyFlags );
int Close(myf MyFlags);
static bool IsRaid(File fd);
static DYNAMIC_ARRAY _raid_map; /* Map of RaidFD* */
private:
uint _raid_type; /* RAID_TYPE_0 or RAID_TYPE_1 or RAID_TYPE_5 */
uint _raid_chunks; /* 1..n */
ulong _raid_chunksize; /* 1..n in bytes */
ulong _total_block; /* We are operating with block no x (can be 0..many). */
uint _this_block; /* can be 0.._raid_chunks */
uint _remaining_bytes; /* Maximum bytes that can be written in this block */
my_off_t _position;
my_off_t _size; /* Cached file size for faster seek(SEEK_END) */
File _fd;
File *_fd_vector; /* Array of File */
off_t *_seek_vector; /* Array of cached seek positions */
inline void Calculate()
{
DBUG_ENTER("RaidFd::_Calculate");
DBUG_PRINT("info",("_position: %lu _raid_chunksize: %d, _size: %lu",
(ulong) _position, _raid_chunksize, (ulong) _size));
_total_block = (ulong) (_position / _raid_chunksize);
_this_block = _total_block % _raid_chunks; /* can be 0.._raid_chunks */
_remaining_bytes = (uint) (_raid_chunksize -
(_position - _total_block * _raid_chunksize));
DBUG_PRINT("info",
("_total_block: %d this_block: %d _remaining_bytes:%d",
_total_block, _this_block, _remaining_bytes));
DBUG_VOID_RETURN;
}
};
#endif /* __cplusplus */
#endif /* USE_RAID */
+48
View File
@@ -0,0 +1,48 @@
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
extern const char *unknown_sqlstate;
extern const char *not_error_sqlstate;
#ifdef __cplusplus
extern "C" {
#endif
MYSQL_FIELD *unpack_fields(MYSQL_DATA *data,MEM_ROOT *alloc,uint fields,
my_bool default_value, uint server_capabilities);
void free_rows(MYSQL_DATA *cur);
void flush_use_result(MYSQL *mysql);
my_bool mysql_autenticate(MYSQL *mysql, const char *passwd);
void free_old_query(MYSQL *mysql);
void end_server(MYSQL *mysql);
my_bool mysql_reconnect(MYSQL *mysql);
void mysql_read_default_options(struct st_mysql_options *options,
const char *filename,const char *group);
my_bool
cli_advanced_command(MYSQL *mysql, enum enum_server_command command,
const char *header, ulong header_length,
const char *arg, ulong arg_length, my_bool skip_check);
void set_stmt_errmsg(MYSQL_STMT * stmt, const char *err, int errcode,
const char *sqlstate);
void set_mysql_error(MYSQL *mysql, int errcode, const char *sqlstate);
#ifdef __cplusplus
}
#endif
#define protocol_41(A) ((A)->server_capabilities & CLIENT_PROTOCOL_41)
+164
View File
@@ -0,0 +1,164 @@
/* Copyright (C) 2000-2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/*
This file includes a mapping from mysql_errno.h to sql_state (as used by
MyODBC) and jdbc_state.
It's suitable to include into a C struct for further processing
The first column is the mysqld server error (declared in mysqld_error.h),
the second column is the ODBC state (which the 4.1 server sends out by
default) and the last is the state used by the JDBC driver.
If the last column is "" then it means that the JDBC driver is using the
ODBC state.
The errors in this file are sorted in the same order as in mysqld_error.h
to allow one to do binary searches for the sqlstate.
*/
ER_DUP_KEY, "23000", "",
ER_OUTOFMEMORY, "HY001", "S1001",
ER_OUT_OF_SORTMEMORY, "HY001", "S1001",
ER_CON_COUNT_ERROR, "08004", "",
ER_BAD_HOST_ERROR, "08S01", "",
ER_HANDSHAKE_ERROR, "08S01", "",
ER_DBACCESS_DENIED_ERROR, "42000", "",
ER_ACCESS_DENIED_ERROR, "28000", "",
ER_NO_DB_ERROR, "3D000", "",
ER_UNKNOWN_COM_ERROR, "08S01", "",
ER_BAD_NULL_ERROR, "23000", "",
ER_BAD_DB_ERROR, "42000", "",
ER_TABLE_EXISTS_ERROR, "42S01", "",
ER_BAD_TABLE_ERROR, "42S02", "",
ER_NON_UNIQ_ERROR, "23000", "",
ER_SERVER_SHUTDOWN, "08S01", "",
ER_BAD_FIELD_ERROR, "42S22", "S0022",
ER_WRONG_FIELD_WITH_GROUP, "42000", "S1009",
ER_WRONG_GROUP_FIELD, "42000", "S1009",
ER_WRONG_SUM_SELECT, "42000", "S1009",
ER_WRONG_VALUE_COUNT, "21S01", "",
ER_TOO_LONG_IDENT, "42000", "S1009",
ER_DUP_FIELDNAME, "42S21", "S1009",
ER_DUP_KEYNAME, "42000", "S1009",
ER_DUP_ENTRY, "23000", "S1009",
ER_WRONG_FIELD_SPEC, "42000", "S1009",
ER_PARSE_ERROR, "42000", "",
ER_EMPTY_QUERY, "42000" , "",
ER_NONUNIQ_TABLE, "42000", "S1009",
ER_INVALID_DEFAULT, "42000", "S1009",
ER_MULTIPLE_PRI_KEY, "42000", "S1009",
ER_TOO_MANY_KEYS, "42000", "S1009",
ER_TOO_MANY_KEY_PARTS, "42000", "S1009",
ER_TOO_LONG_KEY, "42000", "S1009",
ER_KEY_COLUMN_DOES_NOT_EXITS, "42000", "S1009",
ER_BLOB_USED_AS_KEY, "42000", "S1009",
ER_TOO_BIG_FIELDLENGTH, "42000", "S1009",
ER_WRONG_AUTO_KEY, "42000", "S1009",
ER_FORCING_CLOSE, "08S01", "",
ER_IPSOCK_ERROR, "08S01", "",
ER_NO_SUCH_INDEX, "42S12", "S1009",
ER_WRONG_FIELD_TERMINATORS, "42000", "S1009",
ER_BLOBS_AND_NO_TERMINATED, "42000", "S1009",
ER_CANT_REMOVE_ALL_FIELDS, "42000", "",
ER_CANT_DROP_FIELD_OR_KEY, "42000", "",
ER_BLOB_CANT_HAVE_DEFAULT, "42000", "",
ER_WRONG_DB_NAME, "42000", "",
ER_WRONG_TABLE_NAME, "42000", "",
ER_TOO_BIG_SELECT, "42000", "",
ER_UNKNOWN_PROCEDURE, "42000", "",
ER_WRONG_PARAMCOUNT_TO_PROCEDURE, "42000", "",
ER_UNKNOWN_TABLE, "42S02", "",
ER_FIELD_SPECIFIED_TWICE, "42000", "",
ER_UNSUPPORTED_EXTENSION, "42000", "",
ER_TABLE_MUST_HAVE_COLUMNS, "42000", "",
ER_UNKNOWN_CHARACTER_SET, "42000", "",
ER_TOO_BIG_ROWSIZE, "42000", "",
ER_WRONG_OUTER_JOIN, "42000", "",
ER_NULL_COLUMN_IN_INDEX, "42000", "",
ER_PASSWORD_ANONYMOUS_USER, "42000", "",
ER_PASSWORD_NOT_ALLOWED, "42000", "",
ER_PASSWORD_NO_MATCH, "42000", "",
ER_WRONG_VALUE_COUNT_ON_ROW, "21S01", "",
ER_INVALID_USE_OF_NULL, "42000", "",
ER_REGEXP_ERROR, "42000", "",
ER_MIX_OF_GROUP_FUNC_AND_FIELDS,"42000", "",
ER_NONEXISTING_GRANT, "42000", "",
ER_TABLEACCESS_DENIED_ERROR, "42000", "",
ER_COLUMNACCESS_DENIED_ERROR, "42000", "",
ER_ILLEGAL_GRANT_FOR_TABLE, "42000", "",
ER_GRANT_WRONG_HOST_OR_USER, "42000", "",
ER_NO_SUCH_TABLE, "42S02", "",
ER_NONEXISTING_TABLE_GRANT, "42000", "",
ER_NOT_ALLOWED_COMMAND, "42000", "",
ER_SYNTAX_ERROR, "42000", "",
ER_ABORTING_CONNECTION, "08S01", "",
ER_NET_PACKET_TOO_LARGE, "08S01", "",
ER_NET_READ_ERROR_FROM_PIPE, "08S01", "",
ER_NET_FCNTL_ERROR, "08S01", "",
ER_NET_PACKETS_OUT_OF_ORDER, "08S01", "",
ER_NET_UNCOMPRESS_ERROR, "08S01", "",
ER_NET_READ_ERROR, "08S01", "",
ER_NET_READ_INTERRUPTED, "08S01", "",
ER_NET_ERROR_ON_WRITE, "08S01", "",
ER_NET_WRITE_INTERRUPTED, "08S01", "",
ER_TOO_LONG_STRING, "42000", "",
ER_TABLE_CANT_HANDLE_BLOB, "42000", "",
ER_TABLE_CANT_HANDLE_AUTO_INCREMENT, "42000", "",
ER_WRONG_COLUMN_NAME, "42000", "",
ER_WRONG_KEY_COLUMN, "42000", "",
ER_DUP_UNIQUE, "23000", "",
ER_BLOB_KEY_WITHOUT_LENGTH, "42000", "",
ER_PRIMARY_CANT_HAVE_NULL, "42000", "",
ER_TOO_MANY_ROWS, "42000", "",
ER_REQUIRES_PRIMARY_KEY, "42000", "",
ER_CHECK_NO_SUCH_TABLE, "42000", "",
ER_CHECK_NOT_IMPLEMENTED, "42000", "",
ER_CANT_DO_THIS_DURING_AN_TRANSACTION, "25000", "",
ER_NEW_ABORTING_CONNECTION, "08S01", "",
ER_MASTER_NET_READ, "08S01", "",
ER_MASTER_NET_WRITE, "08S01", "",
ER_TOO_MANY_USER_CONNECTIONS, "42000", "",
ER_READ_ONLY_TRANSACTION, "25000", "",
ER_NO_PERMISSION_TO_CREATE_USER,"42000", "",
ER_LOCK_DEADLOCK, "40001", "",
ER_NO_REFERENCED_ROW, "23000", "",
ER_ROW_IS_REFERENCED, "23000", "",
ER_CONNECT_TO_MASTER, "08S01", "",
ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT,"21000", "",
ER_USER_LIMIT_REACHED, "42000", "",
ER_NO_DEFAULT, "42000", "",
ER_WRONG_VALUE_FOR_VAR, "42000", "",
ER_WRONG_TYPE_FOR_VAR, "42000", "",
ER_CANT_USE_OPTION_HERE, "42000", "",
ER_NOT_SUPPORTED_YET, "42000", "",
ER_WRONG_FK_DEF, "42000", "",
ER_OPERAND_COLUMNS, "21000", "",
ER_SUBQUERY_NO_1_ROW, "21000", "",
ER_ILLEGAL_REFERENCE, "42S22", "",
ER_DERIVED_MUST_HAVE_ALIAS, "42000", "",
ER_SELECT_REDUCED, "01000", "",
ER_TABLENAME_NOT_ALLOWED_HERE, "42000", "",
ER_NOT_SUPPORTED_AUTH_MODE, "08004", "",
ER_SPATIAL_CANT_HAVE_NULL, "42000", "",
ER_COLLATION_CHARSET_MISMATCH, "42000", "",
ER_WARN_TOO_FEW_RECORDS, "01000", "",
ER_WARN_TOO_MANY_RECORDS, "01000", "",
ER_WARN_NULL_TO_NOTNULL, "01000", "",
ER_WARN_DATA_OUT_OF_RANGE, "01000", "",
ER_WARN_DATA_TRUNCATED, "01000", "",
ER_WRONG_NAME_FOR_INDEX, "42000", "",
ER_WRONG_NAME_FOR_CATALOG, "42000", "",
ER_UNKNOWN_STORAGE_ENGINE, "42000", "",
+29
View File
@@ -0,0 +1,29 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifdef HAVE_OPENSSL
case OPT_SSL_KEY:
case OPT_SSL_CERT:
case OPT_SSL_CA:
case OPT_SSL_CAPATH:
case OPT_SSL_CIPHER:
/*
Enable use of SSL if we are using any ssl option
One can disable SSL later by using --skip-ssl or --ssl=0
*/
opt_use_ssl= 1;
break;
#endif
+41
View File
@@ -0,0 +1,41 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifdef HAVE_OPENSSL
{"ssl", OPT_SSL_SSL,
"Enable SSL for connection (automatically enabled with other flags). Disable with --skip-ssl.",
(gptr*) &opt_use_ssl, (gptr*) &opt_use_ssl, 0, GET_BOOL, NO_ARG, 0, 0, 0,
0, 0, 0},
{"ssl-key", OPT_SSL_KEY, "X509 key in PEM format (implies --ssl).",
(gptr*) &opt_ssl_key, (gptr*) &opt_ssl_key, 0, GET_STR, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
{"ssl-cert", OPT_SSL_CERT, "X509 cert in PEM format (implies --ssl).",
(gptr*) &opt_ssl_cert, (gptr*) &opt_ssl_cert, 0, GET_STR, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
{"ssl-ca", OPT_SSL_CA,
"CA file in PEM format (check OpenSSL docs, implies --ssl).",
(gptr*) &opt_ssl_ca, (gptr*) &opt_ssl_ca, 0, GET_STR, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
{"ssl-capath", OPT_SSL_CAPATH,
"CA directory (check OpenSSL docs, implies --ssl).",
(gptr*) &opt_ssl_capath, (gptr*) &opt_ssl_capath, 0, GET_STR, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
{"ssl-cipher", OPT_SSL_CIPHER, "SSL cipher to use (implies --ssl).",
(gptr*) &opt_ssl_cipher, (gptr*) &opt_ssl_cipher, 0, GET_STR, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
#endif /* HAVE_OPENSSL */
+24
View File
@@ -0,0 +1,24 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifdef HAVE_OPENSSL
static my_bool opt_use_ssl = 0;
static char *opt_ssl_key = 0;
static char *opt_ssl_cert = 0;
static char *opt_ssl_ca = 0;
static char *opt_ssl_capath = 0;
static char *opt_ssl_cipher = 0;
#endif
+33
View File
@@ -0,0 +1,33 @@
/* Copyright (C) 2000 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef _typelib_h
#define _typelib_h
typedef struct st_typelib { /* Different types saved here */
unsigned int count; /* How many types */
const char *name; /* Name of typelib */
const char **type_names;
} TYPELIB;
extern int find_type(char *x,TYPELIB *typelib,unsigned int full_name);
extern void make_type(char *to,unsigned int nr,TYPELIB *typelib);
extern const char *get_type(TYPELIB *typelib,unsigned int nr);
extern TYPELIB sql_protocol_typelib;
#endif /* _typelib_h */
+31
View File
@@ -0,0 +1,31 @@
CC = clang++-devel
TARGET = teen.exe
IFLAGS = -I./INCLUDE -I../../
CFLAGS = $(IFLAGS) -Wall -O2 -pipe -g
LIBS = -L./LIB -lmysqlclient -lz -lm
SRCS = main.c utils.c socket.c signal.c input.c config.c \
libsql.c sql.c log.c tellwait.c sql_account.c event.c priority_queue.c
OBJS = $(SRCS:%.c=%.o)
default: $(TARGET)
$(TARGET): $(OBJS)
$(CC) -static -o ../$(TARGET) $(OBJS) $(LIBS)
chmod 700 ../$(TARGET)
%.o:%.c
$(CC) $(CFLAGS) -c $<
clean:
rm -f *.o ../$(TARGET)
dep:
$(CC) -MM $(SRCS) > Depend
install:
cp -f ../$(TARGET) $(HOME)/TEST/chat
sinclude Depend
+73
View File
@@ -0,0 +1,73 @@
#include "structs.h"
#include "utils.h"
#include "log.h"
BYTE base_gid1, base_gid2;
WORD mother_port = 10077;
char sql_addr[256] = {0};
char sql_user[256] = {0};
char sql_password[256] = {0};
char sql_db_name[256] = {0};
char sql_teenage_table[256] = {0};
char sql_account_table[256] = {0};
char char_set[256] = {0};
int locale_index = 0;
int teen_all_flag = 0;
void init_config(void)
{
FILE *fp;
char buf[256];
char token_string[256];
char value_string[256];
if (!(fp = fopen("CONFIG", "r")))
{
sys_log("Can not open CONFIG");
exit(1);
}
while (fgets(buf, 256, fp))
{
parse_token(buf, token_string, value_string);
TOKEN("sql_addr")
strncpy(sql_addr, value_string, 256);
TOKEN("sql_user")
strncpy(sql_user, value_string, 256);
TOKEN("sql_password")
strncpy(sql_password, value_string, 256);
TOKEN("sql_db_name")
strncpy(sql_db_name, value_string, 256);
TOKEN("sql_teenage_table")
strncpy(sql_teenage_table, value_string, 256);
TOKEN("sql_account_table")
strncpy(sql_account_table, value_string, 256);
TOKEN("port")
mother_port = atoi(value_string);
TOKEN("char_set")
strncpy(char_set, value_string, 256);
TOKEN("teen_all")
teen_all_flag = atoi(value_string);
}
// check arg
#define FAIL_EXIT(val) \
if (val[0]==0) \
{ \
sys_err("FAIL -> open %s", #val); \
exit(1); \
}
FAIL_EXIT(sql_addr);
FAIL_EXIT(sql_user);
FAIL_EXIT(sql_password);
FAIL_EXIT(sql_db_name);
FAIL_EXIT(sql_teenage_table);
#undef FAIL_EXIT
fclose(fp);
}
+22
View File
@@ -0,0 +1,22 @@
#ifndef _CONFIG_H_
#define _CONFIG_H_
void init_config(void);
extern int base_gid1, base_gid2;
extern WORD mother_port;
extern char sql_addr[256];
extern char sql_user[256];
extern char sql_password[256];
extern char sql_db_name[256];
extern char sql_teenage_table[256];
extern char sql_account_table[256];
extern char char_set[256];
extern int locale_index;
extern int teen_all_flag;
#endif // _CONFIG_H_
+133
View File
@@ -0,0 +1,133 @@
/*
* Filename: event.c
* Description: 이벤트 관련 (timed event)
*
* Author: 김한주 (aka. 비엽, Cronan), 송영진 (aka. myevan, 빗자루)
*/
#include "structs.h"
#include "utils.h"
#include "priority_queue.h"
#include "log.h"
extern int global_pulse; /* main.c */
static PRIORITY_QUEUE* event_q = NULL; /* 이벤트 queue (리스트) */
/* 이벤트 queue 를 초기화 한다 */
void event_init(void)
{/*{{{*/
sys_log("Intializing Event Engine.");
event_q = queue_init();
}
/*}}}*/
/* 이벤트를 생성하고 리턴한다 */
LPEVENT event_create_ex(EVENTFUNC(*func), void *event_obj, long when, const char *file, int line)
{/*{{{*/
LPEVENT new_event;
/* 반드시 다음 pulse 이상의 시간이 지난 후에 부르도록 한다. */
if (when < 1)
when = 1;
CREATE(new_event, EVENT, 1);
strncpy(new_event->file, file, 63);
new_event->line = line;
new_event->func = func;
new_event->info = event_obj;
new_event->q_el = queue_enq(event_q, new_event, when + global_pulse);
return (new_event);
}/*}}}*/
/* 시스템으로 부터 이벤트를 제거한다 */
void event_cancel(LPEVENT event)
{/*{{{*/
if (!event)
{
sys_err("event_cancel(): try to cancel NULL event");
return;
}
queue_deq(event_q, event->q_el);
free(event->info);
free(event);
}/*}}}*/
void event_reset_time(LPEVENT event, long when)
{/*{{{*/
event->q_el = queue_reque(event_q, event->q_el, when + global_pulse);
}
/*}}}*/
/* 이벤트를 실행할 시간에 도달한 이벤트들을 실행한다 */
void event_process(void)
{/*{{{*/
EVENT *the_event;
long new_time;
char last_file[128];
int last_line = -1, last_time = -1;
// event_q 즉 이벤트 큐의 헤드의 시간보다 현재의 pulse 가 적으면 루프문이
// 돌지 않게 된다.
while ((long) global_pulse >= queue_key(event_q))
{
new_time = queue_key(event_q);
if (!(the_event = (LPEVENT) queue_head(event_q)))
{
sys_err("event_process(): trying to call NULL event");
return;
}
if (strcmp(the_event->file, last_file) || last_line != the_event->line || last_time != new_time)
{
strcpy(last_file, the_event->file);
last_line = the_event->line;
last_time = new_time;
// sys_log("EVENT: %s %d %d", the_event->file, the_event->line, new_time);
}
/*
* 리턴 값은 새로운 시간이며 리턴 값이 0 보다 클 경우 이벤트를 다시 추가한다.
* 리턴 값을 0 이상으로 할 경우 event 에 할당된 메모리 정보를 삭제하지 않도록
* 주의한다.
*/
if ((new_time = (the_event->func) (the_event)) > 0)
the_event->q_el = queue_enq(event_q, the_event, new_time + global_pulse);
else
{
free(the_event->info);
free(the_event);
}
}
}/*}}}*/
/* 이벤트가 남은 시간을 pulse 단위로 리턴해 준다 */
long event_time(LPEVENT event)
{/*{{{*/
long when;
when = queue_elmt_key(event->q_el);
return (when - global_pulse);
}
/*}}}*/
/* 모든 이벤트를 제거한다 */
void event_destroy()
{/*{{{*/
LPEVENT the_event;
if (!event_q)
return;
while ((the_event = (LPEVENT) queue_head(event_q)))
free(the_event);
queue_free(event_q);
event_q = NULL;
}/*}}}*/
+40
View File
@@ -0,0 +1,40 @@
/*
* Filename: event.h
* Description: 이벤트 관련 (timed event)
*
* Author: 김한주 (aka. 비엽, Cronan), 송영진 (aka. myevan, 빗자루)
*/
#ifndef __INC_METIN_EVENT_H__
#define __INC_METIN_EVENT_H__
typedef struct priority_q_element PRIORITY_Q_ELEMENT;
typedef struct event_info EVENT;
typedef struct event_info * LPEVENT;
#define EVENTFUNC(name) long (name) (LPEVENT event)
struct event_info
{
EVENTFUNC(*func);
void* info;
PRIORITY_Q_ELEMENT* q_el;
char file[64];
int line;
};
/* 함수 선언 */
extern void event_init();
extern void event_destroy();
extern LPEVENT event_create_ex(EVENTFUNC(*func), void *event_obj, long when, const char *file, int line);
#define event_create(func, event_obj, when) event_create_ex(func, event_obj, when, __FILE__, __LINE__)
extern void event_cancel(LPEVENT event);
extern void event_process();
extern long event_time(LPEVENT event);
extern void event_reset_time(LPEVENT event, long when);
#endif
View File
+420
View File
@@ -0,0 +1,420 @@
#include "structs.h"
#include "utils.h"
#include "socket.h"
#include "protocol.h"
#include "input.h"
#include "log.h"
#include "sql_account.h"
#include "config.h"
#include <common/teen_packet.h>
#include <map>
extern int global_pulse;
#define CHECK_TIME_SEC 10 // 10초
struct conn_event_info
{
CONN_DATA *conn;
};
typedef std::map<DWORD,CONN_DATA*> CONN_MAP;
CONN_MAP s_conn_map;
void packet_header(PACKET_DATA *buf, BYTE header, WORD desc_num)
{
packet(buf, encode_byte(header), 1);
packet(buf, encode_2bytes(desc_num), 2);
}
void packet_teen_notice(CONN_DATA *conn, int hour)
{
DESC_DATA *desc = GET_DESC(conn);
PACKET_DATA *buf = &desc->packet_buffer;
packet_header(buf, HEADER_TG_TEEN_NOTICE, desc->desc_num);
packet(buf, GET_LOGIN(conn), MAX_LOGIN_LEN);
packet(buf, encode_4bytes(hour), 4);
sys_log("NOTICE: (login,hour) = (%s, %d)", GET_LOGIN(conn), hour);
}
void packet_force_logout(DESC_DATA *desc, CONN_DATA *conn)
{
PACKET_DATA *buf = &desc->packet_buffer;
packet_header(buf, HEADER_TG_FORCE_LOGOUT, desc->desc_num);
packet(buf, GET_LOGIN(conn), MAX_LOGIN_LEN);
}
void packet_login_notice(CONN_DATA *conn)
{
DESC_DATA *desc = GET_DESC(conn);
if (NULL==desc) return;
PACKET_DATA *buf = &desc->packet_buffer;
packet_header(buf, HEADER_TG_LOGIN_NOTICE, desc->desc_num);
packet(buf, GET_LOGIN(conn), MAX_LOGIN_LEN);
packet(buf, encode_4bytes(GET_ON_TIME(conn)), 4);
packet(buf, encode_4bytes(GET_OFF_TIME(conn)), 4);
}
void send_force_logout(CONN_DATA *conn)
{
DESC_DATA *desc = GET_DESC(conn);
if (NULL==desc) return;
sys_log("FORCE_LOGOUT : %d, %s", GET_ID(conn), GET_LOGIN(conn)?GET_LOGIN(conn):"null");
packet_force_logout(desc, conn);
}
int __online_hour(CONN_DATA *conn)
{
return (GET_ON_TIME(conn)/HOUR_TO_SEC(1));
}
void send_login_notice(CONN_DATA *conn)
{
packet_login_notice(conn);
}
void set_notice_step(CONN_DATA *conn)
{
int hour = __online_hour(conn);
switch (hour)
{
case 0: GET_NOTICE_STEP(conn) = 0; break;
case 1: GET_NOTICE_STEP(conn) = 0; break;
case 2: GET_NOTICE_STEP(conn) = 1; break;
case 3: GET_NOTICE_STEP(conn) = 2; break;
case 4: GET_NOTICE_STEP(conn) = 3; break;
default: GET_NOTICE_STEP(conn) = 4; break;
}
GET_NOTICE_PULSE(conn) = 0;
}
void send_notice(CONN_DATA *conn)
{
int hour = __online_hour(conn);
switch (hour)
{
case 0:
/* do nothing */
break;
case 1:
if (0==GET_NOTICE_STEP(conn))
{
GET_NOTICE_STEP(conn) = 1;
packet_teen_notice(conn, hour);
}
break;
case 2:
if (1==GET_NOTICE_STEP(conn))
{
GET_NOTICE_STEP(conn) = 2;
packet_teen_notice(conn, hour);
}
break;
case 3:
if (2==GET_NOTICE_STEP(conn))
{
GET_NOTICE_STEP(conn) = 3;
packet_teen_notice(conn, hour);
}
break;
case 4:
if (3==GET_NOTICE_STEP(conn))
{
GET_NOTICE_STEP(conn) = 4;
packet_teen_notice(conn, hour);
}
break;
default:
if ( 0==(GET_NOTICE_PULSE(conn) % MINUTE_TO_PULSE(15)) )
{
packet_teen_notice(conn, hour);
GET_NOTICE_PULSE(conn) = global_pulse;
}
break;
}
}
EVENTFUNC(conn_event_func)
{
if (NULL==event || NULL==event->info) return 0;
struct conn_event_info *info = (conn_event_info*) event->info;
CONN_DATA *conn = info->conn;
if (NULL==conn)
return 0;
GET_ON_TIME(conn) += CHECK_TIME_SEC;
send_notice(conn);
return (CHECK_TIME_SEC * PASSES_PER_SEC);
}
void conn_delete_by_desc(DESC_DATA *d)
{
CONN_MAP::iterator iter, cur_iter;
for (iter = s_conn_map.begin(); iter != s_conn_map.end(); )
{
cur_iter = iter; iter++;
CONN_DATA *conn = cur_iter->second;
if (GET_DESC(conn) == d)
{
s_conn_map.erase(cur_iter);
account_logout(conn);
if (GET_EVENT(conn))
{
event_cancel(GET_EVENT(conn));
GET_EVENT(conn) = NULL;
}
SAFE_FREE(conn);
}
}
}
CONN_DATA *conn_find(DWORD account_id)
{
CONN_MAP::iterator iter;
iter = s_conn_map.find(account_id);
if (iter!=s_conn_map.end())
{
CONN_DATA *conn = iter->second;
return conn;
}
return NULL;
}
CONN_DATA* conn_insert(CONN_DATA *conn)
{
s_conn_map.insert(std::make_pair(GET_ID(conn), conn));
return conn;
}
void conn_delete(DWORD account_id)
{
CONN_MAP::iterator iter;
iter = s_conn_map.find(account_id);
if (iter==s_conn_map.end())
return;
CONN_DATA *conn = iter->second;
s_conn_map.erase(iter);
sys_log("CONN_DELETE : %d, %s", GET_ID(conn), GET_LOGIN(conn)?GET_LOGIN(conn):"null");
if (GET_EVENT(conn))
{
event_cancel(GET_EVENT(conn));
GET_EVENT(conn) = NULL;
}
account_logout(conn);
SAFE_FREE(conn);
}
int input_login(DESC_DATA *d, const char *data, int plen)
{
const int PACKET_LENGTH = 4;
if (plen < PACKET_LENGTH)
return 0;
DWORD account_id = decode_4bytes((const BYTE*)data);
// sys_log("LOGIN: %u", account_id);
/* 기존 정보가 있으면 접속을 끊으라고 알려줌 */
CONN_DATA *conn = conn_find(account_id);
if (conn)
{
send_force_logout(conn);
//conn_delete(GET_ID(conn));
// 새로운 접속자도 접속을 끊는다.
{
PACKET_DATA *buf = &d->packet_buffer;
packet_header(buf, HEADER_TG_FORCE_LOGOUT, d->desc_num);
packet(buf, GET_LOGIN(conn), MAX_LOGIN_LEN);
}
return PACKET_LENGTH;
}
conn = (CONN_DATA*) calloc(1, sizeof(CONN_DATA));
GET_ID(conn) = account_id;
GET_DESC(conn) = d;
GET_EVENT(conn) = NULL;
int login_succ = FALSE;
if (teen_all_flag)
login_succ = account_login_teen_all(account_id, conn);
else
login_succ = account_login(account_id, conn);
if (FALSE==login_succ)
{
//conn_delete(GET_ID(conn));
SAFE_FREE(conn);
return PACKET_LENGTH;
}
conn_insert(conn);
if (YES==GET_TEENAGE(conn))
{
conn_event_info *info = (conn_event_info*) calloc(1, sizeof(conn_event_info));
info->conn = conn;
GET_EVENT(conn) = event_create(conn_event_func, info, (CHECK_TIME_SEC * PASSES_PER_SEC));
}
else
{
GET_EVENT(conn) = NULL;
}
if (YES==GET_TEENAGE(conn))
{
send_login_notice(conn);
set_notice_step(conn);
send_notice(conn);
}
sys_log("CONN_INSERT : %u, %s", GET_ID(conn), GET_LOGIN(conn));
return PACKET_LENGTH;
} /* end of input_login() */
int input_logout(DESC_DATA *d, const char *data, int plen)
{
const int PACKET_LENGTH = 4;
if (plen < PACKET_LENGTH)
return 0;
DWORD account_id = decode_4bytes((const BYTE*)data);
// sys_log("LOGOUT: %u", account_id);
CONN_DATA *conn = conn_find(account_id);
if (NULL==conn)
{
return PACKET_LENGTH;
}
// update online time and logout time
{
conn_delete(account_id);
}
return PACKET_LENGTH;
} /* end of input_logout() */
int input_handshake(DESC_DATA *d, char *orig, int bytes)
{
if (bytes < 4)
return 0;
if (d->handshake == *(DWORD *) orig)
assign_state(d, STATE_MAIN);
else
{
sys_log("SYSERR: BAD_HANDSHAKE: %d %d", d->handshake, *(DWORD *) orig);
assign_state(d, STATE_CLOSE);
}
return 4;
}
int input_main(DESC_DATA *d, char *orig, int bytes)
{
char *data = orig;
BYTE header, last_header = 0;
WORD desc_num;
int i, pl, last_pl = 0, bytes_proceed = 0;
for (i = bytes; i > 0;)
{
header = (BYTE) *(data++);
i--;
// desc_num 은 2 bytes 이므로 2 bytes 보다 내용이 적으면 bytes 를 리턴
if (i < 2)
return (bytes_proceed);
desc_num = *((WORD *) data);
data += 2;
i -= 2;
pl = 0;
switch (header)
{
case HEADER_GT_LOGIN:
if (!(pl = input_login(d, data, i)))
return (bytes_proceed);
break;
case HEADER_GT_LOGOUT:
if (!(pl = input_logout(d, data, i)))
return (bytes_proceed);
break;
default:
sys_log("UNKNOWN HEADER: %d, LAST HEADER: %d(%d), REMAIN BYTES: %d, DESC: %d",
header, last_header, last_pl, i, d->desc_num);
printdata((BYTE*)orig, bytes);
assign_state(d, STATE_CLOSE);
return (bytes);
}
data += pl;
i -= pl;
bytes_proceed += 3 + pl;
last_pl = pl;
last_header = header;
}
return (bytes);
}
+7
View File
@@ -0,0 +1,7 @@
#ifndef _INPUT_H_
#define _INPUT_H_
int input_handshake(DESC_DATA *d, char *data, int bytes);
int input_main(DESC_DATA *d, char *data, int bytes);
#endif // _INPUT_H_
+113
View File
@@ -0,0 +1,113 @@
#ifndef __INC_METIN_LENGTH_H__
#define __INC_METIN_LENGTH_H__
#define MAX_SQL_LOGIN_LENGTH 8
#define MAX_SQL_PWD_LENGTH 12
#define MAX_SQL_REAL_NAME_LENGTH 20
#define MAX_SQL_SOCIAL_ID_LENGTH 18
#define MAX_SQL_EMAIL_LENGTH 40
#define MAX_SQL_PHONE_LENGTH 14
#define MAX_SQL_ADDRESS_LENGTH 80
#define MAX_SQL_GAME_ID_LENGTH 20
#define MAX_SQL_IP_ADDR_LENGTH 15
#define MAX_SQL_SERIAL_LENGTH 25
#define MAX_SQL_BANK_PWD_LENGTH 8
#define MAX_NAME_LENGTH 16
#define MAX_ITEM_NAME_LENGTH 32
#define MAX_SOCIAL_LENGTH 16
#define MAX_TITLE_LENGTH 16
#define MAX_PWD_LENGTH 16
#define MAX_GAME_STORES 2
#define HOST_LENGTH 30
#define MAX_HOST_LENGTH HOST_LENGTH
enum EDescTypes
{
CLIENT_TYPE_GAME,
CLIENT_TYPE_ACCOUNT,
CLIENT_TYPE_UTILS
};
#define HANDSHAKE_XOR 0x6AB3D224
#define MAX_DRAWLIST 256
#define MAX_ITEMS_ON_CHARACTER 80 // 소지할 수 있는 아이템 갯수
#define MAX_EXCHANGE_ITEMS_ON_CHARACTER 4 // 교환할 수 있는 아이템 갯수
#define MAX_QITEMS_ON_CHARACTER 10 // 퀵창에 가질 수 있는 아이템 갯수
#define MAX_ITEMS_ON_BANK 80 // 은행에 가질 수 있는 아이템 갯수
#define MAX_AFFECTS 116 // 가질 수 있는 효과
#define MAX_QUESTS 256 // 최대 퀘스트 갯수
#define MAX_QUEST_QUESTIONS 16 // 최대 퀘스트 질문수
#define MAX_GROUP_MEMBERS 16 // 최대 그룹 멤버 수
#define MAX_SKILL_PER_TYPE 240
#define MAX_QSKILLS 10
#define SKILL_TYPE_SKILL 0 // 기술
#define SKILL_TYPE_MAGIC 1 // 마법
#define SKILL_TYPE_KNOWLEDGE 2 // 지식
#define SKILL_TYPE_SPECIAL 2 // 기타
#define MAX_SKILL_TYPES 3 // 기술 종류
#define GUILD_TYPE_COMBAT 0 // 전투 목적 길드
#define GUILD_TYPE_ETC 1 // 기타 (종교) 목적 길드
#define GUILD_TYPE_ECONOMY 2 // 영리 목적 길드
#define MAX_GUILD_TYPES 3 // 길드 종류
#define MAX_ATTACK_LIST 32 // 공격 리스트
#define MAX_VOICE_MEMBERS 4
//
// For Characters
//
/* 성별 */
enum ESex
{
SEX_NEUTRAL,
SEX_FEMALE,
SEX_MALE,
NUM_SEX
};
/* 종족 */
#define RACE_SENT 0 // 센트 종족
#define RACE_ELF 1 // 엘프 종족
#define RACE_DWARF 2 // 드워프
#define NUM_RACES 3 // 종족 갯수
/* 입을 수 있는 부위 */
#define WEAR_HEAD 1 // 머리
#define WEAR_NECK 2 // 목
#define WEAR_BODY 3 // 몸
#define WEAR_HAND 4 // 양손 (장갑)
#define WEAR_FEET 5 // 양발
#define WEAR_R_FINGER 6 // 오른쪽 손가락
#define WEAR_L_FINGER 7 // 왼쪽 손가락
#define WEAR_WIELD 8 // 무기
#define WEAR_HOLD 9 // 잡기
#define NUM_WEARS 10 // 입을 부위의 총 갯수
//
// For items
//
#define MAX_ITEM_AFFECT 4 // 0 1 2 3
#define MAX_ITEM_VALUES 5 // 0 1 2 3 4
#define MAX_ITEM_RESOURCES 4
#define MAX_ITEM_IMPROVE 24 // 나기라의 눈물로 개량할 수 있는 한계
// by mhh
#define MAX_COMBINE_COUNT 200
#endif
+314
View File
@@ -0,0 +1,314 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <zlib.h>
#include "libsql.h"
#include "tellwait.h"
#include "log.h"
extern void clean_server();
// internal functions
void sql_async_loop(SQL * sql);
static void gzlog_rotate(const char *basename, int count);
SQL * sql_create(const char *addr, const char *user, const char *password, const char *dbname)
{
SQL * sql;
sql = (SQL *) calloc(1, sizeof(SQL));
sql->async_query_pipe[0] = -1;
sql->async_query_pipe[1] = -1;
mysql_init(&sql->sql_conn);
if (char_set[0])
mysql_options(&sql->sql_conn, MYSQL_SET_CHARSET_NAME, char_set);
strncpy(sql->addr, addr, 64);
sql->addr[64] = '\0';
strncpy(sql->user, user, 64);
sql->user[64] = '\0';
strncpy(sql->password, password, 64);
sql->password[64] = '\0';
strncpy(sql->dbname, dbname, 64);
sql->dbname[64] = '\0';
sys_log("SQL: trying to connect %s@%s db %s", sql->user, sql->addr, sql->dbname);
if (!mysql_real_connect(&sql->sql_conn, sql->addr, sql->user, sql->password, sql->dbname, 0, NULL, 0))
{
sql_error(sql);
free(sql);
return NULL;
}
return (sql);
}
SQL * sql_clone(SQL * sql)
{
SQL * new_sql;
if (!(new_sql = sql_create(sql->addr, sql->user, sql->password, sql->dbname)))
return NULL;
new_sql->async_query_pipe[0] = sql->async_query_pipe[0];
new_sql->async_query_pipe[1] = sql->async_query_pipe[1];
return (new_sql);
}
int sql_async_start(SQL * sql)
{
int pid;
if (pipe(sql->async_query_pipe) < 0)
{
perror("pipe");
return 0;
}
TELL_WAIT();
if ((pid = fork()) < 0)
{
perror("fork");
return 0;
}
if (pid > 0) // parent
{
close(sql->async_query_pipe[0]); // 읽기는 필요 없다.
sql->async_query_pipe[0] = -1;
WAIT_CHILD();
}
else // child
{
SQL * new_sql;
close(sql->async_query_pipe[1]); // 쓰기는 필요 없다
sql->async_query_pipe[1] = -1;
new_sql = sql_clone(sql);
clean_server();
if (!new_sql)
exit(1);
TELL_PARENT(getppid());
sql_async_loop(new_sql);
sql_destroy(&new_sql);
exit(1);
}
return 1;
}
void sql_async_loop(SQL * sql)
{
gzFile fp;
int len;
char filename[256], basename[256];
char buf[65535];
char query[1024+1];
int lines = 0;
const char * null;
const char * start;
mkdir("async_query", S_IRWXU);
sprintf(basename, "async_query/%s:%s", sql->addr, sql->dbname);
sprintf(filename, "%s.gz", basename);
fp = gzopen(filename, "w");
if (!fp)
{
fprintf(stderr, "SYSERR: sql_async_loop: gzopen: cannot open %s", filename);
return;
}
while (1)
{
len = read(sql->async_query_pipe[0], buf, 65535);
if (len <= 0) // 부모 프로세스가 종료 했거나 에러면 루프를 탈출 한다.
break;
//fprintf(stderr, "READ: %d ", len);
null = buf;
start = buf;
while (len > 0 && (null = (const char*)memchr(null, '\0', len)))
{
snprintf(query, 1024, "%s", start);
++null;
len -= (null - start);
start = null;
//fprintf(stderr, "LEN: %d ", len);
//sys_log("ASYNC_QUERY: %s;\n", query);
if (sql_query(sql, query) < 0)
sql_error(sql);
if (-1 == gzputs(fp, query))
fprintf(stderr, "SYSERR: gzputs: %s\n", gzerror(fp, NULL));
if (-1 == gzputs(fp, ";\n"))
fprintf(stderr, "SYSERR: gzputs: %s\n", gzerror(fp, NULL));
//gzflush(fp, Z_FINISH);
++lines;
}
}
gzclose(fp);
if (0 == lines)
{
sprintf(filename, "%s.gz", basename);
unlink(filename);
}
else
gzlog_rotate(basename, 9);
}
void sql_destroy(SQL ** r_sql)
{
SQL * sql;
if (!r_sql)
return;
sql = *r_sql;
if (!sql)
return;
if (sql->async_query_pipe[0] != -1)
sql->async_query_pipe[0] = 0;
if (sql->async_query_pipe[1] != -1)
sql->async_query_pipe[1] = 0;
mysql_close(&sql->sql_conn);
*r_sql = NULL;
}
int sql_query(SQL * sql, const char *buf)
{
if (!sql)
return 0;
// fprintf(stderr, "SQL_INFO : P (%x)\n", sql);
// fprintf(stderr, "SQL_INFO : addr (%s)\n", sql->addr);
// fprintf(stderr, "SQL_INFO : user (%s)\n", sql->user);
// fprintf(stderr, "SQL_INFO : query (%s)\n", buf);
// fprintf(stderr, "SQL_INFO : dbname(%s)\n", sql->dbname);
return (mysql_query(&sql->sql_conn, buf));
}
int sql_async_query(SQL * sql, const char *buf)
{
if (!sql)
return 0;
if (sql->async_query_pipe[1] == -1)
return 0;
if (write(sql->async_query_pipe[1], buf, strlen(buf) + 1) < 0)
{
perror("write");
return 0;
}
return 1;
}
MYSQL_RES * sql_result(SQL * sql)
{
return mysql_store_result(&sql->sql_conn);
}
char *sql_string(SQL * sql, char *buf)
{
static char qbuf[4096+256];
int len;
len = strlen(buf);
if (len >= 2048)
{
sys_err("sql_string: query buffer length overflow: %d\n"
" %s", len, buf);
exit(1);
}
mysql_real_escape_string(&sql->sql_conn, qbuf, buf, len);
return (qbuf);
}
int sql_affected_rows(SQL * sql)
{
return mysql_affected_rows(&sql->sql_conn);
}
int sql_num_rows(MYSQL_RES * res)
{
return mysql_num_rows(res);
}
MYSQL_ROW sql_fetch_row(MYSQL_RES * res)
{
return mysql_fetch_row(res);
}
void sql_free_result(MYSQL_RES * res)
{
if (!res)
return;
mysql_free_result(res);
}
void _sql_error(SQL * sql, const char *file, const int line, const char *function)
{
fprintf(stderr, "SQL: %s:%d:%s() | %s\n", file, line, function, mysql_error(&sql->sql_conn));
fflush(stderr);
}
static void gzlog_rotate(const char *basename, int count)
{
char filename[256], filename2[256];
int i;
sprintf(filename, "%s.1.gz", basename);
unlink(filename);
for (i = 2; i <= count; ++i)
{
sprintf(filename2, "%s.%d.gz", basename, i);
rename(filename2, filename);
strcpy(filename, filename2);
}
sprintf(filename, "%s.gz", basename);
rename(filename, filename2);
}
+36
View File
@@ -0,0 +1,36 @@
#ifndef __INC_LIBSQL_H__
#define __INC_LIBSQL_H__
#include <mysql/mysql.h>
typedef struct TSQL
{
MYSQL sql_conn;
char addr[64+1];
char user[64+1];
char password[64+1];
char dbname[64+1];
int async_query_pipe[2];
} SQL;
extern SQL * sql_create(const char *addr, const char *user, const char *password, const char *db_name);
extern void sql_destroy(SQL **);
extern int sql_async_start(SQL *);
extern int sql_query(SQL *, const char *);
extern int sql_async_query(SQL *, const char *);
extern char * sql_string(SQL *, char *);
extern MYSQL_RES * sql_result(SQL *);
extern MYSQL_ROW sql_fetch_row(MYSQL_RES *);
extern void sql_free_result(MYSQL_RES *);
extern int sql_num_rows(MYSQL_RES *);
extern int sql_affected_rows(SQL *);
#define sql_error(sql) _sql_error(sql, __FILE__, __LINE__, __FUNCTION__)
void _sql_error(SQL * sql, const char *file, const int line, const char *function);
extern char char_set[256];
#endif
+292
View File
@@ -0,0 +1,292 @@
#include <sys/types.h>
#include <dirent.h>
#include <stdarg.h>
#include "structs.h"
#include "utils.h"
typedef struct log_file_s* LPLOGFILE;
typedef struct log_file_s LOGFILE;
struct log_file_s
{
char* filename;
FILE* fp;
int last_hour;
int last_day;
};
LPLOGFILE log_file_sys = NULL;
LPLOGFILE log_file_err = NULL;
LPLOGFILE log_file_pt = NULL;
static char log_dir[32] = { 0, };
// Internal functions
LPLOGFILE log_file_init(const char * filename, const char * openmode);
void log_file_destroy(LPLOGFILE logfile);
void log_file_rotate(LPLOGFILE logfile);
void log_file_check(LPLOGFILE logfile);
void log_file_set_dir(const char *dir);
void log_init(void)
{
log_file_set_dir("./log");
log_file_sys = log_file_init("syslog", "a+");
log_file_err = log_file_init("syserr", "a+");
log_file_pt = log_file_init("PTS", "w");
}
void log_destroy(void)
{
log_file_destroy(log_file_sys);
log_file_destroy(log_file_err);
log_file_destroy(log_file_pt);
}
void log_rotate(void)
{
log_file_check(log_file_sys);
log_file_check(log_file_err);
log_file_check(log_file_pt);
log_file_rotate(log_file_sys);
}
void _sys_err(const char *func, int line, const char *format, ...)
{
va_list args;
time_t ct = time(0);
char *time_s = asctime(localtime(&ct));
if (!log_file_err)
return;
time_s[strlen(time_s) - 1] = '\0';
// log_file_err 에 출력
va_start(args, format);
fprintf(log_file_err->fp, "%-15.15s :: %s: ", time_s + 4, func);
vfprintf(log_file_err->fp, format, args);
va_end(args);
fputc('\n', log_file_err->fp);
fflush(log_file_err->fp);
// log_file_sys 에도 출력
va_start(args, format);
fprintf(log_file_sys->fp, "SYSERR: %-15.15s :: %s: ", time_s + 4, func);
vfprintf(log_file_sys->fp, format, args);
va_end(args);
fputc('\n', log_file_sys->fp);
fflush(log_file_sys->fp);
}
static char sys_log_header_string[33] = { 0, };
void sys_log_header(const char *header)
{
strncpy(sys_log_header_string, header, 32);
}
void sys_log(const char *format, ...)
{
va_list args;
if (!log_file_sys)
return;
fprintf(log_file_sys->fp, sys_log_header_string);
va_start(args, format);
vfprintf(log_file_sys->fp, format, args);
va_end(args);
fprintf(log_file_sys->fp, "\n");
fflush(log_file_sys->fp);
}
void pt_log(const char *format, ...)
{
va_list args;
if (!log_file_pt)
return;
va_start(args, format);
vfprintf(log_file_pt->fp, format, args);
va_end(args);
fprintf(log_file_pt->fp, "\n");
fflush(log_file_pt->fp);
}
LPLOGFILE log_file_init(const char* filename, const char * openmode)
{
LPLOGFILE logfile;
FILE* fp;
struct tm curr_tm;
time_t time_s;
time_s = time(0);
curr_tm = *localtime(&time_s);
fp = fopen(filename, openmode);
if (!fp)
return NULL;
logfile = (LPLOGFILE) malloc(sizeof(LOGFILE));
logfile->filename = strdup(filename);
logfile->fp = fp;
logfile->last_hour = curr_tm.tm_hour;
logfile->last_day = curr_tm.tm_mday;
return (logfile);
}
void log_file_destroy(LPLOGFILE logfile)
{
if (logfile->filename)
{
free(logfile->filename);
logfile->filename = NULL;
}
if (logfile->fp)
{
fclose(logfile->fp);
logfile->fp = NULL;
}
free(logfile);
}
void log_file_check(LPLOGFILE logfile)
{
struct stat sb;
// 파일이 없으므로 다시 연다.
if (stat(logfile->filename, &sb) != 0 && errno == ENOENT)
{
fclose(logfile->fp);
logfile->fp = fopen(logfile->filename, "a+");
}
}
void log_file_delete_old(const char *filename)
{
struct stat sb;
struct dirent** namelist;
int n, num1, num2;
char buf[32];
char system_cmd[64];
struct tm new_tm;
stat(filename, &sb);
if (!S_ISDIR(sb.st_mode))
return;
new_tm = *tm_calc(NULL, -3);
n = scandir(filename, &namelist, 0, alphasort);
sprintf(buf, "%04d%02d%02d", new_tm.tm_year + 1900, new_tm.tm_mon + 1, new_tm.tm_mday);
num1 = atoi(buf);
if (n < 0)
perror("scandir");
else
{
while (n-- > 0)
{
if (namelist[n]->d_name[0] == '.')
continue;
if (!isdigit(*namelist[n]->d_name))
continue;
num2 = atoi(namelist[n]->d_name);
if (num2 <= num1)
{
sprintf(system_cmd, "rm -rf %s/%s", filename, namelist[n]->d_name);
system(system_cmd);
sys_log("%s: SYSTEM_CMD: %s", __FUNCTION__, system_cmd);
}
}
}
free(namelist);
}
void log_file_rotate(LPLOGFILE logfile)
{
struct tm curr_tm;
time_t time_s;
char dir[128];
char system_cmd[128];
time_s = time(0);
curr_tm = *localtime(&time_s);
if (curr_tm.tm_mday != logfile->last_day)
{
struct tm new_tm;
new_tm = *tm_calc(&curr_tm, -3);
sprintf(system_cmd, "rm -rf %s/%04d%02d%02d", log_dir, new_tm.tm_year + 1900, new_tm.tm_mon + 1, new_tm.tm_mday);
system(system_cmd);
sys_log("%s: SYSTEM_CMD: %s", __FUNCTION__, system_cmd);
logfile->last_day = curr_tm.tm_mday;
}
if (curr_tm.tm_hour != logfile->last_hour)
{
struct stat stat_buf;
snprintf(dir, 128, "%s/%04d%02d%02d", log_dir, curr_tm.tm_year + 1900, curr_tm.tm_mon + 1, curr_tm.tm_mday);
if (stat(dir, &stat_buf) != 0 || S_ISDIR(stat_buf.st_mode))
mkdir(dir, S_IRWXU);
sys_log("SYSTEM: LOG ROTATE (%04d-%02d-%02d %d)",
curr_tm.tm_year + 1900, curr_tm.tm_mon + 1, curr_tm.tm_mday, logfile->last_hour);
// 로그 파일을 닫고
fclose(logfile->fp);
// 옮긴다.
snprintf(system_cmd, 128, "mv %s %s/%s.%02d", logfile->filename, dir, logfile->filename, logfile->last_hour);
system(system_cmd);
// 마지막 저장시간 저장
logfile->last_hour = curr_tm.tm_hour;
// 로그 파일을 다시 연다.
logfile->fp = fopen(logfile->filename, "a+");
}
}
void log_file_set_dir(const char *dir)
{
strcpy(log_dir, dir);
log_file_delete_old(log_dir);
}
+14
View File
@@ -0,0 +1,14 @@
#ifndef _LOG_H_
#define _LOG_H_
extern void log_init(void);
extern void log_destroy(void);
extern void log_rotate(void);
#define sys_err(fmt, args...) _sys_err(__FUNCTION__, __LINE__, fmt, ##args)
extern void _sys_err(const char *func, int line, const char *format, ...);
extern void sys_log_header(const char *header);
extern void sys_log(const char *format, ...);
extern void pt_log(const char *format, ...);
#endif // _LOG_H_
+38
View File
@@ -0,0 +1,38 @@
/*
* Filename: macros.h
* Description: 각종 매크로들이 정의되어 있는 헤더. structs.h 에서 include 함.
*
* Author: 비엽 (server), myevan (Client)
*/
#ifndef _MACROS_H_
#define _MACROS_H_
/*
* 디스크립터 관련 매크로
*/
#define STATE(d) ((d)->state)
#define GET_ID(conn) ((conn)->account_id)
#define GET_LOGIN(conn) ((conn)->login)
#define GET_TEENAGE(conn) ((conn)->teenage)
#define GET_ON_TIME(conn) ((conn)->on_time)
#define GET_OFF_TIME(conn) ((conn)->off_time)
#define GET_DESC(conn) ((conn)->desc)
#define GET_NOTICE_STEP(conn) ((conn)->notice_step)
#define GET_NOTICE_PULSE(conn) ((conn)->notice_pulse)
#define GET_EVENT(conn) ((conn)->event)
#define HOUR_TO_SEC(x) ((x)*60*60)
#define SEC_TO_HOUR(x) ((x)/(60*60))
#define MINUTE_TO_SEC(x) ((x)*60)
#define SEC_TO_MINUTE(x) ((x)/60)
#define SEC_TO_PULSE(sec) ((sec) * PASSES_PER_SEC)
#define MINUTE_TO_PULSE(min) SEC_TO_PULSE((min)*60)
#define HOUR_TO_PULSE(hour) MINUTE_TO_PULSE((hour)*60)
#endif // _MACROS_H_
+428
View File
@@ -0,0 +1,428 @@
#include "structs.h"
#include "utils.h"
#include "socket.h"
#include "config.h"
#include "log.h"
#include "sql.h"
// 게임과 연결되는 소켓
socket_t mother_desc = 0;
int shutdowned = FALSE;
int tics = 0;
int global_pulse = 0;
int process_input(DESC_DATA * d);
int process_output(DESC_DATA * d);
void process_command(void);
WORD input_desc_remain = 0;
int input_bytes_remain = 0;
struct timeval null_time;
void server_loop(void);
void signal_setup(void);
void insert_all(void);
void heartbeat(int pulse);
struct data_q input_q;
void pid_init(void)
{
FILE *fp;
if ((fp = fopen("pid", "w")))
{
fprintf(fp, "%d", getpid());
fclose(fp);
}
else
{
sys_log("SYSERR: main(): could not open file for writing. (filename: ./pid)");
exit(1);
}
}
void pid_deinit(void)
{
remove("./pid");
}
void clean_server()
{
DESC_DATA *d, *next_d;
for (d = descriptor_list; d; d = next_d)
{
next_d = d->next;
socket_close(d);
}
if (mother_desc)
CLOSE_SOCKET(mother_desc);
}
void shutdown_server()
{
clean_server();
event_destroy();
sql_deinit();
pid_deinit();
sys_log("Server has been shutdowned.");
log_destroy();
}
void heartbeat(int pulse)
{
event_process();
// 1 초에 한번
if (!(pulse%PASSES_PER_SEC))
{
// 5초에 한번
if (!(pulse%(PASSES_PER_SEC*5)))
log_rotate();
}
}
int main(int argc, char **argv)
{
input_q.count = 0;
log_init();
init_config();
mother_desc = socket_init(mother_port);
pid_init();
signal_setup();
if (!sql_init())
return (-1);
event_init();
server_loop();
shutdown_server();
return 1;
}
void server_loop(void)
{
struct timeval opt_time, now, last_time, timeout, before_sleep, process_time;
fd_set input_set, output_set, exc_set, null_set;
register DESC_DATA *d, *next_d;
int missed_pulses, maxdesc = 0;
null_time.tv_sec = 0;
null_time.tv_usec = 0;
opt_time.tv_usec = OPT_USEC;
opt_time.tv_sec = 0;
gettimeofday(&last_time, (struct timezone *) 0);
gettimeofday(&before_sleep, (struct timezone *) 0);
last_time = *timeadd(&last_time, &opt_time);
FD_ZERO(&null_set);
while (!shutdowned)
{
if (descriptor_list == NULL)
{
sys_log("SYSTEM: No connections online. Entering sleep mode.");
FD_ZERO(&input_set);
FD_SET(mother_desc, &input_set);
if (select(mother_desc + 1, &input_set, (fd_set *) 0, (fd_set *) 0, NULL) < 0)
{
if (errno == EINTR)
sys_log("SYSTEM: Woke up by signal");
else
perror("select coma");
}
else
sys_log("SYSTEM: Woke up by new connection.");
gettimeofday(&last_time, (struct timezone *) 0);
last_time = *timeadd(&last_time, &opt_time);
gettimeofday(&before_sleep, (struct timezone *) 0);
}
FD_ZERO(&input_set);
FD_ZERO(&output_set);
FD_ZERO(&exc_set);
FD_SET(mother_desc, &input_set);
maxdesc = mother_desc;
for (d = descriptor_list; d; d = next_d)
{
next_d = d->next;
if (d->descriptor > maxdesc)
maxdesc = d->descriptor;
FD_SET(d->descriptor, &input_set);
FD_SET(d->descriptor, &output_set);
FD_SET(d->descriptor, &exc_set);
}
// 새로운 프레임 스킵/보완 코드 (이게 더 좋다는 것은 아닐 수도 있다. -_-)
gettimeofday(&now, (struct timezone *) 0);
process_time = *timediff(&now, &before_sleep);
before_sleep = *timeadd(&now, timediff(&opt_time, &process_time));
timeout = *timediff(&last_time, &now);
last_time = *timeadd(&last_time, &opt_time);
if (process_time.tv_sec == 0 && process_time.tv_usec < OPT_USEC)
missed_pulses = 0;
else
{
missed_pulses = process_time.tv_sec * PASSES_PER_SEC;
missed_pulses += process_time.tv_usec / OPT_USEC;
process_time.tv_sec = 0;
process_time.tv_usec = process_time.tv_usec % OPT_USEC;
}
if (select(0, (fd_set *) 0, (fd_set *) 0, (fd_set *) 0, &timeout) < 0)
{
if (errno != EINTR)
{
perror("Select sleep");
exit(1);
}
}
if (select(maxdesc + 1, &input_set, &output_set, &exc_set, &null_time) < 0)
{
perror("select() poll");
sys_log("SELECT POLL MAXDESC: %d", maxdesc);
for (d = descriptor_list; d; d = next_d)
{
next_d = d->next;
socket_close(d);
}
CLOSE_SOCKET(mother_desc);
exit(1);
}
// 게임 소켓으로 부터 접속을 받는다
if (FD_ISSET(mother_desc, &input_set))
new_descriptor(mother_desc);
for (d = descriptor_list; d; d = next_d)
{
next_d = d->next;
if (FD_ISSET(d->descriptor, &exc_set) || STATE(d) == STATE_CLOSE)
{
FD_CLR(d->descriptor, &input_set);
FD_CLR(d->descriptor, &output_set);
socket_close(d);
}
}
// 소켓에서 받기
for (d = descriptor_list; d; d = next_d)
{
next_d = d->next;
if (FD_ISSET(d->descriptor, &input_set))
if (process_input(d) < 0)
socket_close(d);
}
process_command();
// 소켓으로 보내기 처리
for (d = descriptor_list; d; d = next_d)
{
next_d = d->next;
if (FD_ISSET(d->descriptor, &output_set))
if (process_output(d) < 0)
socket_close(d);
}
missed_pulses++;
if (missed_pulses <= 0)
{
sys_err("missed_pulses 변수가 양수가 아닙니다!! (%d)", missed_pulses);
missed_pulses = 1;
}
if (missed_pulses > (30 * PASSES_PER_SEC))
{
sys_err("%d 초의 펄스를 잃었습니다. (서버에 랙이 발생)", missed_pulses / PASSES_PER_SEC);
missed_pulses = 30 * PASSES_PER_SEC;
}
while (missed_pulses--)
heartbeat(++global_pulse);
tics++;
}
}
int process_input(DESC_DATA * t)
{
char inbuf[MAX_INPUT_LEN];
ssize_t bytes_read;
bytes_read = perform_socket_read(t->descriptor, inbuf, MAX_INPUT_LEN);
if (bytes_read < 0)
return -1;
else if (bytes_read == 0)
return 0;
// sys_log("DESC #%d receive %d bytes", t->desc_num, bytes_read);
write_to_q(inbuf, &input_q, bytes_read, t->desc_num);
return 1;
}
void process_command(void)
{
static char inbuf[131072];
DESC_DATA *t, *next_t;
WORD desc_num;
char *buf;
int bytes, bytes_proceed;
buf = &inbuf[0];
if (input_bytes_remain > 0)
{
bytes = fetch_from_q(&input_q, buf + input_bytes_remain, input_desc_remain);
if (bytes == 0)
return;
bytes += input_bytes_remain;
for (t = descriptor_list; t; t = next_t)
{
next_t = t->next;
if (t->desc_num == input_desc_remain)
{
if (t->input_processor)
{
bytes_proceed = ((*t->input_processor) (t, buf, bytes));
if (bytes_proceed >= bytes)
{
input_bytes_remain = 0;
input_desc_remain = 0;
break;
}
else
{
if (bytes_proceed > 0)
memcpy(buf, buf + bytes_proceed, bytes - bytes_proceed);
input_bytes_remain = bytes - bytes_proceed;
sys_log("Transaction unfinished %d, DESC %d, step 2", input_bytes_remain, input_desc_remain);
// input_desc_remain = input_desc_remain; // -_-;
break;
}
}
}
}
if (!t)
{
input_bytes_remain = 0;
input_desc_remain = 0;
}
if (input_bytes_remain != 0)
return;
}
if ((bytes = get_from_q(&input_q, buf, &desc_num)) != 0)
{
for (t = descriptor_list; t; t = next_t)
{
next_t = t->next;
if (t->desc_num == desc_num)
{
if (t->input_processor)
{
bytes_proceed = ((*t->input_processor) (t, buf, bytes));
if (bytes_proceed >= bytes)
{
input_bytes_remain = 0;
input_desc_remain = 0;
break;
}
else
{
if (bytes_proceed > 0)
memcpy(buf, buf + bytes_proceed, bytes - bytes_proceed);
input_bytes_remain = bytes - bytes_proceed;
input_desc_remain = desc_num;
sys_log("Transaction Unfinished %d, DESC %d, step 1", input_bytes_remain, input_desc_remain);
break;
}
}
}
}
if (!t)
{
input_bytes_remain = 0;
input_desc_remain = 0;
}
}
else
return;
}
int process_output(DESC_DATA * d)
{
int result;
if (d->packet_buffer.length == 0)
return 0;
result = write_to_descriptor(d->descriptor, d->packet_buffer.data, d->packet_buffer.length);
d->packet_buffer.length = 0;
return (result);
}
+196
View File
@@ -0,0 +1,196 @@
/*
* Filename: queue.c
* Description: 큐 처리
*
* Author: 김한주 (aka. 비엽, Cronan), 송영진 (aka. myevan, 빗자루)
*/
#include "structs.h"
#include "utils.h"
#include "priority_queue.h"
extern int global_pulse;
/* 큐를 초기화 한다 */
PRIORITY_QUEUE *queue_init(void)
{/*{{{*/
PRIORITY_QUEUE *q;
CREATE(q, PRIORITY_QUEUE, 1);
return (q);
}
/*}}}*/
/* 큐를 enqueue 한다. */
PRIORITY_Q_ELEMENT *queue_enq(PRIORITY_QUEUE *q, void *data, int key)
{/*{{{*/
PRIORITY_Q_ELEMENT *qe, *i;
int bucket;
/* fast hasing */
bucket = key % NUM_PRIORITY_QUEUES;
CREATE(qe, PRIORITY_Q_ELEMENT, 1);
qe->data = data;
qe->key = key;
qe->prev = NULL;
qe->next = NULL;
if (!q->head[bucket])
{
// 큐가 비었다.
q->head[bucket] = qe;
q->tail[bucket] = qe;
}
else
{
for (i = q->tail[bucket]; i; i = i->prev)
{
if (i->key < key)
{
// 넣을 곳을 찾았다.
if (i == q->tail[bucket])
q->tail[bucket] = qe;
else
{
qe->next = i->next;
i->next->prev = qe;
}
qe->prev = i;
i->next = qe;
break;
}
}
if (i == NULL)
{
// 넣을 곳이 리스트의 처음 이다.
qe->next = q->head[bucket];
q->head[bucket] = qe;
qe->next->prev = qe;
}
}
return (qe);
}/*}}}*/
/* 큐를 dequeue 한다. */
void queue_deq(PRIORITY_QUEUE *q, PRIORITY_Q_ELEMENT *qe)
{/*{{{*/
int i;
if (qe == NULL)
{
//core_dump();
return;
}
i = qe->key % NUM_PRIORITY_QUEUES;
if (qe->prev == NULL)
q->head[i] = qe->next;
else
qe->prev->next = qe->next;
if (qe->next == NULL)
q->tail[i] = qe->prev;
else
qe->next->prev = qe->prev;
free(qe);
}
/*}}}*/
PRIORITY_Q_ELEMENT *queue_reque(PRIORITY_QUEUE *q, PRIORITY_Q_ELEMENT *qe, int new_key)
{/*{{{*/
void *data;
data = qe->data;
queue_deq(q, qe);
return (queue_enq(q, data, new_key));
}
/*}}}*/
/*
* 큐의 헤드를 dequeue 후 리턴한다.
*/
void *queue_head(PRIORITY_QUEUE *q)
{/*{{{*/
void *data;
int i;
i = (global_pulse % NUM_PRIORITY_QUEUES);
if (!q->head[i])
return (NULL);
data = q->head[i]->data;
queue_deq(q, q->head[i]);
return (data);
}
/*}}}*/
/*
* 숫자가 제일 작은 (큐의 헤드) key 를 리턴한다.
* 큐가 NULL 일 경우 unsinged number 의 최고수를 리턴한다.
*/
int queue_key(PRIORITY_QUEUE *q)
{/*{{{*/
int i;
i = global_pulse % NUM_PRIORITY_QUEUES;
if (q->head[i])
return q->head[i]->key;
else
return LONG_MAX;
}
/*}}}*/
/* key 를 리턴한다. */
int queue_elmt_key(PRIORITY_Q_ELEMENT *qe)
{/*{{{*/
return qe->key;
}
/*}}}*/
/* 큐의 갯수를 리턴한다. */
int queue_count(PRIORITY_QUEUE *q)
{/*{{{*/
int i, count = 0;
PRIORITY_Q_ELEMENT *qe, *next_qe;
for (i = 0; i < NUM_PRIORITY_QUEUES; i++)
{
for (qe = q->head[i]; qe; qe = next_qe)
{
next_qe = qe->next;
count++;
}
}
return (count);
}
/*}}}*/
/* 큐를 free 한다. */
void queue_free(PRIORITY_QUEUE *q)
{/*{{{*/
int i;
PRIORITY_Q_ELEMENT *qe, *next_qe;
for (i = 0; i < NUM_PRIORITY_QUEUES; i++)
{
for (qe = q->head[i]; qe; qe = next_qe)
{
next_qe = qe->next;
free(qe);
}
}
free(q);
}/*}}}*/
+31
View File
@@ -0,0 +1,31 @@
#ifndef __QUEUE_H__
#define __QUEUE_H__
/* number of priority queues to use (reduces enqueue cost) */
#define NUM_PRIORITY_QUEUES 509
typedef struct priority_queue
{
struct priority_q_element *head[NUM_PRIORITY_QUEUES];
struct priority_q_element *tail[NUM_PRIORITY_QUEUES];
} PRIORITY_QUEUE;
typedef struct priority_q_element
{
struct priority_q_element* prev, *next;
void* data;
int key;
} PRIORITY_Q_ELEMENT;
/* function protos need by other modules */
PRIORITY_QUEUE* queue_init(void);
PRIORITY_Q_ELEMENT* queue_enq(PRIORITY_QUEUE* q, void* data, int key);
void queue_deq(PRIORITY_QUEUE* q, PRIORITY_Q_ELEMENT* qe);
PRIORITY_Q_ELEMENT* queue_reque(PRIORITY_QUEUE* q, PRIORITY_Q_ELEMENT* qe, int new_key);
void* queue_head(PRIORITY_QUEUE* q);
int queue_key(PRIORITY_QUEUE* q);
int queue_elmt_key(PRIORITY_Q_ELEMENT* qe);
void queue_free(PRIORITY_QUEUE* q);
int queue_count(PRIORITY_QUEUE* q);
#endif // __QUEUE_H__
+28
View File
@@ -0,0 +1,28 @@
#ifndef __PROTOCOL_H__
#define __PROTOCOL_H__
//#define RECV_LOGIN 0x10
//#define RECV_LOGOUT 0x11
//
//#define SEND_TEEN_NOTICE 0x12
//#define SEND_FORCE_LOGOUT 0x13
//#define SEND_LOGIN_NOTICE 0x14
inline BYTE decode_byte(const BYTE *a)
{
return (*a);
}
inline WORD decode_2bytes(const BYTE *a)
{
return (*((WORD *) a));
}
inline INT decode_4bytes(const BYTE *a)
{
return (*((INT *) a));
}
#endif
+71
View File
@@ -0,0 +1,71 @@
/*
* Filename: signal.c
* Description: ½Ã±×³Î °ü·Ã ÇÔ¼ö.
*
* Author: ºñ¿± (Server), myevan (Client)
*/
#include <signal.h>
#include <sys/wait.h>
#include "structs.h"
#include "socket.h"
#include "utils.h"
#include "log.h"
#define RETSIGTYPE void
#define my_signal signal
extern int shutdowned;
extern int tics;
pid_t waitpid(pid_t pid, int *status, int options);
RETSIGTYPE reap(int sig)
{
while (waitpid(-1, NULL, WNOHANG) > 0);
my_signal(SIGCHLD, reap);
}
RETSIGTYPE checkpointing(int sig)
{
if (!tics)
{
sys_log("SYSERR: CHECKPOINT shutdown: tics did not updated.");
abort();
} else
tics = 0;
}
RETSIGTYPE hupsig(int sig)
{
shutdowned = TRUE;
sys_log("SYSERR: SIGHUP, SIGINT, SIGTERM signal has been received. shutting down.");
}
void signal_setup(void)
{
struct itimerval itime;
struct timeval interval;
interval.tv_sec = 60;
interval.tv_usec = 0;
itime.it_interval = interval;
itime.it_value = interval;
setitimer(ITIMER_VIRTUAL, &itime, NULL);
my_signal(SIGVTALRM, checkpointing);
/* just to be on the safe side: */
my_signal(SIGHUP, hupsig);
my_signal(SIGCHLD, reap);
my_signal(SIGINT, hupsig);
my_signal(SIGTERM, hupsig);
my_signal(SIGPIPE, SIG_IGN);
my_signal(SIGALRM, SIG_IGN);
}
+677
View File
@@ -0,0 +1,677 @@
/*
* Filename: socket.c
* Description: 소켓 관련 소스. 입력 큐 관련 루틴.
*
* Author: 비엽 (Server), myevan (Client)
*/
#include "structs.h"
#include "utils.h"
#include "db.h"
#include "memory.h"
#include "socket.h"
#include "input.h"
// #include "hash.h"
#include "log.h"
DESC_DATA * descriptor_list;
/* internal function define */
void socket_lingeroff(socket_t s);
void socket_sndbuf(socket_t s, unsigned int opt);
void socket_rcvbuf(socket_t s, unsigned int opt);
void socket_timeout(socket_t s, long sec, long usec);
void socket_reuse(socket_t s);
void conn_delete_by_desc(DESC_DATA *d);
extern int input_desc_remain;
extern int input_bytes_remain;
static struct data_block * queue_poll = NULL;
void packet_init(PACKET_DATA *buffer)
{
CREATE(buffer->data, char, DEFAULT_PACKET_BUFFER_SIZE);
buffer->length = 0;
buffer->max_length = DEFAULT_PACKET_BUFFER_SIZE;
}
void packet_free(PACKET_DATA *buffer)
{
free(buffer->data);
}
void packet(PACKET_DATA *buffer, const void *data, int length)
{
// 버퍼가 모자르면.. -_-;
if ((buffer->length + length) > buffer->max_length)
{
buffer->max_length *= 2;
if (!(buffer->data = (char*)realloc(buffer->data, buffer->max_length)))
{
perror("realloc failure");
abort();
}
sys_log("SYSTEM: Reallocating memory to MAX %d, Current length %d encoding %d",
buffer->max_length, buffer->length, length);
}
memcpy(&buffer->data[buffer->length], data, length);
buffer->length += length;
}
const char *encode_byte(char ind)
{
static char a[1];
*((char *) a) = ind;
return (a);
}
const char *encode_2bytes(sh_int ind)
{
static char a[2];
*((sh_int *) a) = ind;
return (a);
}
const char *encode_4bytes(int ind)
{
static char a[4];
*((int *) a) = ind;
return (a);
}
ssize_t perform_socket_read(socket_t desc, char *read_point, size_t space_left)
{
ssize_t ret;
ret = recv(desc, read_point, space_left, 0);
if (ret > 0)
return ret;
return -1;
}
int socket_write_tcp(socket_t desc, const char *txt, int length)
{
int bytes_written = send(desc, txt, length, 0);
// 성공
if (bytes_written > 0)
return (bytes_written);
if (bytes_written == 0)
return -1;
#ifdef EAGAIN /* POSIX */
if (errno == EAGAIN)
return 0;
#endif
#ifdef EWOULDBLOCK /* BSD */
if (errno == EWOULDBLOCK)
return 0;
#endif
#ifdef EDEADLK /* Macintosh */
if (errno == EDEADLK)
return 0;
#endif
/* Looks like the error was fatal. Too bad. */
return -1;
}
int write_to_descriptor(socket_t desc, const char *data, size_t length)
{
size_t total;
ssize_t bytes_written;
total = length;
do
{
if ((bytes_written = socket_write_tcp(desc, data, total)) < 0)
{
#ifdef EWOULDBLOCK
if (errno == EWOULDBLOCK)
errno = EAGAIN;
#endif
if (errno == EAGAIN)
sys_log("SYSERR: socket write would block, about to close!");
else
sys_log("SYSERR: write to descriptor error"); // '보통' 상대편으로 부터 접속이 끊긴 것이다.
return -1;
}
else
{
data += bytes_written;
total -= bytes_written;
}
}
while (total > 0);
return 0;
}
int socket_init(int port)
{
int s;
struct sockaddr_in sa;
if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket");
exit(1);
}
socket_reuse(s);
socket_lingeroff(s);
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
sa.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(s, (struct sockaddr *) &sa, sizeof(sa)) < 0)
{
perror("bind");
exit(1);
}
sys_log("SYSTEM: BINDING PORT [%d]", port);
socket_nonblock(s);
listen(s, SOMAXCONN);
return s;
}
void socket_close(DESC_DATA *d)
{
packet_free(&d->packet_buffer);
CLOSE_SOCKET(d->descriptor);
REMOVE_FROM_TW_LIST(d, descriptor_list, prev, next);
if (d->desc_num == input_desc_remain)
{
input_desc_remain = 0;
input_bytes_remain = 0;
}
conn_delete_by_desc(d);
sys_log("SYSTEM: closing socket. DESC #%d", d->descriptor);
free(d);
}
socket_t socket_accept(socket_t s, struct sockaddr_in *peer)
{
socket_t desc;
size_t i;
i = sizeof(*peer);
if ((desc = accept(s, (struct sockaddr *) peer, &i)) == -1)
{
sys_log("accept");
return -1;
}
if (desc >= 65500)
{
sys_log("SYSERR: SOCKET FD 65500 LIMIT! %d", desc);
CLOSE_SOCKET(desc);
return -1;
}
socket_sndbuf(desc, 233016);
socket_rcvbuf(desc, 233016);
socket_timeout(desc, 15, 0);
socket_lingeroff(desc);
return (desc);
}
#ifndef O_NONBLOCK
#define O_NONBLOCK O_NDELAY
#endif
void socket_nonblock(socket_t s)
{
int flags;
flags = fcntl(s, F_GETFL, 0);
flags |= O_NONBLOCK;
if (fcntl(s, F_SETFL, flags) < 0)
{
perror("SYSERR: Fatal error executing nonblock (comm.c)");
exit(1);
}
}
void socket_dontroute(socket_t s)
{
int set;
if (setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (const void *) &set, sizeof(int)) < 0)
{
perror("SYSERR: Fatal error executing setsockopt()");
exit(1);
}
}
void socket_lingeroff(socket_t s)
{
struct linger linger;
linger.l_onoff = 0;
linger.l_linger = 0;
if (setsockopt(s, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger)) < 0)
{
perror("setsockopt: LINGER");
CLOSE_SOCKET(s);
exit(1);
}
}
void socket_rcvbuf(socket_t s, unsigned int opt)
{
size_t optlen;
optlen = sizeof(opt);
if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, (const unsigned int *) &opt, optlen) < 0)
{
perror("setsockopt: rcvbuf");
close(s);
exit(1);
}
opt = 0;
optlen = sizeof(opt);
if (getsockopt(s, SOL_SOCKET, SO_RCVBUF, (unsigned int *) &opt, &optlen) < 0)
{
perror("getsockopt: rcvbuf");
close(s);
exit(1);
}
sys_log("SYSTEM: %d: receive buffer changed to %d", s, opt);
}
void socket_sndbuf(socket_t s, unsigned int opt)
{
size_t optlen;
optlen = sizeof(opt);
if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, (const unsigned int *) &opt, optlen) < 0)
{
perror("setsockopt: sndbuf");
exit(1);
}
opt = 0;
optlen = sizeof(opt);
if (getsockopt(s, SOL_SOCKET, SO_SNDBUF, (unsigned int *) &opt, &optlen) < 0)
{
perror("getsockopt: sndbuf");
exit(1);
}
sys_log("SYSTEM: %d: send buffer changed to %d", s, opt);
}
// sec : seconds, usec : microseconds
void socket_timeout(socket_t s, long sec, long usec)
{
struct timeval rcvopt;
struct timeval sndopt;
size_t optlen = sizeof(rcvopt);
rcvopt.tv_sec = sndopt.tv_sec = sec;
rcvopt.tv_usec = sndopt.tv_usec = usec;
if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &rcvopt, optlen) < 0)
{
perror("setsockopt: timeout");
close(s);
exit(1);
}
if (getsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &rcvopt, &optlen) < 0)
{
perror("setsockopt: timeout");
close(s);
exit(1);
}
optlen = sizeof(sndopt);
if (setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &sndopt, optlen) < 0)
{
perror("setsockopt: timeout");
close(s);
exit(1);
}
if (getsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &sndopt, &optlen) < 0)
{
perror("setsockopt: timeout");
close(s);
exit(1);
}
sys_log("SYSTEM: %d: TIMEOUT RCV: %d.%d, SND: %d.%d", s, rcvopt.tv_sec, rcvopt.tv_usec, sndopt.tv_sec, sndopt.tv_usec);
}
void socket_reuse(socket_t s)
{
int opt = 1;
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0)
{
perror("setsockopt: reuse");
close(s);
exit(1);
}
}
void flush_queues(struct data_q *queue)
{
char buf[MAX_INPUT_LEN];
WORD tmp;
while (get_from_q(queue, buf, &tmp));
}
int fetch_from_q(struct data_q *dest, char *data, WORD id)
{
struct data_block *tblock;
struct data_block *prev = NULL;
int bytes;
if (!dest->head)
return 0;
for (tblock = dest->head; tblock; tblock = tblock->next)
{
if (tblock->id == id)
{
bytes = tblock->bytes;
memcpy(data, tblock->data, bytes);
// 이전 데이터가 없으면 리스트의 head 이다.
if (!prev)
{
// tblock 이 head 이자 tail 이면 리스트에 아무 것도 없는 것이다.
if (tblock == dest->tail)
dest->head = dest->tail = NULL;
// tail 이 아니면 head 를 tblock 의 next 멤버로 만든다.
else
dest->head = tblock->next;
}
// 이전 데이터가 있으면 리스트의 중간이다.
else
{
// 이전 데이터의 다음을 tblock 의 다음으로 만든다.
prev->next = tblock->next;
// 만약 tblock (fetch 할 데이터) 이 tail 이라면
if (tblock == dest->tail)
{
// tail 이므로 next 가 없을 것이다. 그러므로 이전 리스트가 tail 로 된다.
dest->tail = prev;
}
}
// free 하지 않고 리스트에 넣는다.
tblock->next = queue_poll;
queue_poll = tblock;
dest->count--;
return (bytes);
}
prev = tblock;
}
return 0;
}
int get_from_q(struct data_q *dest, char *str, WORD *id)
{
struct data_block *new_block;
int bytes;
if (!dest->head)
return 0;
new_block = dest->head;
bytes = dest->head->bytes;
*id = dest->head->id;
memcpy(str, dest->head->data, bytes);
dest->head = dest->head->next;
// free 하지 않고 리스트에 넣는다.
new_block->next = queue_poll;
queue_poll = new_block;
// free(new_block->data);
// free(new_block);
dest->count--;
return (bytes);
}
void write_to_q(char *data, struct data_q *dest, int bytes, WORD id)
{
struct data_block *new_block;
// queue poll 이 있다면,
if (queue_poll)
{
new_block = queue_poll;
queue_poll = queue_poll->next;
}
else
CREATE(new_block, struct data_block, 1);
if (new_block->memory_bytes < bytes)
{
if (new_block->memory_bytes == 0)
CREATE(new_block->data, char, bytes);
else
new_block->data = (char*)realloc(new_block->data, bytes);
// memory_bytes 는 메모리 상의 진짜 데이터 이다.
new_block->memory_bytes = bytes;
}
memcpy(new_block->data, data, bytes);
new_block->bytes = bytes;
new_block->id = id;
if (!dest->head)
{
new_block->next = NULL;
dest->head = dest->tail = new_block;
}
else
{
dest->tail->next = new_block;
dest->tail = new_block;
new_block->next = NULL;
}
dest->count++;
}
int valid_host(const char *host)
{
return 1;
static struct valid_ip
{
const char* ip;
BYTE network;
BYTE mask;
} valid_ip_info[] = {
{ "10.0.0", 0, 0 },
{ "10.10.0", 0, 0 },
{ "10.10.100", 0, 0 },
{ "172.20.0", 0, 0 },
{ "192.168.10", 0, 0 },
{ "192.168.1", 0, 0 },
{ "127.0.0", 1, 255 },
{ "210.123.10", 128, 128 },
{ "210.181.251", 112, 240 },
{ "211.93.159", 90, 240 },
{ "211.91.13", 244, 248 },
{ "61.153.3", 192, 192 },
{ "210.51.9", 131, 248 },
{ "210.38.2", 20, 248 },
{ "218.104.201", 106, 255 },
{ "218.104.201", 107, 255 },
{ "218.104.201", 108, 255 },
{ "61.151.251", 69, 251 },
{ "211.100.19", 64, 128 },
{ "61.156.17", 201, 251 },
{ "61.240.232", 17, 251 },
{ "218.30.22", 115, 251 },
{ "202.102.249", 161, 164 },
{ "218.11.243", 227, 237 },
{ "220.95.239", 121, 125 },
{ "61.55.137", 0, 0 }, // cibn cnc1
{ "61.180.228", 0, 0 }, // cibn cnc2
{ "218.7.219", 0, 0 }, // cibn cnc3
{ "121.11.87", 0, 0 }, // cibn te1
{ "222.221.3", 0, 0 }, // cibn te2
{ "61.147.119", 0, 0 }, // cibn te3
{ "222.221.3", 0, 0 }, // cibn te4
{ "218.99.6", 0, 0 }, // cibn te5
{ "218.25.92", 0, 0 }, // cibn te6
{ "\n", 0, 0 },
};
int i, j;
char ip_addr[256];
for (i = 0; *valid_ip_info[i].ip != '\n'; i++)
{
j = 255 - valid_ip_info[i].mask;
do
{
sprintf(ip_addr, "%s.%d", valid_ip_info[i].ip, valid_ip_info[i].network + j);
if (!strcmp(host, ip_addr))
return TRUE;
if (!j)
break;
}
while (j--);
}
return FALSE;
}
void init_descriptor(DESC_DATA *newd, socket_t desc, char *host)
{
static WORD desc_numbers = 0;
packet_init(&newd->packet_buffer);
strncpy(newd->host, host, MAX_HOST_LENGTH);
*(newd->host + MAX_HOST_LENGTH) = '\0';
newd->descriptor = desc;
assign_state(newd, STATE_HANDSHAKE);
if (++desc_numbers >= 65535)
desc_numbers = 1;
newd->desc_num = desc_numbers;
newd->handshake = random() % (1024 * 1024);
sys_log("SYSTEM: new connection from [%s]", newd->host);
}
int new_descriptor(int s)
{
socket_t desc;
int sockets_connected = 0;
DESC_DATA *newd;
static struct sockaddr_in peer;
if ((desc = socket_accept(s, &peer)) == -1)
return -1;
for (newd = descriptor_list; newd; newd = newd->next)
sockets_connected++;
if (sockets_connected >= MAX_ALLOW_USER)
{
CLOSE_SOCKET(desc);
return 0;
}
if (!valid_host(inet_ntoa(peer.sin_addr)))
{
sys_log("\007\007NOT A VALID SITE [%s]", inet_ntoa(peer.sin_addr));
CLOSE_SOCKET(desc);
return 0;
}
CREATE(newd, DESC_DATA, 1);
init_descriptor(newd, desc, inet_ntoa(peer.sin_addr));
/* 리스트에 추가 */
INSERT_TO_TW_LIST(newd, descriptor_list, prev, next);
packet(&newd->packet_buffer, encode_4bytes(newd->handshake ^ HANDSHAKE_XOR), 4);
return 0;
}
void assign_state(DESC_DATA * d, int state)
{
switch (state)
{
case STATE_CLOSE:
d->input_processor = NULL;
break;
case STATE_HANDSHAKE:
d->input_processor = input_handshake;
break;
case STATE_MAIN:
d->input_processor = input_main;
break;
}
d->state = state;
}
+42
View File
@@ -0,0 +1,42 @@
/*
* Filename: socket.c
* Description: ¼ÒÄÏ °ü·Ã ÇÔ¼ö Çì´õ.
*
* Author: ºñ¿± (server), myevan (Client)
*/
#ifndef _SOCKET_H_
#define _SOCKET_H_
#define PORT_NUM 54300
#define MAX_ALLOW_USER 2024
extern DESC_DATA *descriptor_list;
void packet_init(PACKET_DATA *buffer);
void packet_free(PACKET_DATA *buffer);
void packet(PACKET_DATA *buffer, const void *data, int length);
void assign_state(DESC_DATA * d, int state);
void init_descriptor(DESC_DATA *newd, socket_t desc, char *host);
int new_descriptor(int s);
ssize_t perform_socket_read(socket_t desc, char *read_point, size_t space_left);
int write_to_descriptor(socket_t desc, const char *data, size_t length);
int socket_init(int port);
socket_t socket_accept(socket_t s, struct sockaddr_in *peer);
void socket_close(DESC_DATA *d);
void socket_nonblock(socket_t s);
void socket_dontroute(socket_t s);
void socket_lingeroff(socket_t s);
void flush_queues(struct data_q *queue);
int fetch_from_q(struct data_q *dest, char *str, WORD id);
int get_from_q(struct data_q *dest, char *str, WORD *id);
void write_to_q(char *str, struct data_q *dest, int bytes, WORD id);
const char *encode_byte(char ind);
const char *encode_2bytes(sh_int ind);
const char *encode_4bytes(int ind);
#endif // _SOCKET_H_
+47
View File
@@ -0,0 +1,47 @@
#include "structs.h"
#include "utils.h"
#include "socket.h"
#include "config.h"
#include "sql.h"
#include "log.h"
SQL * sql_account = NULL;
char query_buf[MAX_QUERY_LENGTH+1] = { 0, };
int sql_init()
{
sql_account = sql_create(sql_addr, sql_user, sql_password, sql_db_name);
if (!sql_account)
{
sys_err("cannot create sql_account");
return 0;
}
if (!sql_async_start(sql_account))
{
sql_deinit();
return 0;
}
return 1;
}
void sql_deinit()
{
sql_destroy(&sql_account);
}
int sql_account_query(const char *buf)
{
return sql_query(sql_account, buf);
}
void sql_ping()
{
if (sql_account)
mysql_ping(&sql_account->sql_conn);
}
+25
View File
@@ -0,0 +1,25 @@
#ifndef __INC_METIN_I_SQL_H__
#define __INC_METIN_I_SQL_H__
#include "libsql.h"
#ifndef FALSE
#define FALSE 0
#define TRUE (!FALSE)
#endif
#define MAX_QUERY_LENGTH 1024
extern char query_buf[MAX_QUERY_LENGTH+1];
extern SQL * sql_account;
int sql_init();
void sql_deinit();
int sql_account_query(const char *buf);
void sql_ping();
#endif
+266
View File
@@ -0,0 +1,266 @@
/*********************************************************************
* date : 2007.05.22
* file : sql_account.c
* author : mhh
* description :
*/
#define _sql_account_c_
#include "structs.h"
#include "utils.h"
#include "socket.h"
#include "config.h"
#include "log.h"
#include "sql.h"
#include "sql_account.h"
int account_get_login(DWORD account_id, CONN_DATA *conn)
{
snprintf(query_buf, MAX_QUERY_LENGTH,
"SELECT "
"login "
"FROM %s WHERE id='%u' LIMIT 1",
sql_account_table,
account_id);
if (sql_account_query(query_buf)<0)
{
sql_error(sql_account);
return FALSE;
}
MYSQL_RES *result = NULL;
MYSQL_ROW row;
char ret;
if (!(result = sql_result(sql_account)))
{
sql_error(sql_account);
return FALSE;
}
if (mysql_num_rows(result)<=0)
ret = FALSE;
else
ret = TRUE;
if (FALSE==ret)
{
sql_free_result(result);
return FALSE;
}
if (!(row = sql_fetch_row(result)))
{
sql_free_result(result);
return FALSE;
}
char login[MAX_LOGIN_LEN+1] = {0};
lower_string( row[0] , login , MAX_LOGIN_LEN ) ;
sql_free_result(result);
GET_ID(conn) = account_id;
STRNCPY(GET_LOGIN(conn), login, MAX_LOGIN_LEN);
GET_TEENAGE(conn) = NO;
GET_ON_TIME(conn) = 0;
GET_OFF_TIME(conn) = 0;
return TRUE;
} /* end of account_login() */
static
MYSQL_RES* fetch_teen_info(DWORD account_id)
{
snprintf(query_buf, MAX_QUERY_LENGTH,
"SELECT "
"teenage, " // 청소년인가?
"on_time, " // 누적 온라인시간
"off_time, " // 누적 오프라인시간
"UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(logout_time) " // 오프라인 시간 = (현재시간 - 로그아웃시간)
"FROM %s WHERE account_id='%u' LIMIT 1",
sql_teenage_table,
account_id);
if (sql_account_query(query_buf)<0)
{
sql_error(sql_account);
return NULL;
}
MYSQL_RES *result = sql_result(sql_account);
if (!result)
return NULL;
if (mysql_num_rows(result)<=0)
{
sql_free_result(result);
return NULL;
}
return result;
}
int account_login(DWORD account_id, CONN_DATA *conn)
{
if (FALSE == account_get_login(account_id, conn))
return FALSE;
MYSQL_RES *result = fetch_teen_info(account_id);
if (!result)
return FALSE;
int ret = (mysql_num_rows(result) > 0) ? TRUE : FALSE;
if (FALSE == ret)
{
sql_free_result(result);
return TRUE;
}
MYSQL_ROW row = sql_fetch_row(result);;
if (!row)
{
sql_free_result(result);
return FALSE;
}
int teenage = strtol(row[0], NULL, 10);
int on_time = strtol(row[1], NULL, 10);
int off_time = strtol(row[2], NULL, 10);
int logout_time = strtol(row[3], NULL, 10);
if (logout_time<0)
logout_time = 0;
sql_free_result(result);
GET_TEENAGE(conn) = teenage ? YES : NO;
GET_ON_TIME(conn) = on_time;
GET_OFF_TIME(conn) = off_time + logout_time;
// 누적 오프라인시간이 5시간 이상이면 온라인시간은 0
if (GET_OFF_TIME(conn) >= HOUR_TO_SEC(5))
{
GET_ON_TIME(conn) = 0;
GET_OFF_TIME(conn) = 0;
}
else if (GET_OFF_TIME(conn)<0)
GET_OFF_TIME(conn) = 0;
// update on_time, off_time
if (YES==GET_TEENAGE(conn))
{
snprintf(query_buf, MAX_QUERY_LENGTH,
"UPDATE %s SET on_time=%d, off_time=%d "
"WHERE account_id=%d",
sql_teenage_table,
GET_ON_TIME(conn), GET_OFF_TIME(conn), GET_ID(conn));
sql_async_query(sql_account, query_buf);
}
return TRUE;
} /* end of account_login() */
static
int insert_teen_info(DWORD account_id, const char *login)
{
snprintf(query_buf, MAX_QUERY_LENGTH,
"INSERT INTO %s "
"(account_id, login, teenage) values(%u, '%s', 1)",
sql_teenage_table,
account_id,
login);
if (sql_account_query(query_buf)<0)
{
sql_error(sql_account);
return FALSE;
}
return TRUE;
}
int account_login_teen_all(DWORD account_id, CONN_DATA *conn)
{
if (FALSE == account_get_login(account_id, conn))
return FALSE;
MYSQL_RES *result = fetch_teen_info(account_id);
if (NULL == result)
{
// insert new teenage_info
insert_teen_info(account_id, GET_LOGIN(conn));
result = fetch_teen_info(account_id);
}
MYSQL_ROW row = sql_fetch_row(result);;
if (!row)
{
sql_free_result(result);
return FALSE;
}
int teenage = strtol(row[0], NULL, 10);
int on_time = strtol(row[1], NULL, 10);
int off_time = strtol(row[2], NULL, 10);
int logout_time = strtol(row[3], NULL, 10);
if (logout_time<0)
logout_time = 0;
sql_free_result(result);
GET_TEENAGE(conn) = teenage ? YES : NO;
GET_ON_TIME(conn) = on_time;
GET_OFF_TIME(conn) = off_time + logout_time;
// 누적 오프라인시간이 5시간 이상이면 온라인시간은 0
if (GET_OFF_TIME(conn) >= HOUR_TO_SEC(5))
{
GET_ON_TIME(conn) = 0;
GET_OFF_TIME(conn) = 0;
}
else if (GET_OFF_TIME(conn)<0)
GET_OFF_TIME(conn) = 0;
// update on_time, off_time
if (YES==GET_TEENAGE(conn))
{
snprintf(query_buf, MAX_QUERY_LENGTH,
"UPDATE %s SET on_time=%d, off_time=%d "
"WHERE account_id=%d",
sql_teenage_table,
GET_ON_TIME(conn), GET_OFF_TIME(conn), GET_ID(conn));
sql_async_query(sql_account, query_buf);
}
return TRUE;
} /* end of account_login() */
int account_logout(CONN_DATA *conn)
{
// update on_time, logout_time
snprintf(query_buf, MAX_QUERY_LENGTH,
"UPDATE %s SET on_time=%d, logout_time=NOW() "
"WHERE account_id=%u",
sql_teenage_table, GET_ON_TIME(conn),
GET_ID(conn));
sql_async_query(sql_account, query_buf);
return TRUE;
} /* end of account_login() */
+16
View File
@@ -0,0 +1,16 @@
/*********************************************************************
* date : 2007.05.22
* file : sql_account.h
* author : mhh
* description :
*/
#ifndef _sql_account_h_
#define _sql_account_h_
int account_login(DWORD account_id, CONN_DATA *conn);
int account_login_teen_all(DWORD account_id, CONN_DATA *conn);
int account_logout(CONN_DATA *conn);
#endif /* _sql_account_h_ */
+170
View File
@@ -0,0 +1,170 @@
/*
* Filename: structs.h
* Description: 각종 헤더 포함 밑 구조체 밑 중요한(?)부분을 가지고 있는 헤더.
*
* Author: 비엽 (server), myevan (Client)
*/
#ifndef _STRUCTS_H_
#define _STRUCTS_H_
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <ctype.h>
#include <limits.h>
#include "length.h"
#include "macros.h"
#include "event.h"
int atoi(const char *nptr);
#define OPT_USEC 20000
// PASSES_PER_SEC 은 1000000 / OPT_USEC 다.
#define PASSES_PER_SEC (50)
#define RL_SEC * PASSES_PER_SEC
typedef signed char sbyte;
typedef unsigned char ubyte;
typedef signed short int sh_int;
typedef unsigned short int ush_int;
typedef int socket_t;
typedef struct descriptor_data DESC_DATA;
typedef struct packet_data PACKET_DATA;
typedef struct affect_data AFFECT_DATA;
typedef struct npc_relation NPC_RELATION;
typedef unsigned int DWORD;
typedef unsigned short int WORD;
typedef char byte;
typedef unsigned char BYTE;
typedef unsigned int LONG;
typedef unsigned int INT;
typedef sh_int OBJ_NUM;
/************************************************************************
* 디스크립터 관련 define 들 *
************************************************************************/
#define CLOSE_SOCKET(sock) close(sock);
#define DEFAULT_PACKET_BUFFER_SIZE 131072
#define MAX_INPUT_LEN 65535
#define MAX_NAME_LENGTH 16
#define MAX_OBJ_NAME_LENGTH 32
#define MAX_SOCIAL_LENGTH 16
#define MAX_TITLE_LENGTH 16
#define MAX_PWD_LENGTH 16
#define STATE_CLOSE 0
#define STATE_HANDSHAKE 1
#define STATE_MAIN 2
#define MAX_OBJ_AFFECT 4 // 0 1 2 3
#define MAX_OBJ_VALUES 5 // 0 1 2 3 4
#define MAX_OBJ_RESOURCES 4
#define DESCTYPE_GAME 0
#define DESCTYPE_ACCOUNT 1
#define DESCTYPE_CLIENT 2
/************************************************************************
* 디스크립터 관련 구조체 *
************************************************************************/
struct data_block
{
int memory_bytes;
int bytes;
WORD id;
char *data;
struct data_block *next;
};
struct data_q
{
int count;
struct data_block *head;
struct data_block *tail;
};
struct packet_data
{
int max_length;
int length;
char *data;
};
struct descriptor_data
{
int (*input_processor) (struct descriptor_data *d, char *data, int bytes_read);
BYTE type;
WORD users; // 이 서버에 연결된 사용자 수
WORD desc_num;
int descriptor;
int server_descriptor;
WORD poll; // POLL 의 위치
int state;
char host[MAX_HOST_LENGTH];
char inbuf[MAX_INPUT_LEN];
DWORD handshake;
PACKET_DATA packet_buffer;
struct descriptor_data *prev;
struct descriptor_data *next;
};
#define MAX_LOGIN_LEN 30
typedef struct conn_data_s
{
DWORD account_id;
char login[MAX_LOGIN_LEN+1];
int teenage;
int on_time;
int off_time;
DESC_DATA *desc;
int notice_step;
int notice_pulse;
EVENT *event;
} CONN_DATA;
#endif // _STRUCTS_H_
+82
View File
@@ -0,0 +1,82 @@
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
static volatile sig_atomic_t sigflag;
/* set nonzero by signal handler */
static sigset_t newmask, oldmask, zeromask;
static void sig_usr(int signo) /* one signal handler for SIGUSR1 and SIGUSR2 */
{
sigflag = 1;
return;
}
void TELL_WAIT()
{
if (signal(SIGUSR1, sig_usr) == SIG_ERR)
{
fprintf(stderr, "signal(SIGINT) error\n");
exit(1);
}
if (signal(SIGUSR2, sig_usr) == SIG_ERR)
{
fprintf(stderr, "signal(SIGQUIT) error\n");
exit(1);
}
sigemptyset(&zeromask);
sigemptyset(&newmask);
sigaddset(&newmask, SIGUSR1);
sigaddset(&newmask, SIGUSR2);
/* block SIGUSR1 and SIGUSR2, and save current signal mask */
if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0)
{
fprintf(stderr, "SIG_BLOCK error\n");
exit(1);
}
}
void TELL_PARENT(pid_t pid)
{
kill(pid, SIGUSR2); /* tell parent we're done */
}
void WAIT_PARENT(void)
{
while (sigflag == 0)
sigsuspend(&zeromask); /* and wait for parent */
sigflag = 0;
/* reset signal mask to original value */
if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
{
fprintf(stderr, "SIG_SETMASK error\n");
exit(1);
}
}
void TELL_CHILD(pid_t pid)
{
kill(pid, SIGUSR1); /* tell child we're done */
}
void WAIT_CHILD(void)
{
while (sigflag == 0)
sigsuspend(&zeromask); /* and wait for child */
sigflag = 0;
/* reset signal mask to original value */
if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
{
fprintf(stderr, "SIG_SETMASK error\n");
exit(1);
}
}
+12
View File
@@ -0,0 +1,12 @@
#ifndef __INC_METIN_TELLWAIT_H__
#define __INC_METIN_TELLWAIT_H__
extern void TELL_WAIT();
extern void WAIT_CHILD();
extern void TELL_CHILD(pid_t pid);
extern void WAIT_PARENT();
extern void TELL_PARENT(pid_t pid);
#endif
+248
View File
@@ -0,0 +1,248 @@
#include "structs.h"
#include "utils.h"
#include "db.h"
#include <stdarg.h>
extern struct timeval null_time;
#define ishprint(x) ((((x) & 0xE0) > 0x90) || isprint(x))
void printdata(unsigned char *data, int bytes)
{
int i, j, k;
unsigned char *p;
fprintf(stderr, "------------------------------------------------------------------\n");
j = bytes;
while (1)
{
k = j >= 16 ? 16 : j;
p = data;
for (i = 0; i < 16; i++)
{
if (i >= k)
fprintf(stderr, " ");
else
fprintf(stderr, "%02x ", *p);
p++;
}
fprintf(stderr, "| ");
p = data;
for (i = 0; i < k; i++)
{
if (i >= k)
fprintf(stderr, " ");
else
fprintf(stderr, "%c", ishprint(*p) ? *p : '.');
p++;
}
fprintf(stderr, "\n");
j -= 16;
data += 16;
if (j <= 0)
break;
}
fprintf(stderr, "------------------------------------------------------------------\n");
}
struct timeval *timediff(struct timeval *a, struct timeval *b)
{
static struct timeval rslt;
if (a->tv_sec < b->tv_sec)
return &null_time;
else if (a->tv_sec == b->tv_sec)
{
if (a->tv_usec < b->tv_usec)
return &null_time;
else
{
rslt.tv_sec = 0;
rslt.tv_usec = a->tv_usec - b->tv_usec;
return &rslt;
}
}
else
{ /* a->tv_sec > b->tv_sec */
rslt.tv_sec = a->tv_sec - b->tv_sec;
if (a->tv_usec < b->tv_usec)
{
rslt.tv_usec = a->tv_usec + 1000000 - b->tv_usec;
rslt.tv_sec--;
} else
rslt.tv_usec = a->tv_usec - b->tv_usec;
return &rslt;
}
}
struct timeval *timeadd(struct timeval *a, struct timeval *b)
{
static struct timeval rslt;
rslt.tv_sec = a->tv_sec + b->tv_sec;
rslt.tv_usec = a->tv_usec + b->tv_usec;
while (rslt.tv_usec >= 1000000)
{
rslt.tv_usec -= 1000000;
rslt.tv_sec++;
}
return &rslt;
}
char *time_str(time_t ct)
{
static char *time_s;
time_s = asctime(localtime(&ct));
time_s[strlen(time_s) - 6] = '\0';
time_s += 4;
return (time_s);
}
void lower_string(char *src, char *dest, int len)
{
char *tmp;
int i;
for (i = 0, tmp = src; *tmp && i < len; tmp++, i++)
*(dest++) = LOWER(*tmp);
// 뒤 부분을 널로 채운다.
for (; i < len; i++)
*(dest++) = '\0';
}
char *str_dup(const char *source)
{
char *new_line;
CREATE(new_line, char, strlen(source) + 1);
return (strcpy(new_line, source));
}
int filesize(FILE *fp)
{
int pos;
int size;
pos = ftell(fp);
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, pos, SEEK_SET);
return (size);
}
/* "Name : 비엽" 과 같이 "항목 : 값" 으로 이루어진 문자열에서
항목을 token 으로, 값을 value 로 복사하여 리턴한다. */
void parse_token(char *src, char *token, char *value)
{
char *tmp;
for (tmp = src; *tmp && *tmp != ':'; tmp++)
{
if (isnhspace(*tmp))
continue;
*(token++) = LOWER(*tmp);
}
*token = '\0';
for (tmp += 2; *tmp; tmp++)
{
if (*tmp == '\n' || *tmp == '\r')
continue;
*(value++) = *tmp;
}
*value = '\0';
}
struct tm *tm_calc(const struct tm *curr_tm, int days)
{
char yoon = FALSE;
static struct tm new_tm;
int monthdays[12] = { 31, 28, 31, 30, 31, 30, 31, 30, 31, 30, 31 };
if (!curr_tm)
{
time_t time_s = time(0);
new_tm = *localtime(&time_s);
}
else
memcpy(&new_tm, curr_tm, sizeof(struct tm));
if (new_tm.tm_mon == 1)
{
if (!((new_tm.tm_year + 1900) % 4))
{
if (!((new_tm.tm_year + 1900) % 100))
{
if (!((new_tm.tm_year + 1900) % 400))
yoon = TRUE;
}
else
yoon = TRUE;
}
if (yoon)
new_tm.tm_mday += 1;
}
if (yoon)
monthdays[1] = 29;
else
monthdays[1] = 28;
new_tm.tm_mday += days;
if (new_tm.tm_mday <= 0)
{
new_tm.tm_mon--;
if (new_tm.tm_mon < 0)
{
new_tm.tm_year--;
new_tm.tm_mon = 11;
}
new_tm.tm_mday = monthdays[new_tm.tm_mon] + new_tm.tm_mday;
}
else if (new_tm.tm_mday > monthdays[new_tm.tm_mon])
{
new_tm.tm_mon++;
if (new_tm.tm_mon > 11)
{
new_tm.tm_year++;
new_tm.tm_mon = 0;
}
new_tm.tm_mday = monthdays[new_tm.tm_mon] - new_tm.tm_mday;
}
return (&new_tm);
}
+109
View File
@@ -0,0 +1,109 @@
#ifndef _utils_h_chat_
#define _utils_h_chat_
#define FALSE 0
#define TRUE (!FALSE)
#define NO FALSE
#define YES TRUE
#define LOWER(c) (((c)>='A' && (c) <= 'Z') ? ((c)+('a'-'A')) : (c))
#define UPPER(c) (((c)>='a' && (c) <= 'z') ? ((c)+('A'-'a')) : (c))
void lower_string(char *src, char *dest, int len);
#define ishan(ch) (((ch) & 0xE0) > 0x90)
#define ishanasc(ch) (isascii(ch) || ishan(ch))
#define ishanalp(ch) (isalpha(ch) || ishan(ch))
#define isnhdigit(ch) (!ishan(ch) && isdigit(ch))
#define isnhspace(ch) (!ishan(ch) && isspace(ch))
extern struct timeval *timediff(struct timeval *a, struct timeval *b);
extern struct timeval *timeadd(struct timeval *a, struct timeval *b);
struct tm * tm_calc(const struct tm *curr_tm, int days);
extern char *first_han(unsigned char *str);
extern int check_han(char *str);
//extern int is_hangul(unsigned char *str);
extern int under_han(unsigned char *str);
#define str_cmp strcasecmp
extern char *str_dup(const char *source);
extern int get_filename(char *orig_name, char *fname, BYTE type);
//extern void sys_log(const char *format, ...);
//extern void pt_log(const char *format, ...);
extern void printdata(unsigned char *data, int bytes);
extern int filesize(FILE *fp);
#define TOKEN(string) if (!str_cmp(token_string, string))
extern void parse_token(char *src, char *token, char *value);
#define SAFE_FREE(p) do { \
if (p) \
{ \
free(p); \
(p) = NULL; \
} \
} while(0)
#define CREATE(result, type, number) do { \
if (!((result) = (type *) calloc ((number), sizeof(type)))) \
{ perror("malloc failure"); abort(); } } while(0)
// Next ¿Í Prev °¡ ÀÖ´Â ¸®½ºÆ®¿¡ Ãß°¡
#define INSERT_TO_TW_LIST(item, head, prev, next) \
if (!(head)) \
{ \
head = item; \
(head)->prev = (head)->next = NULL; \
} \
else \
{ \
(head)->prev = item; \
(item)->next = head; \
(item)->prev = NULL; \
head = item; \
}
#define REMOVE_FROM_TW_LIST(item, head, prev, next) \
if ((item) == (head)) \
{ \
if (((head) = (item)->next)) \
(head)->prev = NULL; \
} \
else \
{ \
if ((item)->next) \
(item)->next->prev = (item)->prev; \
if ((item)->prev) \
(item)->prev->next = (item)->next; \
}
#define INSERT_TO_LIST(item, head, next) \
(item)->next = (head); \
(head) = (item); \
#define REMOVE_FROM_LIST(item, head, next) \
if ((item) == (head)) \
head = (item)->next; \
else \
{ \
temp = head; \
\
while (temp && (temp->next != (item))) \
temp = temp->next; \
\
if (temp) \
temp->next = (item)->next; \
}
#define STRNCPY(dest,src,len) do { \
strncpy(dest, src, len); \
dest[len] = 0; \
} while(0)
#endif // _utils_h_chat_