sp_tbs_win.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693
  1. #include "precompile.h"
  2. #include "sp_svc.h"
  3. #include "sp_def.h"
  4. #include "sp_ses.h"
  5. #include "sp_tbs.h"
  6. #include "sp_env.h"
  7. #include "sp_bcm.h"
  8. #include "sp_log.h"
  9. #include "sp_uid.h"
  10. #include "sp_var.h"
  11. #include "SpBase.h"
  12. #include "list.h"
  13. #include "hash.h"
  14. #include "array.h"
  15. #include "refcnt.h"
  16. #include "spinlock.h"
  17. #include "strutil.h"
  18. #include "fileutil.h"
  19. #include "memutil.h"
  20. #include "uuid4.h"
  21. #include "dbgutil.h"
  22. #include <winpr/winsock.h>
  23. #include <winpr/string.h>
  24. #define TAG SPBASE_TAG("tbs")
  25. #define SESSION_BUCKET_SIZE 511
  26. #define REGISTER_BUCKET_SIZE 127
  27. #define RX_BUF_SIZE 1024
  28. #define MSG_EVT_IDX 0
  29. #define SRV_EVT_IDX 1
  30. #define MAX_TIMEOUT 30000
  31. #define HDR_LEN 4
  32. #define CONN_INVALID_ID -1
  33. #define MSG_STOP 0
  34. #define MSG_UAC_ON_CONNECT 1
  35. #define MSG_UAC_ON_CLOSE 2
  36. #define MSG_UAC_ON_DESTROY 3
  37. #define MSG_UAC_ON_ANS 4
  38. #define MSG_ON_EVENT 5
  39. #define RECV_STATE_HEADER 0 /* already recv header length */
  40. #define RECV_STATE_BODY 1 /* recv body */
  41. //数据信息 0x00 00 FF FF
  42. #define PKT_TYPE_INFO 0
  43. #define PKT_TYPE_SESSION 1
  44. #define PKT_TYPE_SESSIONEND 2
  45. #define PKT_TYPE_REQ 3
  46. #define PKT_TYPE_REQACK 4
  47. #define PKT_TYPE_SESSIONACK 5
  48. #define PKT_TYPE_REGISTER_EVENT 6
  49. #define PKT_TYPE_UNREGISTER_EVENT 7
  50. #define PKT_TYPE_EVENT_DATA 8
  51. #define PKT_TYPE_LOG_EVENT 9
  52. #define PKT_TYPE_LOG_WARN 10
  53. // add sys var get & set type by xkm@20150526
  54. #define PKT_TYPE_SET_VAR_REQ 11 // len + type + tsx_id + varname + varvalue
  55. #define PKT_TYPE_SET_VAR_ACK 12 // len + type + conn_id + tsx_id + errcode + errmsg
  56. #define PKT_TYPE_GET_VAR_REQ 13 // len + type + tsx_id + varname
  57. #define PKT_TYPE_GET_VAR_ACK 14 // len + type + conn_id + tsx_id + errcode + varvalue/errmsg
  58. //控制信息 0xFF FF 00 00
  59. #define PKT_TYPE_CONTROL_LINKCONTEXT (1 << 31)
  60. class link_context {
  61. public:
  62. char* businessId; //32
  63. char* traceId; //32
  64. char* spanId; //16
  65. char* parentSpanId; //16
  66. wchar_t* wbusinessId; //32
  67. wchar_t* wtraceId; //32
  68. wchar_t* wspanId; //16
  69. wchar_t* wparentSpanId; //16
  70. //重复代码,需优化
  71. public:
  72. link_context() {
  73. businessId = traceId = spanId = parentSpanId = nullptr;
  74. wbusinessId = wtraceId = wspanId = wparentSpanId = nullptr;
  75. }
  76. ~link_context() {
  77. if (businessId)
  78. free(businessId);
  79. if (traceId)
  80. free(traceId);
  81. if (spanId)
  82. free(spanId);
  83. if (parentSpanId)
  84. free(parentSpanId);
  85. if (wbusinessId)
  86. free(wbusinessId);
  87. if (wtraceId)
  88. free(wtraceId);
  89. if (wspanId)
  90. free(wspanId);
  91. if (wparentSpanId)
  92. free(wparentSpanId);
  93. }
  94. void InitbusinessId(const std::string t_businessId)
  95. {
  96. if (nullptr == businessId) {
  97. businessId = (char*)malloc(t_businessId.length() + 1);
  98. ZeroMemory(businessId, t_businessId.length() + 1);
  99. strcpy_s(businessId, t_businessId.length() + 1, t_businessId.c_str());
  100. }
  101. }
  102. void InittraceId(const std::string t_traceId)
  103. {
  104. if (nullptr == traceId) {
  105. traceId = (char*)malloc(t_traceId.length() + 1);
  106. ZeroMemory(traceId, t_traceId.length() + 1);
  107. strcpy_s(traceId, t_traceId.length() + 1, t_traceId.c_str());
  108. }
  109. }
  110. void InitspanId(const std::string t_spanId)
  111. {
  112. if (nullptr == spanId) {
  113. spanId = (char*)malloc(t_spanId.length() + 1);
  114. ZeroMemory(spanId, t_spanId.length() + 1);
  115. strcpy_s(spanId, t_spanId.length() + 1, t_spanId.c_str());
  116. }
  117. }
  118. void InitparentSpanId(const std::string t_parentSpanId)
  119. {
  120. if (nullptr == parentSpanId) {
  121. parentSpanId = (char*)malloc(t_parentSpanId.length() + 1);
  122. ZeroMemory(parentSpanId, t_parentSpanId.length() + 1);
  123. strcpy_s(parentSpanId, t_parentSpanId.length() + 1, t_parentSpanId.c_str());
  124. }
  125. }
  126. const char* businessIdWtoA()
  127. {
  128. if (businessId)
  129. return businessId;
  130. else if (wbusinessId)
  131. {
  132. int n = WideCharToMultiByte(CP_ACP, 0, wbusinessId, -1, NULL, 0, NULL, NULL);
  133. businessId = (char*)malloc(n);
  134. WideCharToMultiByte(CP_ACP, 0, wbusinessId, -1, businessId, n, NULL, NULL);
  135. return businessId;
  136. }
  137. else
  138. return "None";
  139. }
  140. const char* traceIdWtoA()
  141. {
  142. if (traceId)
  143. return traceId;
  144. else if (wtraceId)
  145. {
  146. int n = WideCharToMultiByte(CP_ACP, 0, wtraceId, -1, NULL, 0, NULL, NULL);
  147. traceId = (char*)malloc(n);
  148. WideCharToMultiByte(CP_ACP, 0, wtraceId, -1, traceId, n, NULL, NULL);
  149. return traceId;
  150. }
  151. else
  152. return "None";
  153. }
  154. const char* spanIdWtoA()
  155. {
  156. if (spanId)
  157. return spanId;
  158. else if (wspanId)
  159. {
  160. int n = WideCharToMultiByte(CP_ACP, 0, wspanId, -1, NULL, 0, NULL, NULL);
  161. spanId = (char*)malloc(n);
  162. WideCharToMultiByte(CP_ACP, 0, wspanId, -1, spanId, n, NULL, NULL);
  163. return spanId;
  164. }
  165. else
  166. return "None";
  167. }
  168. const char* parentSpanIdWtoA()
  169. {
  170. if (parentSpanId)
  171. return parentSpanId;
  172. else if (wparentSpanId)
  173. {
  174. int n = WideCharToMultiByte(CP_ACP, 0, wparentSpanId, -1, NULL, 0, NULL, NULL);
  175. parentSpanId = (char*)malloc(n);
  176. WideCharToMultiByte(CP_ACP, 0, wparentSpanId, -1, parentSpanId, n, NULL, NULL);
  177. return parentSpanId;
  178. }
  179. else
  180. return "None";
  181. }
  182. };
  183. typedef struct cmd_entry cmd_entry;
  184. typedef struct sub_session sub_session;
  185. typedef struct reg_entry reg_entry;
  186. typedef struct sock_connection sock_connection;
  187. struct cmd_entry {
  188. struct list_head entry;
  189. int msg;
  190. param_size_t param1;
  191. param_size_t param2;
  192. };
  193. struct sub_session {
  194. struct hlist_node hentry;
  195. unsigned int id;
  196. unsigned int tsx_id;
  197. sp_ses_uac_t *uac;
  198. sock_connection *conn;
  199. };
  200. struct reg_entry {
  201. struct hlist_node hentry;
  202. unsigned int register_id;
  203. unsigned int entity_id;
  204. sp_uid_t uid;
  205. sp_bcm_listener_t *listener;
  206. sock_connection *conn;
  207. };
  208. struct sock_connection {
  209. SOCKET fd;
  210. int idx;
  211. int session_cnt;
  212. struct hlist_head session_bucket[SESSION_BUCKET_SIZE];
  213. int register_cnt;
  214. struct hlist_head register_bucket[REGISTER_BUCKET_SIZE];
  215. iobuffer_queue_t *tx_queue;
  216. iobuffer_t *rx_pkt;
  217. char rx_hdr_buf[RX_BUF_SIZE];
  218. int rx_hdr_buf_len;
  219. int rx_state;
  220. int rx_header_len;
  221. sp_tbs_t *tbs;
  222. DECLARE_REF_COUNT_MEMBER(ref_cnt);
  223. };
  224. DECLARE_REF_COUNT_STATIC(sock_connection, sock_connection)
  225. struct sp_tbs_t
  226. {
  227. SOCKET server_fd;
  228. unsigned long server_ip;
  229. unsigned short server_port;
  230. HANDLE conn_evt[MAXIMUM_WAIT_OBJECTS]; // 0 对应待发送消息;1 对应侦听socket事件;2~MAX 对应通讯socket事件
  231. HANDLE ready_evt;
  232. int ready_evt_result;
  233. sock_connection *conn[MAXIMUM_WAIT_OBJECTS]; // 0和1为空
  234. int conn_cnt; // 实际连接数+2
  235. unsigned int sub_session_seq;
  236. struct list_head cmd_list;
  237. spinlock_t cmd_list_lock;
  238. sp_log_client_t *log_client;
  239. HANDLE work_thread;
  240. DWORD work_thread_id;
  241. sp_ses_mgr_t *ses_mgr;
  242. sp_var_client_t *var_client;
  243. };
  244. static void on_write(sp_tbs_t *tbs, sock_connection *conn);
  245. static void on_accept(sp_tbs_t *tbs);
  246. static void on_read(sp_tbs_t *tbs, sock_connection *conn);
  247. static void on_close(sp_tbs_t *tbs, sock_connection *conn);
  248. static void on_stop(sp_tbs_t *tbs);
  249. static void on_session_end(sp_tbs_t *tbs, sock_connection *conn, int conn_id);
  250. static void on_info(sp_tbs_t *tbs, sock_connection *conn, int conn_id, int method_id, int method_sig, iobuffer_t **info_pkt);
  251. static void on_req(sp_tbs_t *tbs, sock_connection *conn, int conn_id, int tsx_id, int method_id, int method_sig, int timeout, iobuffer_t **req_pkt);
  252. static void on_session(sp_tbs_t *tbs, sock_connection *conn, int tsx_id, char *entity_name, char *function_name, char *class_name);
  253. static void on_register_event(sp_tbs_t *tbs, sock_connection *conn, int register_id, char *entity_name, char *function_name);
  254. static void on_unregister_event(sp_tbs_t *tbs, sock_connection *conn, int register_id);
  255. static void post_session_end(sp_tbs_t *tbs, sock_connection *conn, int conn_id);
  256. static void post_req_ack(sp_tbs_t *tbs, sock_connection *conn, int conn_id, int tsx_id, int end, int err, const wchar_t *err_msg, iobuffer_t **ack_pkt);
  257. static void post_session_ack(sp_tbs_t *tbs, sock_connection *conn, int conn_id, int tsx_id, int err, const wchar_t *err_msg);
  258. static void post_event(sp_tbs_t *tbs, reg_entry *entry, int conn_id, int tsx_id, iobuffer_t **evt_pkt);
  259. static void uac_on_connect(sp_tbs_t *tbs, sock_connection *conn, sub_session *session, int error);
  260. static void uac_on_close(sp_tbs_t *tbs, sock_connection *conn, sub_session *session, int error);
  261. static void uac_on_ans(sp_tbs_t *tbs, sock_connection *conn, sub_session *session, int tsx_id, int error, int user_error, const char* msg, int end, iobuffer_t **ans_pkt);
  262. static void uac_on_destroy(sp_tbs_t *tbs, sock_connection *conn, sub_session *session);
  263. static void post_msg(sp_tbs_t *tbs, int msg, param_size_t param1, param_size_t param2);
  264. static void destroy_sub_session(sp_tbs_t *tbs, sock_connection *conn, sub_session *session);
  265. postLink g_postlink = NULL;
  266. void sp_tbs_setpostlink(postLink cur)
  267. {
  268. g_postlink = cur;
  269. }
  270. static const wchar_t *get_err_msg(int rc)
  271. {
  272. return rc == 0 ? NULL : L"please find the err msg in ErrorCode.h!";
  273. }
  274. static const wchar_t *get_user_err_msg(int rc)
  275. {
  276. static wchar_t msg[512];
  277. if (rc == 0)
  278. return NULL;
  279. memset(msg, 0, sizeof(msg));
  280. swprintf_s(msg, 512, L"UserError=%d", rc);
  281. return msg;
  282. }
  283. static int create_connection(sp_tbs_t *tbs)
  284. {
  285. sock_connection *conn;
  286. SOCKET new_client;
  287. int i;
  288. BOOL opt;
  289. struct sockaddr_in from_addr;
  290. int from_len = sizeof(from_addr);
  291. new_client = accept(tbs->server_fd, (struct sockaddr*)&from_addr, &from_len);
  292. if (new_client == INVALID_SOCKET) {
  293. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("accept connection failed! %s %d", _GetFileName(__FILE__), __LINE__);
  294. return Error_NetBroken;
  295. }
  296. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("accept from %s:%d", inet_ntoa(from_addr.sin_addr), ntohs(from_addr.sin_port));
  297. if (tbs->conn_cnt >= MAXIMUM_WAIT_OBJECTS) {
  298. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("exceed maximum wait objects, connection discard! %s %d", _GetFileName(__FILE__), __LINE__);
  299. WSAEventSelect(new_client, tbs->conn_evt[SRV_EVT_IDX], 0);
  300. closesocket(new_client);
  301. return Error_Resource;
  302. }
  303. conn = MALLOC_T(sock_connection);
  304. conn->idx = tbs->conn_cnt++;
  305. conn->fd = new_client;
  306. conn->rx_hdr_buf_len = 0;
  307. conn->tx_queue = iobuffer_queue_create();
  308. conn->rx_pkt = NULL;
  309. conn->session_cnt = 0;
  310. conn->register_cnt = 0;
  311. conn->tbs = tbs;
  312. conn->rx_state = RECV_STATE_HEADER;
  313. conn->rx_header_len = 0;
  314. for (i = 0; i < array_size(conn->session_bucket); ++i) {
  315. INIT_HLIST_HEAD(&conn->session_bucket[i]);
  316. }
  317. for (i = 0; i < array_size(conn->register_bucket); ++i) {
  318. INIT_HLIST_HEAD(&conn->register_bucket[i]);
  319. }
  320. REF_COUNT_INIT(&conn->ref_cnt);
  321. tbs->conn[conn->idx] = conn;
  322. tbs->conn_evt[conn->idx] = WSACreateEvent();
  323. opt = TRUE;
  324. setsockopt(new_client, IPPROTO_TCP, TCP_NODELAY, (char*)&opt, sizeof(opt));
  325. opt = TRUE;
  326. setsockopt(new_client, SOL_SOCKET, SO_DONTLINGER, (char*)&opt, sizeof(opt));
  327. WSAEventSelect(new_client, tbs->conn_evt[conn->idx], FD_WRITE | FD_READ | FD_CLOSE);
  328. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("sock connection created!");
  329. return 0;
  330. }
  331. static void __destroy_connection(sock_connection *conn)
  332. {
  333. sp_tbs_t *tbs = conn->tbs;
  334. if (conn->fd != INVALID_SOCKET) {
  335. WSAEventSelect(conn->fd, tbs->conn_evt[conn->idx], 0);
  336. closesocket(conn->fd);
  337. conn->fd = INVALID_SOCKET;
  338. }
  339. WSACloseEvent(tbs->conn_evt[conn->idx]);
  340. tbs->conn_evt[conn->idx] = NULL;
  341. tbs->conn[conn->idx] = NULL;
  342. if (conn->idx != tbs->conn_cnt-1) {
  343. tbs->conn_evt[conn->idx] = tbs->conn_evt[tbs->conn_cnt-1];
  344. tbs->conn[conn->idx] = tbs->conn[tbs->conn_cnt-1];
  345. tbs->conn[conn->idx]->idx = conn->idx;
  346. }
  347. tbs->conn_cnt--;
  348. iobuffer_queue_destroy(conn->tx_queue);
  349. conn->tx_queue = NULL;
  350. if (conn->rx_pkt) {
  351. iobuffer_dec_ref(conn->rx_pkt);
  352. conn->rx_pkt = NULL;
  353. }
  354. free(conn);
  355. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("sock connection destroy!");
  356. }
  357. IMPLEMENT_REF_COUNT_STATIC(sock_connection, sock_connection, ref_cnt, __destroy_connection)
  358. static __inline int is_worker_thread(sp_tbs_t *tbs)
  359. {
  360. return GetCurrentThreadId() == tbs->work_thread_id;
  361. }
  362. static sub_session *find_sub_session(sock_connection *conn, int conn_id)
  363. {
  364. sub_session *tpos;
  365. struct hlist_node *pos;
  366. int slot = ((unsigned int )conn_id) % SESSION_BUCKET_SIZE; // bugfix, assure slot positive
  367. hlist_for_each_entry(tpos, pos, &conn->session_bucket[slot], sub_session, hentry) {
  368. if (tpos->id == conn_id)
  369. return tpos;
  370. }
  371. return NULL;
  372. }
  373. static void __uac_on_connect(sp_ses_uac_t *uac, int error, void *user_data)
  374. {
  375. sub_session *session = (sub_session*)user_data;
  376. if (is_worker_thread(session->conn->tbs)) {
  377. uac_on_connect(session->conn->tbs, session->conn, session, error);
  378. } else {
  379. post_msg(session->conn->tbs, MSG_UAC_ON_CONNECT, (int)session, error);
  380. }
  381. }
  382. static void __uac_on_close(sp_ses_uac_t *uac, int error, void *user_data)
  383. {
  384. sub_session *session = (sub_session*)user_data;
  385. if (is_worker_thread(session->conn->tbs)) {
  386. uac_on_close(session->conn->tbs, session->conn, session, error);
  387. } else {
  388. post_msg(session->conn->tbs, MSG_UAC_ON_CLOSE, (int)session, error);
  389. }
  390. }
  391. static void __uac_on_destroy(sp_ses_uac_t *uac, void *user_data)
  392. {
  393. sub_session *session = (sub_session*)user_data;
  394. TOOLKIT_ASSERT(session->uac == NULL);
  395. if (is_worker_thread(session->conn->tbs)) {
  396. uac_on_destroy(session->conn->tbs, session->conn, session);
  397. } else {
  398. post_msg(session->conn->tbs, MSG_UAC_ON_DESTROY, (int)session, 0);
  399. }
  400. }
  401. static void __uac_on_ans(sp_tsx_uac_t *tsx, int error, int end, iobuffer_t **ans_pkt, void *user_data)
  402. {
  403. sub_session *session = (sub_session*)user_data;
  404. iobuffer_t *pkt = NULL;
  405. int tsx_id;
  406. int user_error = 0;
  407. int slen = 0;
  408. char *msg_str = NULL;
  409. if (error)
  410. {
  411. if (ans_pkt)
  412. {
  413. pkt = *ans_pkt;
  414. iobuffer_reset(pkt);
  415. *ans_pkt = NULL;
  416. }
  417. else
  418. {
  419. pkt = iobuffer_create(-1, -1);
  420. }
  421. }
  422. else
  423. {
  424. TOOLKIT_ASSERT(ans_pkt);
  425. pkt = *ans_pkt;
  426. *ans_pkt = NULL;
  427. iobuffer_read(pkt, IOBUF_T_I4, &error, NULL);
  428. iobuffer_read(pkt, IOBUF_T_I4, &user_error, NULL);
  429. if (error)
  430. {
  431. iobuffer_read(pkt, IOBUF_T_STR, NULL, &slen);
  432. if (slen) {
  433. msg_str = (char*)malloc(slen + 1);
  434. iobuffer_read(pkt, IOBUF_T_WSTR, msg_str, NULL);
  435. }
  436. iobuffer_reset(pkt);
  437. }
  438. }
  439. tsx_id = sp_tsx_uac_get_id(tsx);
  440. if (is_worker_thread(session->conn->tbs))
  441. {
  442. uac_on_ans(session->conn->tbs, session->conn, session, tsx_id, error, user_error, msg_str, end, &pkt);
  443. if (pkt)
  444. iobuffer_dec_ref(pkt);
  445. }
  446. else
  447. {
  448. iobuffer_format_write_head(pkt, "s4444", msg_str, &end, &user_error, &error, &tsx_id);
  449. post_msg(session->conn->tbs, MSG_UAC_ON_ANS, (int)session, (int)pkt);
  450. }
  451. if (error || end)
  452. {
  453. sp_tsx_uac_close(tsx);
  454. sp_tsx_uac_destroy(tsx);
  455. }
  456. }
  457. static void uac_on_connect(sp_tbs_t *tbs, sock_connection *conn, sub_session *session, int error)
  458. {
  459. if (!error) {
  460. post_session_ack(tbs, conn, session->id, session->tsx_id, error, NULL);
  461. if(getReduceSpbaseLog())
  462. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("sub session created ok! ses_id = %d, tsx_id = %d", session->id, session->tsx_id);
  463. } else {
  464. sp_ses_uac_t *uac = session->uac;
  465. post_session_ack(tbs, conn, CONN_INVALID_ID, session->tsx_id, error, get_err_msg(error));
  466. session->uac = NULL;
  467. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("sub session created failed %d! ses_id = %d, tsx_id = %d", error, session->id, session->tsx_id);
  468. if (uac) {
  469. sp_ses_uac_close(uac);
  470. sp_ses_uac_destroy(uac);
  471. }
  472. }
  473. }
  474. static void uac_on_close(sp_tbs_t *tbs, sock_connection *conn, sub_session *session, int error)
  475. {
  476. if (session->uac) {
  477. sp_ses_uac_t *uac = session->uac;
  478. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("uac on close detected! id = %d, %s %d %d", session->id, _GetFileName(__FILE__), __LINE__, error);
  479. post_session_end(tbs, conn, session->id);
  480. session->uac = NULL;
  481. if (error != Error_Closed)
  482. sp_ses_uac_close(uac);
  483. sp_ses_uac_destroy(uac);
  484. }
  485. }
  486. static void uac_on_ans(sp_tbs_t *tbs, sock_connection *conn, sub_session *session, int tsx_id, int error, int user_error, const char* msg, int end, iobuffer_t **ans_pkt)
  487. {
  488. if(msg == NULL || strlen(msg) == 0)
  489. post_req_ack(tbs, conn, session->id, tsx_id, end, error, get_user_err_msg(user_error), ans_pkt);
  490. else
  491. post_req_ack(tbs, conn, session->id, tsx_id, end, error, CSimpleStringA2W(msg).GetData(), ans_pkt);
  492. }
  493. static void uac_on_destroy(sp_tbs_t *tbs, sock_connection *conn, sub_session *session)
  494. {
  495. destroy_sub_session(tbs, conn, session);
  496. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("destroy sub session(id:%d) uac %s %d", session->id, _GetFileName(__FILE__), __LINE__);
  497. }
  498. static int create_sub_session(sp_tbs_t *tbs, sock_connection *conn, int tsx_id, char *entity_name, char *function_name, char *class_name, sub_session **p_session)
  499. {
  500. sp_env_t *env = sp_get_env();
  501. sp_entity_t *ent = sp_mod_mgr_find_entity_by_name(env->mod_mgr, entity_name);
  502. if (ent) {
  503. int rc;
  504. sub_session *session = MALLOC_T(sub_session);
  505. sp_ses_uac_callback cb;
  506. iobuffer_t *pkt = NULL;
  507. char *param = NULL;
  508. session->id = tbs->sub_session_seq++;
  509. session->conn = conn;
  510. session->tsx_id = tsx_id;
  511. hlist_add_head(&session->hentry, &conn->session_bucket[session->id % SESSION_BUCKET_SIZE]);
  512. conn->session_cnt++;
  513. sock_connection_inc_ref(conn);
  514. cb.user_data = session;
  515. cb.on_close = &__uac_on_close;
  516. cb.on_destroy = &__uac_on_destroy;
  517. cb.on_connect = &__uac_on_connect;
  518. rc = sp_ses_uac_create(tbs->ses_mgr, ent->mod->cfg->idx, ent->cfg->idx, &cb, &session->uac);
  519. if (rc != 0) {
  520. goto on_error;
  521. }
  522. pkt = iobuffer_create(-1, -1);
  523. if (function_name == NULL || strlen(function_name) == 0) {
  524. param = class_name;
  525. } else {
  526. param = strdup_printf("%s::%s", class_name, function_name);
  527. }
  528. iobuffer_write(pkt, IOBUF_T_STR, param, -1);
  529. if (param != class_name) {
  530. FREE(param);
  531. }
  532. rc = sp_ses_uac_async_connect(session->uac, 10000, &pkt);
  533. if (pkt)
  534. iobuffer_dec_ref(pkt);
  535. if (rc != 0) {
  536. goto on_error;
  537. }
  538. on_error:
  539. if (rc != 0) {
  540. conn->session_cnt--;
  541. hlist_del(&session->hentry);
  542. sock_connection_dec_ref(conn);
  543. free(session);
  544. } else {
  545. *p_session = session;
  546. }
  547. return rc;
  548. } else {
  549. return Error_NotExist;
  550. }
  551. }
  552. static void destroy_sub_session(sp_tbs_t *tbs, sock_connection *conn, sub_session *session)
  553. {
  554. conn->session_cnt--;
  555. hlist_del(&session->hentry);
  556. if (session->uac) {
  557. sp_ses_uac_t *uac = session->uac;
  558. session->uac = NULL;
  559. sp_ses_uac_destroy(uac);
  560. }
  561. sock_connection_dec_ref(conn);
  562. free(session);
  563. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("destroy sub session(id:%d) %s %d", session->id, _GetFileName(__FILE__), __LINE__);
  564. }
  565. static void post_session_ack(sp_tbs_t *tbs, sock_connection *conn, int conn_id, int tsx_id, int err, const wchar_t *err_msg)
  566. {
  567. if (conn->fd != INVALID_SOCKET) {
  568. int len;
  569. iobuffer_t *pkt = iobuffer_create(-1, -1);
  570. int type = PKT_TYPE_SESSIONACK;
  571. iobuffer_format_write(pkt, "4444w", &type, &conn_id, &tsx_id, &err, err_msg);
  572. len = iobuffer_get_length(pkt)-4;
  573. iobuffer_write_head(pkt, IOBUF_T_I4, &len, 0);
  574. iobuffer_queue_enqueue(conn->tx_queue, pkt);
  575. on_write(tbs, conn);
  576. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("send PKT_TYPE_SESSIONACK tsx_id=%d, err=%d", tsx_id, err);
  577. }
  578. }
  579. static void post_req_ack(sp_tbs_t *tbs, sock_connection *conn, int conn_id, int tsx_id, int end, int err, const wchar_t *err_msg, iobuffer_t **ack_pkt)
  580. {
  581. if (conn->fd != INVALID_SOCKET) {
  582. iobuffer_t *pkt = NULL;
  583. int len;
  584. char bend = !!end;
  585. int type = PKT_TYPE_REQACK;
  586. if (ack_pkt) {
  587. pkt = *ack_pkt;
  588. *ack_pkt = NULL;
  589. }
  590. if (!pkt) {
  591. pkt = iobuffer_create(-1, -1);
  592. }
  593. iobuffer_format_write_head(pkt, "w41444", err_msg, &err, &bend, &tsx_id, &conn_id, &type);
  594. len = iobuffer_get_length(pkt)-4;
  595. iobuffer_write_head(pkt, IOBUF_T_I4, &len, 0);
  596. iobuffer_queue_enqueue(conn->tx_queue, pkt);
  597. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("send PKT_TYPE_REQACK tsx_id=%d, err=%d, pktLen=%d", tsx_id, err, iobuffer_get_length(pkt));
  598. on_write(tbs, conn);
  599. }
  600. }
  601. static void post_set_var_ack(sp_tbs_t *tbs, sock_connection *conn, int tsx_id, int err, const wchar_t *err_msg)
  602. {
  603. if (conn->fd != INVALID_SOCKET) {
  604. int len;
  605. int type = PKT_TYPE_SET_VAR_ACK;
  606. iobuffer_t *pkt = iobuffer_create(-1, -1);
  607. int conn_id = CONN_INVALID_ID;
  608. iobuffer_format_write(pkt, "4444w", &type, &conn_id, &tsx_id, &err, err_msg);
  609. len = iobuffer_get_length(pkt) - 4;
  610. iobuffer_write_head(pkt, IOBUF_T_I4, &len, 0);
  611. iobuffer_queue_enqueue(conn->tx_queue, pkt);
  612. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("send PKT_TYPE_SET_VAR_ACK tsx_id=%d, err=%d", tsx_id, err);
  613. on_write(tbs, conn);
  614. }
  615. }
  616. static void post_get_var_ack(sp_tbs_t *tbs, sock_connection *conn, int tsx_id, int err, const wchar_t *err_msg, const wchar_t *value)
  617. {
  618. if (conn->fd != INVALID_SOCKET) {
  619. int len;
  620. int type = PKT_TYPE_GET_VAR_ACK;
  621. iobuffer_t *pkt = iobuffer_create(-1, -1);
  622. int conn_id = CONN_INVALID_ID;
  623. iobuffer_format_write(pkt, "4444w", &type, &conn_id, &tsx_id, &err, err == 0 ? value : err_msg);
  624. len = iobuffer_get_length(pkt) - 4;
  625. iobuffer_write_head(pkt, IOBUF_T_I4, &len, 0);
  626. iobuffer_queue_enqueue(conn->tx_queue, pkt);
  627. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("send PKT_TYPE_GET_VAR_ACK tsx_id=%d, err=%d", tsx_id, err);
  628. on_write(tbs, conn);
  629. }
  630. }
  631. static void post_session_end(sp_tbs_t *tbs, sock_connection *conn, int conn_id)
  632. {
  633. if (conn->fd != INVALID_SOCKET) {
  634. int len;
  635. iobuffer_t *pkt = iobuffer_create(-1, -1);
  636. int type = PKT_TYPE_SESSIONEND;
  637. iobuffer_format_write(pkt, "44", &type, &conn_id);
  638. len = iobuffer_get_length(pkt)-4;
  639. iobuffer_write_head(pkt, IOBUF_T_I4, &len, 0);
  640. iobuffer_queue_enqueue(conn->tx_queue, pkt);
  641. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("send PKT_TYPE_SESSIONEND");
  642. on_write(tbs, conn);
  643. }
  644. }
  645. static void on_session(sp_tbs_t *tbs, sock_connection *conn, int tsx_id, char *entity_name, char *function_name, char *class_name)
  646. {
  647. sub_session *session = NULL;
  648. int rc;
  649. rc = create_sub_session(tbs, conn, tsx_id, entity_name, function_name, class_name, &session);
  650. if (rc == 0) {
  651. if (getReduceSpbaseLog())
  652. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("start create sub session!");
  653. //post_session_ack(tbs, conn, session->id, tsx_id, rc, NULL);
  654. } else {
  655. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create_sub_session failed! entity: %s, err = %d %s %d",
  656. entity_name, rc, _GetFileName(__FILE__), __LINE__);
  657. post_session_ack(tbs, conn, CONN_INVALID_ID, tsx_id, rc, get_err_msg(rc));
  658. }
  659. }
  660. static reg_entry *find_reg_entry(sock_connection *conn, int register_id)
  661. {
  662. reg_entry *tpos;
  663. struct hlist_node *pos;
  664. int slot = ((unsigned int)register_id) % REGISTER_BUCKET_SIZE; // bugfix, assure slot positive
  665. hlist_for_each_entry(tpos, pos, &conn->register_bucket[slot], reg_entry, hentry) {
  666. if (tpos->register_id == register_id) {
  667. return tpos;
  668. }
  669. }
  670. return NULL;
  671. }
  672. static void post_event(sp_tbs_t *tbs, reg_entry *entry, int conn_id, int tsx_id, iobuffer_t **evt_pkt)
  673. {
  674. if (entry->conn->fd != INVALID_SOCKET) {
  675. int type;
  676. int len;
  677. iobuffer_t *pkt = *evt_pkt;
  678. *evt_pkt = NULL;
  679. type = PKT_TYPE_EVENT_DATA;
  680. iobuffer_write_head(pkt, IOBUF_T_I4, &tsx_id, 0);
  681. iobuffer_write_head(pkt, IOBUF_T_I4, &conn_id, 0);
  682. iobuffer_write_head(pkt, IOBUF_T_I4, &type, 0);
  683. len = iobuffer_get_length(pkt)-4;
  684. iobuffer_write_head(pkt, IOBUF_T_I4, &len, 0);
  685. iobuffer_queue_enqueue(entry->conn->tx_queue, pkt);
  686. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("send PKT_TYPE_EVENT_DATA tsx_id=%d", tsx_id);
  687. on_write(tbs, entry->conn);
  688. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("post event len:%d", len);
  689. }
  690. sp_bcm_listener_dec_ref(entry->listener); //@
  691. }
  692. static void __bcm_on_message_raw(sp_bcm_listener_t *listener, int from_client_id, iobuffer_t **msg_pkt, void *user_data)
  693. {
  694. reg_entry *entry = (reg_entry*)user_data;
  695. iobuffer_t *pkt = *msg_pkt;
  696. *msg_pkt = NULL;
  697. sp_bcm_listener_inc_ref(listener); //@
  698. post_msg(entry->conn->tbs, MSG_ON_EVENT, (int)entry, (int)pkt);
  699. if(getReduceSpbaseLog())
  700. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("post event from_client_id:%d", from_client_id);
  701. }
  702. static void __bcm_on_destroy(sp_bcm_listener_t *listener, void *user_data)
  703. {
  704. reg_entry *entry = (reg_entry*)user_data;
  705. entry->conn->register_cnt--;
  706. hlist_del(&entry->hentry);
  707. sock_connection_dec_ref(entry->conn);
  708. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unregister event ok! register_id = %d", entry->register_id);
  709. free(entry);
  710. }
  711. static void on_register_event(sp_tbs_t *tbs, sock_connection *conn, int register_id, char *entity_name, char *function_name)
  712. {
  713. sp_env_t *env = sp_get_env();
  714. sp_entity_t *ent = sp_mod_mgr_find_entity_by_name(env->mod_mgr, entity_name);
  715. if (ent) {
  716. int rc;
  717. sp_svc_t *svc = sp_ses_mgr_get_svc(tbs->ses_mgr);
  718. reg_entry *entry;
  719. sp_bcm_listener_cb cb;
  720. if (find_reg_entry(conn, register_id)) {
  721. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("register entry already exist, register id %d", register_id);
  722. return;
  723. }
  724. entry = ZALLOC_T(reg_entry);
  725. entry->register_id = register_id;
  726. entry->entity_id = ent->cfg->idx;
  727. hlist_add_head(&entry->hentry, &conn->register_bucket[((unsigned int)register_id) % REGISTER_BUCKET_SIZE]); // bugfix, assure index positive
  728. conn->register_cnt++;
  729. sock_connection_inc_ref(conn);
  730. entry->conn = conn;
  731. cb.on_message_raw = &__bcm_on_message_raw;
  732. cb.on_message = NULL;
  733. cb.on_destroy = &__bcm_on_destroy;
  734. cb.user_data = entry;
  735. rc = sp_bcm_listener_create(svc, entry->entity_id, function_name, &cb, &entry->listener);
  736. if (rc != 0) {
  737. goto on_error;
  738. }
  739. rc = sp_bcm_listener_subscribe(entry->listener, &entry->uid);
  740. if (rc != 0) {
  741. goto on_error;
  742. }
  743. on_error:
  744. if (rc != 0) {
  745. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create bcm listener failed! entity = %s, register_id = %d", ent->cfg->name, register_id);
  746. conn->register_cnt--;
  747. hlist_del_init(&entry->hentry);
  748. if (entry->listener) {
  749. sp_bcm_listener_destroy(entry->listener);
  750. }
  751. free(entry);
  752. sock_connection_dec_ref(conn);
  753. } else {
  754. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("register event for %s ok! register_id = %d", ent->cfg->name, register_id);
  755. }
  756. } else {
  757. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("cannot find entity %s!", entity_name);
  758. }
  759. }
  760. static void on_unregister_event(sp_tbs_t *tbs, sock_connection *conn, int register_id)
  761. {
  762. reg_entry *entry = find_reg_entry(conn, register_id);
  763. if (entry) {
  764. if (sp_bcm_listener_unsubscribe(entry->listener) == 0) {
  765. sp_bcm_listener_destroy(entry->listener);
  766. } else {
  767. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("entry already unregistered! register_id = %d", register_id);
  768. }
  769. } else {
  770. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("%s, entry not found, registered_id = %d", __FUNCTION__, register_id);
  771. }
  772. }
  773. static void on_log_event(sp_tbs_t *tbs, sock_connection *conn, int severity_level, int user_code, const char *msg, const linkContext &t_context)
  774. {
  775. sp_log_client_logWithLink(tbs->log_client, Log_Event, severity_level, 0, user_code, 0, 0, NULL == msg ? "" : msg, NULL == msg ? 0 : strlen(msg)
  776. , t_context.bussinessId.GetData(), t_context.traceId.GetData(), t_context.spanId.GetData(), t_context.parentSpanId.GetData());
  777. }
  778. static void on_log_warn(sp_tbs_t *tbs, sock_connection *conn, int severity_level, int user_code, const char *msg, const linkContext& t_context)
  779. {
  780. sp_log_client_logWithLink(tbs->log_client, Log_Warning, severity_level, 0, user_code, 0, 0, NULL == msg ? "" : msg, NULL == msg ? 0 : strlen(msg)
  781. , t_context.bussinessId.GetData(), t_context.traceId.GetData(), t_context.spanId.GetData(), t_context.parentSpanId.GetData());
  782. }
  783. static void on_req(sp_tbs_t *tbs, sock_connection *conn, int conn_id, int tsx_id, int method_id, int method_sig, int timeout, iobuffer_t **req_pkt)
  784. {
  785. sub_session *session = find_sub_session(conn, conn_id);
  786. if (session) {
  787. if (session->uac) {
  788. int rc;
  789. sp_tsx_uac_t *tsx;
  790. sp_tsx_uac_callback cb;
  791. cb.user_data = session;
  792. cb.on_ans = &__uac_on_ans;
  793. cb.on_destroy = NULL;
  794. rc = sp_tsx_uac_create(session->uac, tsx_id, method_id, method_sig, &cb, &tsx);
  795. if (rc == 0) {
  796. rc = sp_tsx_uac_async_req(tsx, timeout, req_pkt);
  797. if (rc == 0) {
  798. WLog_DBG(TAG, "send req: tsx_id=%d, method_id=%d, method_sig=%d, pkt_size=%d",
  799. tsx_id, method_id, method_sig, *req_pkt == NULL ? 0 : iobuffer_get_length(*req_pkt));
  800. } else {
  801. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("async req tsx failed! err = %d %s %d", rc, _GetFileName(__FILE__), __LINE__);
  802. post_req_ack(tbs, conn, conn_id, tsx_id, 1, rc, get_err_msg(rc), NULL);
  803. sp_tsx_uac_destroy(tsx);
  804. }
  805. } else {
  806. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create req tsx failed! %s %d", _GetFileName(__FILE__), __LINE__);
  807. post_req_ack(tbs, conn, conn_id, tsx_id, 1, rc, get_err_msg(rc), NULL);
  808. }
  809. } else {
  810. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("session already closed! %s %d", _GetFileName(__FILE__), __LINE__);
  811. post_req_ack(tbs, conn, conn_id, tsx_id, 1, Error_NetBroken, get_err_msg(Error_NetBroken), NULL);
  812. }
  813. } else {
  814. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("cannot find session id in htable! ignored! %s %d", _GetFileName(__FILE__), __LINE__);
  815. post_req_ack(tbs, conn, conn_id, tsx_id, 1, Error_NotExist, get_err_msg(Error_NotExist), NULL);
  816. }
  817. }
  818. static void on_info(sp_tbs_t *tbs, sock_connection *conn, int conn_id, int method_id, int method_sig, iobuffer_t **info_pkt)
  819. {
  820. sub_session *session = find_sub_session(conn, conn_id);
  821. if (session) {
  822. if (session->uac) {
  823. int rc = sp_ses_uac_send_info(session->uac, method_id, method_sig, info_pkt);
  824. if (rc != 0) {
  825. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("uac send info failed! error = %d %s %d", rc, _GetFileName(__FILE__), __LINE__);
  826. }
  827. else {
  828. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("send info: method_id=%d, method_sig=%d, pkt_size=%d", method_id, method_sig,
  829. // *info_pkt == NULL ? 0 : iobuffer_get_length(*info_pkt));
  830. }
  831. } else {
  832. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("session already closed! info ignored ! %s %d", _GetFileName(__FILE__), __LINE__);
  833. }
  834. } else {
  835. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("cannot find session id in htable! ignored! %s %d", _GetFileName(__FILE__), __LINE__);
  836. }
  837. }
  838. static void on_session_end(sp_tbs_t *tbs, sock_connection *conn, int conn_id)
  839. {
  840. sub_session *session = find_sub_session(conn, conn_id);
  841. if (session) {
  842. if (session->uac) {
  843. sp_ses_uac_t *uac = session->uac;
  844. session->uac = NULL;
  845. if (sp_ses_uac_close(uac) == 0) {
  846. sp_ses_uac_destroy(uac);
  847. } else {
  848. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("duplicated uac close!");
  849. }
  850. }
  851. } else {
  852. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("cannot find session id in htable! ignored! %s %d", _GetFileName(__FILE__), __LINE__);
  853. }
  854. }
  855. static void on_stop(sp_tbs_t *tbs)
  856. {
  857. int i;
  858. WSAEventSelect(tbs->server_fd, tbs->conn_evt[SRV_EVT_IDX], 0);
  859. closesocket(tbs->server_fd);
  860. tbs->server_fd = INVALID_SOCKET;
  861. for (i = tbs->conn_cnt-1; i > SRV_EVT_IDX; --i) {
  862. sock_connection *conn = tbs->conn[i];
  863. TOOLKIT_ASSERT(conn);
  864. on_close(tbs, conn);
  865. }
  866. }
  867. static void on_close(sp_tbs_t *tbs, sock_connection *conn)
  868. {
  869. int i;
  870. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("socket on close is invoked!");
  871. if (conn->fd != INVALID_SOCKET) {
  872. WSAEventSelect(conn->fd, tbs->conn_evt[conn->idx], 0);
  873. closesocket(conn->fd);
  874. conn->fd = INVALID_SOCKET;
  875. }
  876. for (i = 0; i < SESSION_BUCKET_SIZE; ++i) {
  877. sub_session *tpos;
  878. struct hlist_node *pos, *n;
  879. hlist_for_each_entry_safe(tpos, pos, n, &conn->session_bucket[i], sub_session, hentry) {
  880. if (tpos->uac) {
  881. sp_ses_uac_t *uac = tpos->uac;
  882. tpos->uac = NULL;
  883. if (sp_ses_uac_close(uac) == 0) {
  884. sp_ses_uac_destroy(uac);
  885. } else {
  886. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("duplicated uac close! %s %d", _GetFileName(__FILE__), __LINE__);
  887. }
  888. }
  889. }
  890. }
  891. for (i = 0; i < REGISTER_BUCKET_SIZE; ++i) {
  892. reg_entry *tpos;
  893. struct hlist_node *pos, *n;
  894. hlist_for_each_entry_safe(tpos, pos, n, &conn->register_bucket[i], reg_entry, hentry) {
  895. if (tpos->listener) {
  896. if (sp_bcm_listener_unsubscribe(tpos->listener) == 0) {
  897. sp_bcm_listener_destroy(tpos->listener);
  898. }
  899. }
  900. }
  901. }
  902. sock_connection_dec_ref(conn);
  903. }
  904. static void on_set_var_req(sp_tbs_t *tbs, sock_connection *conn, int tsx_id, char *name, char *value)
  905. {
  906. int rc;
  907. if (name == NULL)
  908. {
  909. rc = Error_Param;
  910. post_set_var_ack(tbs, conn, tsx_id, rc, L"param [name] is null");
  911. return;
  912. }
  913. rc = sp_var_client_set((sp_var_client_t*)tbs->var_client, name, value, 0);
  914. post_set_var_ack(tbs, conn, tsx_id, rc, get_err_msg(rc));
  915. }
  916. static void on_get_var_req(sp_tbs_t *tbs, sock_connection *conn, int tsx_id, char *name)
  917. {
  918. int len = 260;
  919. int rc;
  920. char szTmp[260] = { 0 };
  921. wchar_t wszValue[260] = { 0 };
  922. if (name == NULL)
  923. {
  924. rc = Error_Param;
  925. post_get_var_ack(tbs, conn, tsx_id, rc, L"param [name] is null", NULL);
  926. return;
  927. }
  928. rc = sp_var_client_lock(tbs->var_client);
  929. if (rc == 0) {
  930. rc = sp_var_client_get((sp_var_client_t*)tbs->var_client, name, szTmp, &len);
  931. }
  932. sp_var_client_unlock(tbs->var_client);
  933. if (rc == 0)
  934. {
  935. len = 260;
  936. MultiByteToWideChar(CP_ACP, 0, szTmp, -1, &wszValue[0], len);
  937. post_get_var_ack(tbs, conn, tsx_id, rc, get_err_msg(rc), wszValue);
  938. }
  939. else
  940. post_get_var_ack(tbs, conn, tsx_id, rc, get_err_msg(rc), NULL);
  941. }
  942. static void process_tcp_pkt(sp_tbs_t *tbs, sock_connection *conn, iobuffer_t **p_pkt)
  943. {
  944. iobuffer_t *pkt = *p_pkt;
  945. int type;
  946. iobuffer_read(pkt, IOBUF_T_I4, &type, NULL);
  947. link_context cur;
  948. char linkStr[512] = "";
  949. bool withLinkContex = !!(type & PKT_TYPE_CONTROL_LINKCONTEXT);
  950. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("process_tcp_pkt withLinkContex:%d", withLinkContex);
  951. int linkId = 0;
  952. type = type & 0x0000FFFF; //clear control part
  953. switch (type) {
  954. case PKT_TYPE_INFO:
  955. {
  956. int conn_id;
  957. int method_id;
  958. int method_sig;
  959. if (withLinkContex)
  960. {
  961. iobuffer_format_read(pkt, "444wwww", &conn_id, &method_id, &method_sig, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  962. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  963. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  964. iobuffer_set_linkInfo(pkt, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  965. }
  966. else
  967. iobuffer_format_read(pkt, "444", &conn_id, &method_id, &method_sig);
  968. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("recv PKT_TYPE_INFO conn_id=%d method_id=%d method_sig=%d, %s", conn_id, method_id, method_sig, linkStr);
  969. on_info(tbs, conn, conn_id, method_id, method_sig, &pkt);
  970. }
  971. break;
  972. case PKT_TYPE_REQ:
  973. {
  974. int conn_id;
  975. int tsx_id;
  976. int method_id;
  977. int method_sig;
  978. int timeout;
  979. if (withLinkContex)
  980. {
  981. iobuffer_format_read(pkt, "44444wwww", &conn_id, &tsx_id, &method_id, &method_sig, &timeout, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  982. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  983. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  984. iobuffer_set_linkInfo(pkt, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  985. }
  986. else
  987. iobuffer_format_read(pkt, "44444", &conn_id, &tsx_id, &method_id, &method_sig, &timeout);
  988. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("recv PKT_TYPE_REQ conn_id=%d tsx_id=%d method_id=%d method_sig=%d timeout=%d, %s", conn_id, tsx_id, method_id, method_sig, timeout, linkStr);
  989. on_req(tbs, conn, conn_id, tsx_id, method_id, method_sig, timeout, &pkt);
  990. }
  991. break;
  992. case PKT_TYPE_SESSION:
  993. {
  994. int tsx_id;
  995. wchar_t *wentity_name;
  996. wchar_t *wfunction_name;
  997. wchar_t *wclass_name;
  998. char *entity_name;
  999. char *function_name;
  1000. char *class_name;
  1001. int n;
  1002. if (withLinkContex)
  1003. {
  1004. iobuffer_format_read(pkt, "4wwwwwww", &tsx_id, &wentity_name, &wfunction_name, &wclass_name, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  1005. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  1006. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  1007. }
  1008. else
  1009. iobuffer_format_read(pkt, "4www", &tsx_id, &wentity_name, &wfunction_name, &wclass_name);
  1010. n = WideCharToMultiByte(CP_ACP, 0, wentity_name, -1, NULL, 0, NULL, NULL);
  1011. entity_name = (char *)malloc(n);
  1012. WideCharToMultiByte(CP_ACP, 0, wentity_name, -1, entity_name, n, NULL, NULL);
  1013. FREE(wentity_name);
  1014. n = WideCharToMultiByte(CP_ACP, 0, wfunction_name, -1, NULL, 0, NULL, NULL);
  1015. function_name = (char *)malloc(n);
  1016. WideCharToMultiByte(CP_ACP, 0, wfunction_name, -1, function_name, n, NULL, NULL);
  1017. FREE(wfunction_name);
  1018. n = WideCharToMultiByte(CP_ACP, 0, wclass_name, -1, NULL, 0, NULL, NULL);
  1019. class_name = (char *)malloc(n);
  1020. WideCharToMultiByte(CP_ACP, 0, wclass_name, -1, class_name, n, NULL, NULL);
  1021. FREE(wclass_name);
  1022. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("recv PKT_TYPE_SESSION tsx_id=%d entity_name=%s function_name=%s class_name=%s", tsx_id, entity_name, function_name, class_name);
  1023. on_session(tbs, conn, tsx_id, entity_name, function_name, class_name);
  1024. if (entity_name)
  1025. free(entity_name);
  1026. if (function_name)
  1027. free(function_name);
  1028. if (class_name)
  1029. free(class_name);
  1030. }
  1031. break;
  1032. case PKT_TYPE_SESSIONEND:
  1033. {
  1034. int conn_id;
  1035. if (withLinkContex)
  1036. {
  1037. iobuffer_format_read(pkt, "4wwww", &conn_id, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  1038. if(g_postlink) linkId = g_postlink(cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  1039. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  1040. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  1041. }
  1042. else
  1043. iobuffer_format_read(pkt, "4", &conn_id);
  1044. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("recv PKT_TYPE_SESSIONEND conn_id=%d, %s", conn_id, linkStr);
  1045. on_session_end(tbs, conn, conn_id);
  1046. }
  1047. break;
  1048. case PKT_TYPE_REGISTER_EVENT:
  1049. {
  1050. int register_id;
  1051. wchar_t *wentity_name;
  1052. char *entity_name;
  1053. wchar_t *wfunction_name;
  1054. char *function_name;
  1055. int n;
  1056. if (withLinkContex)
  1057. {
  1058. iobuffer_format_read(pkt, "4wwwwww", &register_id, &wentity_name, &wfunction_name, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  1059. if(g_postlink) linkId = g_postlink(cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  1060. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  1061. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  1062. }
  1063. else
  1064. iobuffer_format_read(pkt, "4ww", &register_id, &wentity_name, &wfunction_name);
  1065. n = WideCharToMultiByte(CP_ACP, 0, wentity_name, -1, NULL, 0, NULL, NULL);
  1066. entity_name = (char *)malloc(n);
  1067. WideCharToMultiByte(CP_ACP, 0, wentity_name, -1, entity_name, n, NULL, NULL);
  1068. FREE(wentity_name);
  1069. n = WideCharToMultiByte(CP_ACP, 0, wfunction_name, -1, NULL, 0, NULL, NULL);
  1070. function_name = (char*)malloc(n);
  1071. WideCharToMultiByte(CP_ACP, 0, wfunction_name, -1, function_name, n, NULL, NULL);
  1072. FREE(wfunction_name);
  1073. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("recv PKT_TYPE_REGISTER_EVENT register_id=%d, entity_name=%s, function_name=%s", register_id, entity_name, function_name);
  1074. on_register_event(tbs, conn, register_id, entity_name, function_name);
  1075. if (entity_name)
  1076. free(entity_name);
  1077. if (function_name)
  1078. free(function_name);
  1079. }
  1080. break;
  1081. case PKT_TYPE_UNREGISTER_EVENT:
  1082. {
  1083. int register_id;
  1084. if (withLinkContex)
  1085. {
  1086. iobuffer_format_read(pkt, "4wwww", &register_id, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  1087. if(g_postlink) linkId = g_postlink(cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  1088. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  1089. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  1090. }
  1091. else
  1092. iobuffer_format_read(pkt, "4", &register_id);
  1093. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("recv PKT_TYPE_UNREGISTER_EVENT register_id=%d, %s", register_id, linkStr);
  1094. on_unregister_event(tbs, conn, register_id);
  1095. }
  1096. break;
  1097. case PKT_TYPE_LOG_EVENT:
  1098. {
  1099. int severity_level;
  1100. int user_code;
  1101. wchar_t *wmsg = NULL;
  1102. char *msg = NULL;
  1103. if (withLinkContex)
  1104. {
  1105. iobuffer_format_read(pkt, "44wwwww", &severity_level, &user_code, &wmsg, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  1106. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  1107. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  1108. }
  1109. else
  1110. iobuffer_format_read(pkt, "44w", &severity_level, &user_code, &wmsg);
  1111. if (wmsg) {
  1112. int n = WideCharToMultiByte(CP_ACP, 0, wmsg, -1, NULL, 0, NULL, NULL);
  1113. msg = (char*)malloc(n);
  1114. WideCharToMultiByte(CP_ACP, 0, wmsg, -1, msg, n, NULL, NULL);
  1115. FREE(wmsg);
  1116. }
  1117. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("recv PKT_TYPE_LOG_EVENT severity_level=%d, user_code=0x%08x, msg=%s, %s", severity_level, user_code, msg ? msg : "<null>", linkStr);
  1118. linkContext t_Context(cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  1119. on_log_event(tbs, conn, severity_level, user_code, msg, t_Context);
  1120. if (msg)
  1121. free(msg);
  1122. }
  1123. break;
  1124. case PKT_TYPE_LOG_WARN:
  1125. {
  1126. int severity_level;
  1127. int user_code;
  1128. wchar_t *wmsg = NULL;
  1129. char *msg = NULL;
  1130. if (withLinkContex)
  1131. {
  1132. iobuffer_format_read(pkt, "44wwwww", &severity_level, &user_code, &wmsg, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  1133. if(g_postlink) linkId = g_postlink(cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  1134. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  1135. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  1136. }
  1137. else
  1138. iobuffer_format_read(pkt, "44w", &severity_level, &user_code, &wmsg);
  1139. if (wmsg) {
  1140. int n = WideCharToMultiByte(CP_ACP, 0, wmsg, -1, NULL, 0, NULL, NULL);
  1141. msg = (char*)malloc(n);
  1142. WideCharToMultiByte(CP_ACP, 0, wmsg, -1, msg, n, NULL, NULL);
  1143. FREE(wmsg);
  1144. }
  1145. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("recv PKT_TYPE_LOG_WARN severity_level=%d, user_code=0x%08x, msg=%s, %s", severity_level, user_code, msg ? msg : "<null>", linkStr);
  1146. linkContext t_Context(cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  1147. on_log_warn(tbs, conn, severity_level, user_code, msg, t_Context);
  1148. if (msg)
  1149. free(msg);
  1150. }
  1151. break;
  1152. case PKT_TYPE_SET_VAR_REQ:
  1153. {
  1154. int tsx_id = 0;
  1155. wchar_t *wname = NULL;
  1156. wchar_t *wvalue = NULL;
  1157. char *name = NULL;
  1158. char *value = NULL;
  1159. if (withLinkContex)
  1160. {
  1161. iobuffer_format_read(pkt, "4wwwwww", &tsx_id, &wname, &wvalue, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  1162. if(g_postlink) linkId = g_postlink(cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  1163. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  1164. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  1165. }
  1166. else
  1167. iobuffer_format_read(pkt, "4ww", &tsx_id, &wname, &wvalue, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  1168. if (wname)
  1169. {
  1170. int n = WideCharToMultiByte(CP_ACP, 0, wname, -1, NULL, 0, NULL, NULL);
  1171. name = (char*)malloc(n);
  1172. WideCharToMultiByte(CP_ACP, 0, wname, -1, name, n, NULL, NULL);
  1173. FREE(wname);
  1174. }
  1175. if (wvalue)
  1176. {
  1177. int n = WideCharToMultiByte(CP_ACP, 0, wvalue, -1, NULL, 0, NULL, NULL);
  1178. value = (char*)malloc(n);
  1179. WideCharToMultiByte(CP_ACP, 0, wvalue, -1, value, n, NULL, NULL);
  1180. FREE(wvalue);
  1181. }
  1182. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("recv PKT_TYPE_SET_VAR_REQ tsx_id=%d, name=%s, value=%s, %s"
  1183. , tsx_id, name ? name : "<null>", value ? value : "<null>", linkStr);
  1184. on_set_var_req(tbs, conn, tsx_id, name, value);
  1185. if (name)
  1186. free(name);
  1187. if (value)
  1188. free(value);
  1189. }
  1190. break;
  1191. case PKT_TYPE_GET_VAR_REQ:
  1192. {
  1193. int tsx_id = 0;
  1194. wchar_t *wname = NULL;
  1195. char *name = NULL;
  1196. if (withLinkContex)
  1197. {
  1198. iobuffer_format_read(pkt, "4wwwww", &tsx_id, &wname, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  1199. if(g_postlink) linkId = g_postlink(cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  1200. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  1201. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  1202. }
  1203. else
  1204. iobuffer_format_read(pkt, "4w", &tsx_id, &wname);
  1205. if (wname)
  1206. {
  1207. int n = WideCharToMultiByte(CP_ACP, 0, wname, -1, NULL, 0, NULL, NULL);
  1208. name = (char*)malloc(n);
  1209. WideCharToMultiByte(CP_ACP, 0, wname, -1, name, n, NULL, NULL);
  1210. FREE(wname);
  1211. }
  1212. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("recv PKT_TYPE_GET_VAR_REQ tsx_id=%d, name=%s, %s", tsx_id, name ? name : "<null>", linkStr);
  1213. on_get_var_req(tbs, conn, tsx_id, name);
  1214. if (name)
  1215. free(name);
  1216. }
  1217. break;
  1218. default:
  1219. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("recv unknown pkt type: %d", type);
  1220. //assert(0);
  1221. break;
  1222. }
  1223. *p_pkt = NULL;
  1224. if (pkt)
  1225. iobuffer_dec_ref(pkt);
  1226. }
  1227. static void on_read(sp_tbs_t *tbs, sock_connection *conn)
  1228. {
  1229. if (conn->rx_state == RECV_STATE_HEADER) {
  1230. int t = recv(conn->fd, &conn->rx_hdr_buf[conn->rx_hdr_buf_len], RX_BUF_SIZE-conn->rx_hdr_buf_len, 0);
  1231. if (t > 0) {
  1232. int offset = 0;
  1233. conn->rx_hdr_buf_len += t;
  1234. while (conn->rx_hdr_buf_len-offset >= HDR_LEN) {
  1235. iobuffer_t *pkt;
  1236. memcpy(&conn->rx_header_len, conn->rx_hdr_buf+offset, HDR_LEN);
  1237. conn->rx_header_len += 4; // fixed hdr not include type!!!
  1238. offset += HDR_LEN;
  1239. pkt = iobuffer_create(-1, conn->rx_header_len);
  1240. if (conn->rx_hdr_buf_len-offset >= conn->rx_header_len) {
  1241. memcpy(iobuffer_data(pkt, -1), conn->rx_hdr_buf+offset, conn->rx_header_len);
  1242. offset += conn->rx_header_len;
  1243. iobuffer_push_count(pkt, conn->rx_header_len);
  1244. process_tcp_pkt(tbs, conn, &pkt);
  1245. if (pkt)
  1246. iobuffer_dec_ref(pkt);
  1247. } else {
  1248. memcpy(iobuffer_data(pkt, -1), conn->rx_hdr_buf+offset, conn->rx_hdr_buf_len-offset);
  1249. iobuffer_push_count(pkt, conn->rx_hdr_buf_len-offset);
  1250. offset = conn->rx_hdr_buf_len;
  1251. TOOLKIT_ASSERT(conn->rx_pkt == NULL);
  1252. conn->rx_pkt = pkt;
  1253. conn->rx_state = RECV_STATE_BODY;
  1254. }
  1255. }
  1256. if (offset == conn->rx_hdr_buf_len) {
  1257. conn->rx_hdr_buf_len = 0;
  1258. } else {
  1259. if (offset > 0) {
  1260. TOOLKIT_ASSERT(conn->rx_state == RECV_STATE_HEADER);
  1261. memmove(&conn->rx_hdr_buf[0], &conn->rx_hdr_buf[offset], conn->rx_hdr_buf_len-offset);
  1262. conn->rx_hdr_buf_len -= offset;
  1263. }
  1264. }
  1265. }
  1266. } else if (conn->rx_state == RECV_STATE_BODY) {
  1267. int offset, t;
  1268. TOOLKIT_ASSERT(conn->rx_pkt);
  1269. offset = iobuffer_get_length(conn->rx_pkt);
  1270. t = recv(conn->fd, iobuffer_data(conn->rx_pkt, -1), conn->rx_header_len-offset, 0);
  1271. if (t > 0) {
  1272. iobuffer_push_count(conn->rx_pkt, t);
  1273. if (offset+t == conn->rx_header_len) {
  1274. process_tcp_pkt(tbs, conn, &conn->rx_pkt);
  1275. if (conn->rx_pkt) {
  1276. iobuffer_dec_ref(conn->rx_pkt);
  1277. conn->rx_pkt = NULL;
  1278. }
  1279. conn->rx_hdr_buf_len = 0;
  1280. conn->rx_state = RECV_STATE_HEADER;
  1281. }
  1282. }
  1283. } else {
  1284. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("cannot go here, bug! %s, %d", _GetFileName(__FILE__), __LINE__);
  1285. TOOLKIT_ASSERT(0);
  1286. }
  1287. }
  1288. static void on_write(sp_tbs_t *tbs, sock_connection *conn)
  1289. {
  1290. if (conn->fd == INVALID_SOCKET)
  1291. return;
  1292. while (iobuffer_queue_count(conn->tx_queue) > 0) {
  1293. iobuffer_t *pkt = iobuffer_queue_head(conn->tx_queue);
  1294. int sended = 0;
  1295. int total = iobuffer_get_length(pkt);
  1296. while (sended < total) {
  1297. int t = send(conn->fd, iobuffer_data(pkt, 0), total-sended, 0);
  1298. if (t > 0) {
  1299. sended += t;
  1300. iobuffer_pop_count(pkt, t);
  1301. } else {
  1302. break;
  1303. }
  1304. }
  1305. if (sended < total) {
  1306. break;
  1307. } else {
  1308. iobuffer_queue_deque(conn->tx_queue);
  1309. iobuffer_dec_ref(pkt);
  1310. }
  1311. }
  1312. }
  1313. static void on_accept(sp_tbs_t *tbs)
  1314. {
  1315. int rc;
  1316. rc = create_connection(tbs);
  1317. if (rc != 0) {
  1318. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create connection failed! err = %d %s %d", rc, _GetFileName(__FILE__), __LINE__);
  1319. } else {
  1320. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create connection ok! %s %d", _GetFileName(__FILE__), __LINE__);
  1321. }
  1322. }
  1323. static void post_msg(sp_tbs_t *tbs, int msg, param_size_t param1, param_size_t param2)
  1324. {
  1325. cmd_entry *e = MALLOC_T(cmd_entry);
  1326. e->msg = msg;
  1327. e->param1 = param1;
  1328. e->param2 = param2;
  1329. spinlock_enter(&tbs->cmd_list_lock, -1);
  1330. list_add_tail(&e->entry, &tbs->cmd_list);
  1331. spinlock_leave(&tbs->cmd_list_lock);
  1332. ReleaseSemaphore(tbs->conn_evt[MSG_EVT_IDX], 1, NULL);
  1333. }
  1334. static unsigned int __stdcall server_proc(void *arg)
  1335. {
  1336. sp_tbs_t *tbs = (sp_tbs_t*)arg;
  1337. struct sockaddr_in addr = {0};
  1338. int istop = 0;
  1339. int fixed_conn;
  1340. TOOLKIT_ASSERT(tbs->server_fd == INVALID_SOCKET);
  1341. tbs->server_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  1342. if (tbs->server_fd == INVALID_SOCKET) {
  1343. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create list fd socket failed! %s %d, LastError=%d", _GetFileName(__FILE__), __LINE__, WSAGetLastError());
  1344. tbs->ready_evt_result = Error_Resource;
  1345. goto on_error;
  1346. }
  1347. {
  1348. long val = 1;
  1349. setsockopt(tbs->server_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&val, sizeof(val));
  1350. }
  1351. addr.sin_family = AF_INET;
  1352. addr.sin_addr.s_addr = tbs->server_ip;
  1353. addr.sin_port = tbs->server_port;
  1354. if (bind(tbs->server_fd, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
  1355. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("bind address failed! %s %d, LastError=%d", _GetFileName(__FILE__), __LINE__, WSAGetLastError());
  1356. tbs->ready_evt_result = Error_AlreadyExist;
  1357. goto on_error;
  1358. }
  1359. if (listen(tbs->server_fd, 5) != 0) {
  1360. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("winsock::listen failed! %s %d, LastError=%d", _GetFileName(__FILE__), __LINE__, WSAGetLastError());
  1361. tbs->ready_evt_result = Error_AlreadyExist;
  1362. goto on_error;
  1363. }
  1364. TOOLKIT_ASSERT(tbs->conn_evt[SRV_EVT_IDX] == NULL);
  1365. tbs->conn_evt[SRV_EVT_IDX] = WSACreateEvent();
  1366. WSAEventSelect(tbs->server_fd, tbs->conn_evt[SRV_EVT_IDX], FD_ACCEPT | FD_CLOSE);
  1367. tbs->conn_cnt++;
  1368. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("start server ok!");
  1369. tbs->ready_evt_result = 0;
  1370. SetEvent(tbs->ready_evt);
  1371. fixed_conn = tbs->conn_cnt;
  1372. while (!istop || tbs->conn_cnt > fixed_conn) {
  1373. DWORD evt_cnt = (DWORD)tbs->conn_cnt;
  1374. DWORD dwRet = WaitForMultipleObjects(evt_cnt, &tbs->conn_evt[0], FALSE, MAX_TIMEOUT);
  1375. if (dwRet == WAIT_TIMEOUT) {
  1376. continue;
  1377. } else if (dwRet == WAIT_OBJECT_0+MSG_EVT_IDX) { // cmd
  1378. cmd_entry *e;
  1379. spinlock_enter(&tbs->cmd_list_lock, -1);
  1380. e = list_first_entry(&tbs->cmd_list, cmd_entry, entry);
  1381. list_del(&e->entry);
  1382. spinlock_leave(&tbs->cmd_list_lock);
  1383. switch (e->msg) {
  1384. case MSG_STOP:
  1385. {
  1386. on_stop(tbs); // ...stop
  1387. istop++;
  1388. }
  1389. break;
  1390. case MSG_UAC_ON_CONNECT:
  1391. {
  1392. sub_session *session = (sub_session*)e->param1;
  1393. int error = e->param2;
  1394. uac_on_connect(tbs, session->conn, session, error);
  1395. }
  1396. break;
  1397. case MSG_UAC_ON_DESTROY:
  1398. {
  1399. sub_session *session = (sub_session*)e->param1;
  1400. uac_on_destroy(tbs, session->conn, session);
  1401. }
  1402. break;
  1403. case MSG_UAC_ON_CLOSE:
  1404. {
  1405. sub_session *session = (sub_session*)e->param1;
  1406. int error = e->param2;
  1407. uac_on_close(tbs, session->conn, session, error);
  1408. }
  1409. break;
  1410. case MSG_UAC_ON_ANS:
  1411. {
  1412. sub_session *session = (sub_session*)e->param1;
  1413. iobuffer_t *ans_pkt = (iobuffer_t*)e->param2;
  1414. int tsx_id;
  1415. int error;
  1416. int end;
  1417. int user_error;
  1418. char* msg_str = NULL;
  1419. iobuffer_format_read(ans_pkt, "4444s", &tsx_id, &error, &user_error, &end, &msg_str);
  1420. uac_on_ans(tbs, session->conn, session, tsx_id, error, user_error, msg_str, end, &ans_pkt);
  1421. if (ans_pkt)
  1422. iobuffer_dec_ref(ans_pkt);
  1423. if (msg_str)
  1424. free(msg_str);
  1425. }
  1426. break;
  1427. case MSG_ON_EVENT:
  1428. {
  1429. reg_entry *entry = (reg_entry*)e->param1;
  1430. iobuffer_t *evt_pkt = (iobuffer_t *)e->param2;
  1431. post_event(tbs, entry, 0, entry->register_id, &evt_pkt);
  1432. if (evt_pkt)
  1433. iobuffer_dec_ref(evt_pkt);
  1434. }
  1435. break;
  1436. default:
  1437. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unknown msg type! %s %d", _GetFileName(__FILE__), __LINE__);
  1438. TOOLKIT_ASSERT(0);
  1439. break;
  1440. }
  1441. free(e);
  1442. } else if (dwRet == WAIT_OBJECT_0 + SRV_EVT_IDX) { //
  1443. WSANETWORKEVENTS netevents;
  1444. if (WSAEnumNetworkEvents(tbs->server_fd, tbs->conn_evt[SRV_EVT_IDX], &netevents) != SOCKET_ERROR) {
  1445. if (netevents.lNetworkEvents & FD_ACCEPT) {
  1446. if (netevents.iErrorCode[FD_ACCEPT_BIT] == 0) {
  1447. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("FD_ACCEPT trigger!");
  1448. on_accept(tbs);
  1449. } else {
  1450. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("listen accept error bit! %s, %d", _GetFileName(__FILE__), __LINE__);
  1451. }
  1452. }
  1453. if (netevents.lNetworkEvents & FD_CLOSE) {
  1454. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("listen socket closed detected! %s, %d", _GetFileName(__FILE__), __LINE__);
  1455. break;
  1456. }
  1457. } else {
  1458. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("WSAEnumNetworkEvents failed, LastError=%d", WSAGetLastError());
  1459. }
  1460. } else if (dwRet < WAIT_OBJECT_0 + evt_cnt) {
  1461. WSANETWORKEVENTS netevents;
  1462. int idx = dwRet - WAIT_OBJECT_0;
  1463. sock_connection *conn = tbs->conn[idx];
  1464. TOOLKIT_ASSERT(conn);
  1465. if (WSAEnumNetworkEvents(conn->fd, tbs->conn_evt[idx], &netevents) != SOCKET_ERROR) {
  1466. if (netevents.lNetworkEvents & FD_READ) {
  1467. if (netevents.iErrorCode[FD_READ_BIT] == 0) {
  1468. on_read(tbs, conn);
  1469. }
  1470. }
  1471. if (netevents.lNetworkEvents & FD_WRITE) {
  1472. if (netevents.iErrorCode[FD_WRITE_BIT] == 0) {
  1473. on_write(tbs, conn);
  1474. }
  1475. }
  1476. if (netevents.lNetworkEvents & FD_CLOSE) {
  1477. on_close(tbs, conn);
  1478. }
  1479. }
  1480. } else {
  1481. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unexpected dwRet! %s %d", _GetFileName(__FILE__), __LINE__);
  1482. break;
  1483. }
  1484. }
  1485. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("tbs server thread exit!");
  1486. on_error:
  1487. if (tbs->server_fd != INVALID_SOCKET) {
  1488. if (tbs->conn_evt[SRV_EVT_IDX])
  1489. WSAEventSelect(tbs->server_fd, tbs->conn_evt[SRV_EVT_IDX], 0);
  1490. closesocket(tbs->server_fd);
  1491. tbs->server_fd = INVALID_SOCKET;
  1492. }
  1493. if (tbs->conn_evt[SRV_EVT_IDX]) {
  1494. WSACloseEvent(tbs->conn_evt[SRV_EVT_IDX]);
  1495. tbs->conn_evt[SRV_EVT_IDX] = NULL;
  1496. tbs->conn_cnt--;
  1497. }
  1498. if (tbs->ready_evt_result) {
  1499. SetEvent(tbs->ready_evt);
  1500. }
  1501. return 0;
  1502. }
  1503. int sp_tbs_create(sp_ses_mgr_t *ses_mgr, const char *ipaddr, unsigned short port, sp_tbs_t **p_tbs)
  1504. {
  1505. sp_tbs_t *tbs;
  1506. sp_svc_t *svc = sp_ses_mgr_get_svc(ses_mgr);
  1507. TOOLKIT_ASSERT(ipaddr);
  1508. TOOLKIT_ASSERT(ses_mgr);
  1509. tbs = ZALLOC_T(sp_tbs_t);
  1510. tbs->conn_evt[0] = CreateSemaphoreA(NULL, 0, 0x7fffffff, NULL);
  1511. tbs->ready_evt = CreateEventA(NULL, TRUE, FALSE, NULL);
  1512. sp_log_client_create(svc, sp_svc_get_iom(svc), &tbs->log_client);
  1513. tbs->conn_cnt = 1;
  1514. tbs->server_fd = INVALID_SOCKET;
  1515. tbs->server_ip = inet_addr(ipaddr);
  1516. tbs->server_port = htons(port);
  1517. tbs->sub_session_seq = (unsigned int)GetTickCount();
  1518. INIT_LIST_HEAD(&tbs->cmd_list);
  1519. spinlock_init(&tbs->cmd_list_lock);
  1520. tbs->ses_mgr = ses_mgr;
  1521. sp_var_client_create(svc, &tbs->var_client);
  1522. *p_tbs = tbs;
  1523. return 0;
  1524. }
  1525. int sp_tbs_start(sp_tbs_t *tbs)
  1526. {
  1527. if (tbs->work_thread) {
  1528. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("may be already started! %s %d", _GetFileName(__FILE__), __LINE__);
  1529. return Error_Duplication;
  1530. }
  1531. tbs->ready_evt_result = 0;
  1532. ResetEvent(tbs->ready_evt);
  1533. tbs->work_thread = (HANDLE)_beginthreadex(NULL, 0, &server_proc, tbs, 0, (unsigned*)&tbs->work_thread_id);
  1534. if (!tbs->work_thread) {
  1535. return Error_Resource;
  1536. }
  1537. WaitForSingleObject(tbs->ready_evt, INFINITE);
  1538. if (tbs->ready_evt_result) {
  1539. CloseHandle(tbs->work_thread);
  1540. tbs->work_thread = NULL;
  1541. }
  1542. return tbs->ready_evt_result;
  1543. }
  1544. void sp_tbs_stop(sp_tbs_t *tbs)
  1545. {
  1546. TOOLKIT_ASSERT(tbs->work_thread);
  1547. post_msg(tbs, MSG_STOP, 0, 0);
  1548. WaitForSingleObject(tbs->work_thread, INFINITE);
  1549. CloseHandle(tbs->work_thread);
  1550. tbs->work_thread = NULL;
  1551. }
  1552. void sp_tbs_destroy(sp_tbs_t *tbs)
  1553. {
  1554. TOOLKIT_ASSERT(tbs->conn_cnt == 1);
  1555. TOOLKIT_ASSERT(tbs->server_fd == INVALID_SOCKET);
  1556. CloseHandle(tbs->conn_evt[0]);
  1557. CloseHandle(tbs->ready_evt);
  1558. sp_log_client_destroy(tbs->log_client);
  1559. sp_var_client_destroy(tbs->var_client);
  1560. free(tbs);
  1561. }