sp_tbs_win.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690
  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. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("sub session created ok! ses_id = %d, tsx_id = %d", session->id, session->tsx_id);
  462. } else {
  463. sp_ses_uac_t *uac = session->uac;
  464. post_session_ack(tbs, conn, CONN_INVALID_ID, session->tsx_id, error, get_err_msg(error));
  465. session->uac = NULL;
  466. 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);
  467. if (uac) {
  468. sp_ses_uac_close(uac);
  469. sp_ses_uac_destroy(uac);
  470. }
  471. }
  472. }
  473. static void uac_on_close(sp_tbs_t *tbs, sock_connection *conn, sub_session *session, int error)
  474. {
  475. if (session->uac) {
  476. sp_ses_uac_t *uac = session->uac;
  477. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("uac on close detected! id = %d, %s %d %d", session->id, _GetFileName(__FILE__), __LINE__, error);
  478. post_session_end(tbs, conn, session->id);
  479. session->uac = NULL;
  480. if (error != Error_Closed)
  481. sp_ses_uac_close(uac);
  482. sp_ses_uac_destroy(uac);
  483. }
  484. }
  485. 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)
  486. {
  487. if(msg == NULL || strlen(msg) == 0)
  488. post_req_ack(tbs, conn, session->id, tsx_id, end, error, get_user_err_msg(user_error), ans_pkt);
  489. else
  490. post_req_ack(tbs, conn, session->id, tsx_id, end, error, CSimpleStringA2W(msg).GetData(), ans_pkt);
  491. }
  492. static void uac_on_destroy(sp_tbs_t *tbs, sock_connection *conn, sub_session *session)
  493. {
  494. destroy_sub_session(tbs, conn, session);
  495. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("destroy sub session(id:%d) uac %s %d", session->id, _GetFileName(__FILE__), __LINE__);
  496. }
  497. 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)
  498. {
  499. sp_env_t *env = sp_get_env();
  500. sp_entity_t *ent = sp_mod_mgr_find_entity_by_name(env->mod_mgr, entity_name);
  501. if (ent) {
  502. int rc;
  503. sub_session *session = MALLOC_T(sub_session);
  504. sp_ses_uac_callback cb;
  505. iobuffer_t *pkt = NULL;
  506. char *param = NULL;
  507. session->id = tbs->sub_session_seq++;
  508. session->conn = conn;
  509. session->tsx_id = tsx_id;
  510. hlist_add_head(&session->hentry, &conn->session_bucket[session->id % SESSION_BUCKET_SIZE]);
  511. conn->session_cnt++;
  512. sock_connection_inc_ref(conn);
  513. cb.user_data = session;
  514. cb.on_close = &__uac_on_close;
  515. cb.on_destroy = &__uac_on_destroy;
  516. cb.on_connect = &__uac_on_connect;
  517. rc = sp_ses_uac_create(tbs->ses_mgr, ent->mod->cfg->idx, ent->cfg->idx, &cb, &session->uac);
  518. if (rc != 0) {
  519. goto on_error;
  520. }
  521. pkt = iobuffer_create(-1, -1);
  522. if (function_name == NULL || strlen(function_name) == 0) {
  523. param = class_name;
  524. } else {
  525. param = strdup_printf("%s::%s", class_name, function_name);
  526. }
  527. iobuffer_write(pkt, IOBUF_T_STR, param, -1);
  528. if (param != class_name) {
  529. FREE(param);
  530. }
  531. rc = sp_ses_uac_async_connect(session->uac, 10000, &pkt);
  532. if (pkt)
  533. iobuffer_dec_ref(pkt);
  534. if (rc != 0) {
  535. goto on_error;
  536. }
  537. on_error:
  538. if (rc != 0) {
  539. conn->session_cnt--;
  540. hlist_del(&session->hentry);
  541. sock_connection_dec_ref(conn);
  542. free(session);
  543. } else {
  544. *p_session = session;
  545. }
  546. return rc;
  547. } else {
  548. return Error_NotExist;
  549. }
  550. }
  551. static void destroy_sub_session(sp_tbs_t *tbs, sock_connection *conn, sub_session *session)
  552. {
  553. conn->session_cnt--;
  554. hlist_del(&session->hentry);
  555. if (session->uac) {
  556. sp_ses_uac_t *uac = session->uac;
  557. session->uac = NULL;
  558. sp_ses_uac_destroy(uac);
  559. }
  560. sock_connection_dec_ref(conn);
  561. free(session);
  562. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("destroy sub session(id:%d) %s %d", session->id, _GetFileName(__FILE__), __LINE__);
  563. }
  564. 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)
  565. {
  566. if (conn->fd != INVALID_SOCKET) {
  567. int len;
  568. iobuffer_t *pkt = iobuffer_create(-1, -1);
  569. int type = PKT_TYPE_SESSIONACK;
  570. iobuffer_format_write(pkt, "4444w", &type, &conn_id, &tsx_id, &err, err_msg);
  571. len = iobuffer_get_length(pkt)-4;
  572. iobuffer_write_head(pkt, IOBUF_T_I4, &len, 0);
  573. iobuffer_queue_enqueue(conn->tx_queue, pkt);
  574. on_write(tbs, conn);
  575. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("send PKT_TYPE_SESSIONACK tsx_id=%d, err=%d", tsx_id, err);
  576. }
  577. }
  578. 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)
  579. {
  580. if (conn->fd != INVALID_SOCKET) {
  581. iobuffer_t *pkt = NULL;
  582. int len;
  583. char bend = !!end;
  584. int type = PKT_TYPE_REQACK;
  585. if (ack_pkt) {
  586. pkt = *ack_pkt;
  587. *ack_pkt = NULL;
  588. }
  589. if (!pkt) {
  590. pkt = iobuffer_create(-1, -1);
  591. }
  592. iobuffer_format_write_head(pkt, "w41444", err_msg, &err, &bend, &tsx_id, &conn_id, &type);
  593. len = iobuffer_get_length(pkt)-4;
  594. iobuffer_write_head(pkt, IOBUF_T_I4, &len, 0);
  595. iobuffer_queue_enqueue(conn->tx_queue, pkt);
  596. //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));
  597. on_write(tbs, conn);
  598. }
  599. }
  600. static void post_set_var_ack(sp_tbs_t *tbs, sock_connection *conn, int tsx_id, int err, const wchar_t *err_msg)
  601. {
  602. if (conn->fd != INVALID_SOCKET) {
  603. int len;
  604. int type = PKT_TYPE_SET_VAR_ACK;
  605. iobuffer_t *pkt = iobuffer_create(-1, -1);
  606. int conn_id = CONN_INVALID_ID;
  607. iobuffer_format_write(pkt, "4444w", &type, &conn_id, &tsx_id, &err, err_msg);
  608. len = iobuffer_get_length(pkt) - 4;
  609. iobuffer_write_head(pkt, IOBUF_T_I4, &len, 0);
  610. iobuffer_queue_enqueue(conn->tx_queue, pkt);
  611. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("send PKT_TYPE_SET_VAR_ACK tsx_id=%d, err=%d", tsx_id, err);
  612. on_write(tbs, conn);
  613. }
  614. }
  615. 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)
  616. {
  617. if (conn->fd != INVALID_SOCKET) {
  618. int len;
  619. int type = PKT_TYPE_GET_VAR_ACK;
  620. iobuffer_t *pkt = iobuffer_create(-1, -1);
  621. int conn_id = CONN_INVALID_ID;
  622. iobuffer_format_write(pkt, "4444w", &type, &conn_id, &tsx_id, &err, err == 0 ? value : err_msg);
  623. len = iobuffer_get_length(pkt) - 4;
  624. iobuffer_write_head(pkt, IOBUF_T_I4, &len, 0);
  625. iobuffer_queue_enqueue(conn->tx_queue, pkt);
  626. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("send PKT_TYPE_GET_VAR_ACK tsx_id=%d, err=%d", tsx_id, err);
  627. on_write(tbs, conn);
  628. }
  629. }
  630. static void post_session_end(sp_tbs_t *tbs, sock_connection *conn, int conn_id)
  631. {
  632. if (conn->fd != INVALID_SOCKET) {
  633. int len;
  634. iobuffer_t *pkt = iobuffer_create(-1, -1);
  635. int type = PKT_TYPE_SESSIONEND;
  636. iobuffer_format_write(pkt, "44", &type, &conn_id);
  637. len = iobuffer_get_length(pkt)-4;
  638. iobuffer_write_head(pkt, IOBUF_T_I4, &len, 0);
  639. iobuffer_queue_enqueue(conn->tx_queue, pkt);
  640. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("send PKT_TYPE_SESSIONEND");
  641. on_write(tbs, conn);
  642. }
  643. }
  644. static void on_session(sp_tbs_t *tbs, sock_connection *conn, int tsx_id, char *entity_name, char *function_name, char *class_name)
  645. {
  646. sub_session *session = NULL;
  647. int rc;
  648. rc = create_sub_session(tbs, conn, tsx_id, entity_name, function_name, class_name, &session);
  649. if (rc == 0) {
  650. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("start create sub session!");
  651. //post_session_ack(tbs, conn, session->id, tsx_id, rc, NULL);
  652. } else {
  653. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create_sub_session failed! entity: %s, err = %d %s %d",
  654. entity_name, rc, _GetFileName(__FILE__), __LINE__);
  655. post_session_ack(tbs, conn, CONN_INVALID_ID, tsx_id, rc, get_err_msg(rc));
  656. }
  657. }
  658. static reg_entry *find_reg_entry(sock_connection *conn, int register_id)
  659. {
  660. reg_entry *tpos;
  661. struct hlist_node *pos;
  662. int slot = ((unsigned int)register_id) % REGISTER_BUCKET_SIZE; // bugfix, assure slot positive
  663. hlist_for_each_entry(tpos, pos, &conn->register_bucket[slot], reg_entry, hentry) {
  664. if (tpos->register_id == register_id) {
  665. return tpos;
  666. }
  667. }
  668. return NULL;
  669. }
  670. static void post_event(sp_tbs_t *tbs, reg_entry *entry, int conn_id, int tsx_id, iobuffer_t **evt_pkt)
  671. {
  672. if (entry->conn->fd != INVALID_SOCKET) {
  673. int type;
  674. int len;
  675. iobuffer_t *pkt = *evt_pkt;
  676. *evt_pkt = NULL;
  677. type = PKT_TYPE_EVENT_DATA;
  678. iobuffer_write_head(pkt, IOBUF_T_I4, &tsx_id, 0);
  679. iobuffer_write_head(pkt, IOBUF_T_I4, &conn_id, 0);
  680. iobuffer_write_head(pkt, IOBUF_T_I4, &type, 0);
  681. len = iobuffer_get_length(pkt)-4;
  682. iobuffer_write_head(pkt, IOBUF_T_I4, &len, 0);
  683. iobuffer_queue_enqueue(entry->conn->tx_queue, pkt);
  684. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("send PKT_TYPE_EVENT_DATA tsx_id=%d", tsx_id);
  685. on_write(tbs, entry->conn);
  686. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("post event len:%d", len);
  687. }
  688. sp_bcm_listener_dec_ref(entry->listener); //@
  689. }
  690. static void __bcm_on_message_raw(sp_bcm_listener_t *listener, int from_client_id, iobuffer_t **msg_pkt, void *user_data)
  691. {
  692. reg_entry *entry = (reg_entry*)user_data;
  693. iobuffer_t *pkt = *msg_pkt;
  694. *msg_pkt = NULL;
  695. sp_bcm_listener_inc_ref(listener); //@
  696. post_msg(entry->conn->tbs, MSG_ON_EVENT, (int)entry, (int)pkt);
  697. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("post event from_client_id:%d", from_client_id);
  698. }
  699. static void __bcm_on_destroy(sp_bcm_listener_t *listener, void *user_data)
  700. {
  701. reg_entry *entry = (reg_entry*)user_data;
  702. entry->conn->register_cnt--;
  703. hlist_del(&entry->hentry);
  704. sock_connection_dec_ref(entry->conn);
  705. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unregister event ok! register_id = %d", entry->register_id);
  706. free(entry);
  707. }
  708. static void on_register_event(sp_tbs_t *tbs, sock_connection *conn, int register_id, char *entity_name, char *function_name)
  709. {
  710. sp_env_t *env = sp_get_env();
  711. sp_entity_t *ent = sp_mod_mgr_find_entity_by_name(env->mod_mgr, entity_name);
  712. if (ent) {
  713. int rc;
  714. sp_svc_t *svc = sp_ses_mgr_get_svc(tbs->ses_mgr);
  715. reg_entry *entry;
  716. sp_bcm_listener_cb cb;
  717. if (find_reg_entry(conn, register_id)) {
  718. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("register entry already exist, register id %d", register_id);
  719. return;
  720. }
  721. entry = ZALLOC_T(reg_entry);
  722. entry->register_id = register_id;
  723. entry->entity_id = ent->cfg->idx;
  724. hlist_add_head(&entry->hentry, &conn->register_bucket[((unsigned int)register_id) % REGISTER_BUCKET_SIZE]); // bugfix, assure index positive
  725. conn->register_cnt++;
  726. sock_connection_inc_ref(conn);
  727. entry->conn = conn;
  728. cb.on_message_raw = &__bcm_on_message_raw;
  729. cb.on_message = NULL;
  730. cb.on_destroy = &__bcm_on_destroy;
  731. cb.user_data = entry;
  732. rc = sp_bcm_listener_create(svc, entry->entity_id, function_name, &cb, &entry->listener);
  733. if (rc != 0) {
  734. goto on_error;
  735. }
  736. rc = sp_bcm_listener_subscribe(entry->listener, &entry->uid);
  737. if (rc != 0) {
  738. goto on_error;
  739. }
  740. on_error:
  741. if (rc != 0) {
  742. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create bcm listener failed! entity = %s, register_id = %d", ent->cfg->name, register_id);
  743. conn->register_cnt--;
  744. hlist_del_init(&entry->hentry);
  745. if (entry->listener) {
  746. sp_bcm_listener_destroy(entry->listener);
  747. }
  748. free(entry);
  749. sock_connection_dec_ref(conn);
  750. } else {
  751. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("register event for %s ok! register_id = %d", ent->cfg->name, register_id);
  752. }
  753. } else {
  754. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("cannot find entity %s!", entity_name);
  755. }
  756. }
  757. static void on_unregister_event(sp_tbs_t *tbs, sock_connection *conn, int register_id)
  758. {
  759. reg_entry *entry = find_reg_entry(conn, register_id);
  760. if (entry) {
  761. if (sp_bcm_listener_unsubscribe(entry->listener) == 0) {
  762. sp_bcm_listener_destroy(entry->listener);
  763. } else {
  764. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("entry already unregistered! register_id = %d", register_id);
  765. }
  766. } else {
  767. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("%s, entry not found, registered_id = %d", __FUNCTION__, register_id);
  768. }
  769. }
  770. 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)
  771. {
  772. sp_log_client_logWithLink(tbs->log_client, Log_Event, severity_level, 0, user_code, 0, 0, NULL == msg ? "" : msg, NULL == msg ? 0 : strlen(msg)
  773. , t_context.bussinessId.GetData(), t_context.traceId.GetData(), t_context.spanId.GetData(), t_context.parentSpanId.GetData());
  774. }
  775. 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)
  776. {
  777. sp_log_client_logWithLink(tbs->log_client, Log_Warning, severity_level, 0, user_code, 0, 0, NULL == msg ? "" : msg, NULL == msg ? 0 : strlen(msg)
  778. , t_context.bussinessId.GetData(), t_context.traceId.GetData(), t_context.spanId.GetData(), t_context.parentSpanId.GetData());
  779. }
  780. 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)
  781. {
  782. sub_session *session = find_sub_session(conn, conn_id);
  783. if (session) {
  784. if (session->uac) {
  785. int rc;
  786. sp_tsx_uac_t *tsx;
  787. sp_tsx_uac_callback cb;
  788. cb.user_data = session;
  789. cb.on_ans = &__uac_on_ans;
  790. cb.on_destroy = NULL;
  791. rc = sp_tsx_uac_create(session->uac, tsx_id, method_id, method_sig, &cb, &tsx);
  792. if (rc == 0) {
  793. rc = sp_tsx_uac_async_req(tsx, timeout, req_pkt);
  794. if (rc == 0) {
  795. WLog_DBG(TAG, "send req: tsx_id=%d, method_id=%d, method_sig=%d, pkt_size=%d",
  796. tsx_id, method_id, method_sig, *req_pkt == NULL ? 0 : iobuffer_get_length(*req_pkt));
  797. } else {
  798. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("async req tsx failed! err = %d %s %d", rc, _GetFileName(__FILE__), __LINE__);
  799. post_req_ack(tbs, conn, conn_id, tsx_id, 1, rc, get_err_msg(rc), NULL);
  800. sp_tsx_uac_destroy(tsx);
  801. }
  802. } else {
  803. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create req tsx failed! %s %d", _GetFileName(__FILE__), __LINE__);
  804. post_req_ack(tbs, conn, conn_id, tsx_id, 1, rc, get_err_msg(rc), NULL);
  805. }
  806. } else {
  807. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("session already closed! %s %d", _GetFileName(__FILE__), __LINE__);
  808. post_req_ack(tbs, conn, conn_id, tsx_id, 1, Error_NetBroken, get_err_msg(Error_NetBroken), NULL);
  809. }
  810. } else {
  811. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("cannot find session id in htable! ignored! %s %d", _GetFileName(__FILE__), __LINE__);
  812. post_req_ack(tbs, conn, conn_id, tsx_id, 1, Error_NotExist, get_err_msg(Error_NotExist), NULL);
  813. }
  814. }
  815. static void on_info(sp_tbs_t *tbs, sock_connection *conn, int conn_id, int method_id, int method_sig, iobuffer_t **info_pkt)
  816. {
  817. sub_session *session = find_sub_session(conn, conn_id);
  818. if (session) {
  819. if (session->uac) {
  820. int rc = sp_ses_uac_send_info(session->uac, method_id, method_sig, info_pkt);
  821. if (rc != 0) {
  822. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("uac send info failed! error = %d %s %d", rc, _GetFileName(__FILE__), __LINE__);
  823. }
  824. else {
  825. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("send info: method_id=%d, method_sig=%d, pkt_size=%d", method_id, method_sig,
  826. // *info_pkt == NULL ? 0 : iobuffer_get_length(*info_pkt));
  827. }
  828. } else {
  829. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("session already closed! info ignored ! %s %d", _GetFileName(__FILE__), __LINE__);
  830. }
  831. } else {
  832. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("cannot find session id in htable! ignored! %s %d", _GetFileName(__FILE__), __LINE__);
  833. }
  834. }
  835. static void on_session_end(sp_tbs_t *tbs, sock_connection *conn, int conn_id)
  836. {
  837. sub_session *session = find_sub_session(conn, conn_id);
  838. if (session) {
  839. if (session->uac) {
  840. sp_ses_uac_t *uac = session->uac;
  841. session->uac = NULL;
  842. if (sp_ses_uac_close(uac) == 0) {
  843. sp_ses_uac_destroy(uac);
  844. } else {
  845. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("duplicated uac close!");
  846. }
  847. }
  848. } else {
  849. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("cannot find session id in htable! ignored! %s %d", _GetFileName(__FILE__), __LINE__);
  850. }
  851. }
  852. static void on_stop(sp_tbs_t *tbs)
  853. {
  854. int i;
  855. WSAEventSelect(tbs->server_fd, tbs->conn_evt[SRV_EVT_IDX], 0);
  856. closesocket(tbs->server_fd);
  857. tbs->server_fd = INVALID_SOCKET;
  858. for (i = tbs->conn_cnt-1; i > SRV_EVT_IDX; --i) {
  859. sock_connection *conn = tbs->conn[i];
  860. TOOLKIT_ASSERT(conn);
  861. on_close(tbs, conn);
  862. }
  863. }
  864. static void on_close(sp_tbs_t *tbs, sock_connection *conn)
  865. {
  866. int i;
  867. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("socket on close is invoked!");
  868. if (conn->fd != INVALID_SOCKET) {
  869. WSAEventSelect(conn->fd, tbs->conn_evt[conn->idx], 0);
  870. closesocket(conn->fd);
  871. conn->fd = INVALID_SOCKET;
  872. }
  873. for (i = 0; i < SESSION_BUCKET_SIZE; ++i) {
  874. sub_session *tpos;
  875. struct hlist_node *pos, *n;
  876. hlist_for_each_entry_safe(tpos, pos, n, &conn->session_bucket[i], sub_session, hentry) {
  877. if (tpos->uac) {
  878. sp_ses_uac_t *uac = tpos->uac;
  879. tpos->uac = NULL;
  880. if (sp_ses_uac_close(uac) == 0) {
  881. sp_ses_uac_destroy(uac);
  882. } else {
  883. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("duplicated uac close! %s %d", _GetFileName(__FILE__), __LINE__);
  884. }
  885. }
  886. }
  887. }
  888. for (i = 0; i < REGISTER_BUCKET_SIZE; ++i) {
  889. reg_entry *tpos;
  890. struct hlist_node *pos, *n;
  891. hlist_for_each_entry_safe(tpos, pos, n, &conn->register_bucket[i], reg_entry, hentry) {
  892. if (tpos->listener) {
  893. if (sp_bcm_listener_unsubscribe(tpos->listener) == 0) {
  894. sp_bcm_listener_destroy(tpos->listener);
  895. }
  896. }
  897. }
  898. }
  899. sock_connection_dec_ref(conn);
  900. }
  901. static void on_set_var_req(sp_tbs_t *tbs, sock_connection *conn, int tsx_id, char *name, char *value)
  902. {
  903. int rc;
  904. if (name == NULL)
  905. {
  906. rc = Error_Param;
  907. post_set_var_ack(tbs, conn, tsx_id, rc, L"param [name] is null");
  908. return;
  909. }
  910. rc = sp_var_client_set((sp_var_client_t*)tbs->var_client, name, value, 0);
  911. post_set_var_ack(tbs, conn, tsx_id, rc, get_err_msg(rc));
  912. }
  913. static void on_get_var_req(sp_tbs_t *tbs, sock_connection *conn, int tsx_id, char *name)
  914. {
  915. int len = 260;
  916. int rc;
  917. char szTmp[260] = { 0 };
  918. wchar_t wszValue[260] = { 0 };
  919. if (name == NULL)
  920. {
  921. rc = Error_Param;
  922. post_get_var_ack(tbs, conn, tsx_id, rc, L"param [name] is null", NULL);
  923. return;
  924. }
  925. rc = sp_var_client_lock(tbs->var_client);
  926. if (rc == 0) {
  927. rc = sp_var_client_get((sp_var_client_t*)tbs->var_client, name, szTmp, &len);
  928. }
  929. sp_var_client_unlock(tbs->var_client);
  930. if (rc == 0)
  931. {
  932. len = 260;
  933. MultiByteToWideChar(CP_ACP, 0, szTmp, -1, &wszValue[0], len);
  934. post_get_var_ack(tbs, conn, tsx_id, rc, get_err_msg(rc), wszValue);
  935. }
  936. else
  937. post_get_var_ack(tbs, conn, tsx_id, rc, get_err_msg(rc), NULL);
  938. }
  939. static void process_tcp_pkt(sp_tbs_t *tbs, sock_connection *conn, iobuffer_t **p_pkt)
  940. {
  941. iobuffer_t *pkt = *p_pkt;
  942. int type;
  943. iobuffer_read(pkt, IOBUF_T_I4, &type, NULL);
  944. link_context cur;
  945. char linkStr[512] = "";
  946. bool withLinkContex = !!(type & PKT_TYPE_CONTROL_LINKCONTEXT);
  947. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("process_tcp_pkt withLinkContex:%d", withLinkContex);
  948. int linkId = 0;
  949. type = type & 0x0000FFFF; //clear control part
  950. switch (type) {
  951. case PKT_TYPE_INFO:
  952. {
  953. int conn_id;
  954. int method_id;
  955. int method_sig;
  956. if (withLinkContex)
  957. {
  958. iobuffer_format_read(pkt, "444wwww", &conn_id, &method_id, &method_sig, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  959. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  960. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  961. iobuffer_set_linkInfo(pkt, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  962. }
  963. else
  964. iobuffer_format_read(pkt, "444", &conn_id, &method_id, &method_sig);
  965. //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);
  966. on_info(tbs, conn, conn_id, method_id, method_sig, &pkt);
  967. }
  968. break;
  969. case PKT_TYPE_REQ:
  970. {
  971. int conn_id;
  972. int tsx_id;
  973. int method_id;
  974. int method_sig;
  975. int timeout;
  976. if (withLinkContex)
  977. {
  978. iobuffer_format_read(pkt, "44444wwww", &conn_id, &tsx_id, &method_id, &method_sig, &timeout, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  979. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  980. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  981. iobuffer_set_linkInfo(pkt, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  982. }
  983. else
  984. iobuffer_format_read(pkt, "44444", &conn_id, &tsx_id, &method_id, &method_sig, &timeout);
  985. //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);
  986. on_req(tbs, conn, conn_id, tsx_id, method_id, method_sig, timeout, &pkt);
  987. }
  988. break;
  989. case PKT_TYPE_SESSION:
  990. {
  991. int tsx_id;
  992. wchar_t *wentity_name;
  993. wchar_t *wfunction_name;
  994. wchar_t *wclass_name;
  995. char *entity_name;
  996. char *function_name;
  997. char *class_name;
  998. int n;
  999. if (withLinkContex)
  1000. {
  1001. iobuffer_format_read(pkt, "4wwwwwww", &tsx_id, &wentity_name, &wfunction_name, &wclass_name, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  1002. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  1003. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  1004. }
  1005. else
  1006. iobuffer_format_read(pkt, "4www", &tsx_id, &wentity_name, &wfunction_name, &wclass_name);
  1007. n = WideCharToMultiByte(CP_ACP, 0, wentity_name, -1, NULL, 0, NULL, NULL);
  1008. entity_name = (char *)malloc(n);
  1009. WideCharToMultiByte(CP_ACP, 0, wentity_name, -1, entity_name, n, NULL, NULL);
  1010. FREE(wentity_name);
  1011. n = WideCharToMultiByte(CP_ACP, 0, wfunction_name, -1, NULL, 0, NULL, NULL);
  1012. function_name = (char *)malloc(n);
  1013. WideCharToMultiByte(CP_ACP, 0, wfunction_name, -1, function_name, n, NULL, NULL);
  1014. FREE(wfunction_name);
  1015. n = WideCharToMultiByte(CP_ACP, 0, wclass_name, -1, NULL, 0, NULL, NULL);
  1016. class_name = (char *)malloc(n);
  1017. WideCharToMultiByte(CP_ACP, 0, wclass_name, -1, class_name, n, NULL, NULL);
  1018. FREE(wclass_name);
  1019. DbgWithLink(LOG_LEVEL_INFO, 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);
  1020. on_session(tbs, conn, tsx_id, entity_name, function_name, class_name);
  1021. if (entity_name)
  1022. free(entity_name);
  1023. if (function_name)
  1024. free(function_name);
  1025. if (class_name)
  1026. free(class_name);
  1027. }
  1028. break;
  1029. case PKT_TYPE_SESSIONEND:
  1030. {
  1031. int conn_id;
  1032. if (withLinkContex)
  1033. {
  1034. iobuffer_format_read(pkt, "4wwww", &conn_id, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  1035. if(g_postlink) linkId = g_postlink(cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  1036. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  1037. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  1038. }
  1039. else
  1040. iobuffer_format_read(pkt, "4", &conn_id);
  1041. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("recv PKT_TYPE_SESSIONEND conn_id=%d, %s", conn_id, linkStr);
  1042. on_session_end(tbs, conn, conn_id);
  1043. }
  1044. break;
  1045. case PKT_TYPE_REGISTER_EVENT:
  1046. {
  1047. int register_id;
  1048. wchar_t *wentity_name;
  1049. char *entity_name;
  1050. wchar_t *wfunction_name;
  1051. char *function_name;
  1052. int n;
  1053. if (withLinkContex)
  1054. {
  1055. iobuffer_format_read(pkt, "4wwwwww", &register_id, &wentity_name, &wfunction_name, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  1056. if(g_postlink) linkId = g_postlink(cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  1057. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  1058. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  1059. }
  1060. else
  1061. iobuffer_format_read(pkt, "4ww", &register_id, &wentity_name, &wfunction_name);
  1062. n = WideCharToMultiByte(CP_ACP, 0, wentity_name, -1, NULL, 0, NULL, NULL);
  1063. entity_name = (char *)malloc(n);
  1064. WideCharToMultiByte(CP_ACP, 0, wentity_name, -1, entity_name, n, NULL, NULL);
  1065. FREE(wentity_name);
  1066. n = WideCharToMultiByte(CP_ACP, 0, wfunction_name, -1, NULL, 0, NULL, NULL);
  1067. function_name = (char*)malloc(n);
  1068. WideCharToMultiByte(CP_ACP, 0, wfunction_name, -1, function_name, n, NULL, NULL);
  1069. FREE(wfunction_name);
  1070. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("recv PKT_TYPE_REGISTER_EVENT register_id=%d, entity_name=%s, function_name=%s", register_id, entity_name, function_name);
  1071. on_register_event(tbs, conn, register_id, entity_name, function_name);
  1072. if (entity_name)
  1073. free(entity_name);
  1074. if (function_name)
  1075. free(function_name);
  1076. }
  1077. break;
  1078. case PKT_TYPE_UNREGISTER_EVENT:
  1079. {
  1080. int register_id;
  1081. if (withLinkContex)
  1082. {
  1083. iobuffer_format_read(pkt, "4wwww", &register_id, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  1084. if(g_postlink) linkId = g_postlink(cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  1085. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  1086. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  1087. }
  1088. else
  1089. iobuffer_format_read(pkt, "4", &register_id);
  1090. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("recv PKT_TYPE_UNREGISTER_EVENT register_id=%d, %s", register_id, linkStr);
  1091. on_unregister_event(tbs, conn, register_id);
  1092. }
  1093. break;
  1094. case PKT_TYPE_LOG_EVENT:
  1095. {
  1096. int severity_level;
  1097. int user_code;
  1098. wchar_t *wmsg = NULL;
  1099. char *msg = NULL;
  1100. if (withLinkContex)
  1101. {
  1102. iobuffer_format_read(pkt, "44wwwww", &severity_level, &user_code, &wmsg, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  1103. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  1104. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  1105. }
  1106. else
  1107. iobuffer_format_read(pkt, "44w", &severity_level, &user_code, &wmsg);
  1108. if (wmsg) {
  1109. int n = WideCharToMultiByte(CP_ACP, 0, wmsg, -1, NULL, 0, NULL, NULL);
  1110. msg = (char*)malloc(n);
  1111. WideCharToMultiByte(CP_ACP, 0, wmsg, -1, msg, n, NULL, NULL);
  1112. FREE(wmsg);
  1113. }
  1114. //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);
  1115. linkContext t_Context(cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  1116. on_log_event(tbs, conn, severity_level, user_code, msg, t_Context);
  1117. if (msg)
  1118. free(msg);
  1119. }
  1120. break;
  1121. case PKT_TYPE_LOG_WARN:
  1122. {
  1123. int severity_level;
  1124. int user_code;
  1125. wchar_t *wmsg = NULL;
  1126. char *msg = NULL;
  1127. if (withLinkContex)
  1128. {
  1129. iobuffer_format_read(pkt, "44wwwww", &severity_level, &user_code, &wmsg, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  1130. if(g_postlink) linkId = g_postlink(cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  1131. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  1132. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  1133. }
  1134. else
  1135. iobuffer_format_read(pkt, "44w", &severity_level, &user_code, &wmsg);
  1136. if (wmsg) {
  1137. int n = WideCharToMultiByte(CP_ACP, 0, wmsg, -1, NULL, 0, NULL, NULL);
  1138. msg = (char*)malloc(n);
  1139. WideCharToMultiByte(CP_ACP, 0, wmsg, -1, msg, n, NULL, NULL);
  1140. FREE(wmsg);
  1141. }
  1142. //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);
  1143. linkContext t_Context(cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  1144. on_log_warn(tbs, conn, severity_level, user_code, msg, t_Context);
  1145. if (msg)
  1146. free(msg);
  1147. }
  1148. break;
  1149. case PKT_TYPE_SET_VAR_REQ:
  1150. {
  1151. int tsx_id = 0;
  1152. wchar_t *wname = NULL;
  1153. wchar_t *wvalue = NULL;
  1154. char *name = NULL;
  1155. char *value = NULL;
  1156. if (withLinkContex)
  1157. {
  1158. iobuffer_format_read(pkt, "4wwwwww", &tsx_id, &wname, &wvalue, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  1159. if(g_postlink) linkId = g_postlink(cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  1160. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  1161. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  1162. }
  1163. else
  1164. iobuffer_format_read(pkt, "4ww", &tsx_id, &wname, &wvalue, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  1165. if (wname)
  1166. {
  1167. int n = WideCharToMultiByte(CP_ACP, 0, wname, -1, NULL, 0, NULL, NULL);
  1168. name = (char*)malloc(n);
  1169. WideCharToMultiByte(CP_ACP, 0, wname, -1, name, n, NULL, NULL);
  1170. FREE(wname);
  1171. }
  1172. if (wvalue)
  1173. {
  1174. int n = WideCharToMultiByte(CP_ACP, 0, wvalue, -1, NULL, 0, NULL, NULL);
  1175. value = (char*)malloc(n);
  1176. WideCharToMultiByte(CP_ACP, 0, wvalue, -1, value, n, NULL, NULL);
  1177. FREE(wvalue);
  1178. }
  1179. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("recv PKT_TYPE_SET_VAR_REQ tsx_id=%d, name=%s, value=%s, %s"
  1180. , tsx_id, name ? name : "<null>", value ? value : "<null>", linkStr);
  1181. on_set_var_req(tbs, conn, tsx_id, name, value);
  1182. if (name)
  1183. free(name);
  1184. if (value)
  1185. free(value);
  1186. }
  1187. break;
  1188. case PKT_TYPE_GET_VAR_REQ:
  1189. {
  1190. int tsx_id = 0;
  1191. wchar_t *wname = NULL;
  1192. char *name = NULL;
  1193. if (withLinkContex)
  1194. {
  1195. iobuffer_format_read(pkt, "4wwwww", &tsx_id, &wname, &cur.wbusinessId, &cur.wtraceId, &cur.wspanId, &cur.wparentSpanId);
  1196. if(g_postlink) linkId = g_postlink(cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA());
  1197. sprintf_s(linkStr, sizeof(linkStr), "withLinkContex:%d linkcontext:%s-%s-%s-%s-%d",
  1198. withLinkContex, cur.businessIdWtoA(), cur.traceIdWtoA(), cur.spanIdWtoA(), cur.parentSpanIdWtoA(), linkId);
  1199. }
  1200. else
  1201. iobuffer_format_read(pkt, "4w", &tsx_id, &wname);
  1202. if (wname)
  1203. {
  1204. int n = WideCharToMultiByte(CP_ACP, 0, wname, -1, NULL, 0, NULL, NULL);
  1205. name = (char*)malloc(n);
  1206. WideCharToMultiByte(CP_ACP, 0, wname, -1, name, n, NULL, NULL);
  1207. FREE(wname);
  1208. }
  1209. 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);
  1210. on_get_var_req(tbs, conn, tsx_id, name);
  1211. if (name)
  1212. free(name);
  1213. }
  1214. break;
  1215. default:
  1216. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("recv unknown pkt type: %d", type);
  1217. //assert(0);
  1218. break;
  1219. }
  1220. *p_pkt = NULL;
  1221. if (pkt)
  1222. iobuffer_dec_ref(pkt);
  1223. }
  1224. static void on_read(sp_tbs_t *tbs, sock_connection *conn)
  1225. {
  1226. if (conn->rx_state == RECV_STATE_HEADER) {
  1227. int t = recv(conn->fd, &conn->rx_hdr_buf[conn->rx_hdr_buf_len], RX_BUF_SIZE-conn->rx_hdr_buf_len, 0);
  1228. if (t > 0) {
  1229. int offset = 0;
  1230. conn->rx_hdr_buf_len += t;
  1231. while (conn->rx_hdr_buf_len-offset >= HDR_LEN) {
  1232. iobuffer_t *pkt;
  1233. memcpy(&conn->rx_header_len, conn->rx_hdr_buf+offset, HDR_LEN);
  1234. conn->rx_header_len += 4; // fixed hdr not include type!!!
  1235. offset += HDR_LEN;
  1236. pkt = iobuffer_create(-1, conn->rx_header_len);
  1237. if (conn->rx_hdr_buf_len-offset >= conn->rx_header_len) {
  1238. memcpy(iobuffer_data(pkt, -1), conn->rx_hdr_buf+offset, conn->rx_header_len);
  1239. offset += conn->rx_header_len;
  1240. iobuffer_push_count(pkt, conn->rx_header_len);
  1241. process_tcp_pkt(tbs, conn, &pkt);
  1242. if (pkt)
  1243. iobuffer_dec_ref(pkt);
  1244. } else {
  1245. memcpy(iobuffer_data(pkt, -1), conn->rx_hdr_buf+offset, conn->rx_hdr_buf_len-offset);
  1246. iobuffer_push_count(pkt, conn->rx_hdr_buf_len-offset);
  1247. offset = conn->rx_hdr_buf_len;
  1248. TOOLKIT_ASSERT(conn->rx_pkt == NULL);
  1249. conn->rx_pkt = pkt;
  1250. conn->rx_state = RECV_STATE_BODY;
  1251. }
  1252. }
  1253. if (offset == conn->rx_hdr_buf_len) {
  1254. conn->rx_hdr_buf_len = 0;
  1255. } else {
  1256. if (offset > 0) {
  1257. TOOLKIT_ASSERT(conn->rx_state == RECV_STATE_HEADER);
  1258. memmove(&conn->rx_hdr_buf[0], &conn->rx_hdr_buf[offset], conn->rx_hdr_buf_len-offset);
  1259. conn->rx_hdr_buf_len -= offset;
  1260. }
  1261. }
  1262. }
  1263. } else if (conn->rx_state == RECV_STATE_BODY) {
  1264. int offset, t;
  1265. TOOLKIT_ASSERT(conn->rx_pkt);
  1266. offset = iobuffer_get_length(conn->rx_pkt);
  1267. t = recv(conn->fd, iobuffer_data(conn->rx_pkt, -1), conn->rx_header_len-offset, 0);
  1268. if (t > 0) {
  1269. iobuffer_push_count(conn->rx_pkt, t);
  1270. if (offset+t == conn->rx_header_len) {
  1271. process_tcp_pkt(tbs, conn, &conn->rx_pkt);
  1272. if (conn->rx_pkt) {
  1273. iobuffer_dec_ref(conn->rx_pkt);
  1274. conn->rx_pkt = NULL;
  1275. }
  1276. conn->rx_hdr_buf_len = 0;
  1277. conn->rx_state = RECV_STATE_HEADER;
  1278. }
  1279. }
  1280. } else {
  1281. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("cannot go here, bug! %s, %d", _GetFileName(__FILE__), __LINE__);
  1282. TOOLKIT_ASSERT(0);
  1283. }
  1284. }
  1285. static void on_write(sp_tbs_t *tbs, sock_connection *conn)
  1286. {
  1287. if (conn->fd == INVALID_SOCKET)
  1288. return;
  1289. while (iobuffer_queue_count(conn->tx_queue) > 0) {
  1290. iobuffer_t *pkt = iobuffer_queue_head(conn->tx_queue);
  1291. int sended = 0;
  1292. int total = iobuffer_get_length(pkt);
  1293. while (sended < total) {
  1294. int t = send(conn->fd, iobuffer_data(pkt, 0), total-sended, 0);
  1295. if (t > 0) {
  1296. sended += t;
  1297. iobuffer_pop_count(pkt, t);
  1298. } else {
  1299. break;
  1300. }
  1301. }
  1302. if (sended < total) {
  1303. break;
  1304. } else {
  1305. iobuffer_queue_deque(conn->tx_queue);
  1306. iobuffer_dec_ref(pkt);
  1307. }
  1308. }
  1309. }
  1310. static void on_accept(sp_tbs_t *tbs)
  1311. {
  1312. int rc;
  1313. rc = create_connection(tbs);
  1314. if (rc != 0) {
  1315. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create connection failed! err = %d %s %d", rc, _GetFileName(__FILE__), __LINE__);
  1316. } else {
  1317. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create connection ok! %s %d", _GetFileName(__FILE__), __LINE__);
  1318. }
  1319. }
  1320. static void post_msg(sp_tbs_t *tbs, int msg, param_size_t param1, param_size_t param2)
  1321. {
  1322. cmd_entry *e = MALLOC_T(cmd_entry);
  1323. e->msg = msg;
  1324. e->param1 = param1;
  1325. e->param2 = param2;
  1326. spinlock_enter(&tbs->cmd_list_lock, -1);
  1327. list_add_tail(&e->entry, &tbs->cmd_list);
  1328. spinlock_leave(&tbs->cmd_list_lock);
  1329. ReleaseSemaphore(tbs->conn_evt[MSG_EVT_IDX], 1, NULL);
  1330. }
  1331. static unsigned int __stdcall server_proc(void *arg)
  1332. {
  1333. sp_tbs_t *tbs = (sp_tbs_t*)arg;
  1334. struct sockaddr_in addr = {0};
  1335. int istop = 0;
  1336. int fixed_conn;
  1337. TOOLKIT_ASSERT(tbs->server_fd == INVALID_SOCKET);
  1338. tbs->server_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  1339. if (tbs->server_fd == INVALID_SOCKET) {
  1340. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create list fd socket failed! %s %d, LastError=%d", _GetFileName(__FILE__), __LINE__, WSAGetLastError());
  1341. tbs->ready_evt_result = Error_Resource;
  1342. goto on_error;
  1343. }
  1344. {
  1345. long val = 1;
  1346. setsockopt(tbs->server_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&val, sizeof(val));
  1347. }
  1348. addr.sin_family = AF_INET;
  1349. addr.sin_addr.s_addr = tbs->server_ip;
  1350. addr.sin_port = tbs->server_port;
  1351. if (bind(tbs->server_fd, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
  1352. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("bind address failed! %s %d, LastError=%d", _GetFileName(__FILE__), __LINE__, WSAGetLastError());
  1353. tbs->ready_evt_result = Error_AlreadyExist;
  1354. goto on_error;
  1355. }
  1356. if (listen(tbs->server_fd, 5) != 0) {
  1357. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("winsock::listen failed! %s %d, LastError=%d", _GetFileName(__FILE__), __LINE__, WSAGetLastError());
  1358. tbs->ready_evt_result = Error_AlreadyExist;
  1359. goto on_error;
  1360. }
  1361. TOOLKIT_ASSERT(tbs->conn_evt[SRV_EVT_IDX] == NULL);
  1362. tbs->conn_evt[SRV_EVT_IDX] = WSACreateEvent();
  1363. WSAEventSelect(tbs->server_fd, tbs->conn_evt[SRV_EVT_IDX], FD_ACCEPT | FD_CLOSE);
  1364. tbs->conn_cnt++;
  1365. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("start server ok!");
  1366. tbs->ready_evt_result = 0;
  1367. SetEvent(tbs->ready_evt);
  1368. fixed_conn = tbs->conn_cnt;
  1369. while (!istop || tbs->conn_cnt > fixed_conn) {
  1370. DWORD evt_cnt = (DWORD)tbs->conn_cnt;
  1371. DWORD dwRet = WaitForMultipleObjects(evt_cnt, &tbs->conn_evt[0], FALSE, MAX_TIMEOUT);
  1372. if (dwRet == WAIT_TIMEOUT) {
  1373. continue;
  1374. } else if (dwRet == WAIT_OBJECT_0+MSG_EVT_IDX) { // cmd
  1375. cmd_entry *e;
  1376. spinlock_enter(&tbs->cmd_list_lock, -1);
  1377. e = list_first_entry(&tbs->cmd_list, cmd_entry, entry);
  1378. list_del(&e->entry);
  1379. spinlock_leave(&tbs->cmd_list_lock);
  1380. switch (e->msg) {
  1381. case MSG_STOP:
  1382. {
  1383. on_stop(tbs); // ...stop
  1384. istop++;
  1385. }
  1386. break;
  1387. case MSG_UAC_ON_CONNECT:
  1388. {
  1389. sub_session *session = (sub_session*)e->param1;
  1390. int error = e->param2;
  1391. uac_on_connect(tbs, session->conn, session, error);
  1392. }
  1393. break;
  1394. case MSG_UAC_ON_DESTROY:
  1395. {
  1396. sub_session *session = (sub_session*)e->param1;
  1397. uac_on_destroy(tbs, session->conn, session);
  1398. }
  1399. break;
  1400. case MSG_UAC_ON_CLOSE:
  1401. {
  1402. sub_session *session = (sub_session*)e->param1;
  1403. int error = e->param2;
  1404. uac_on_close(tbs, session->conn, session, error);
  1405. }
  1406. break;
  1407. case MSG_UAC_ON_ANS:
  1408. {
  1409. sub_session *session = (sub_session*)e->param1;
  1410. iobuffer_t *ans_pkt = (iobuffer_t*)e->param2;
  1411. int tsx_id;
  1412. int error;
  1413. int end;
  1414. int user_error;
  1415. char* msg_str = NULL;
  1416. iobuffer_format_read(ans_pkt, "4444s", &tsx_id, &error, &user_error, &end, &msg_str);
  1417. uac_on_ans(tbs, session->conn, session, tsx_id, error, user_error, msg_str, end, &ans_pkt);
  1418. if (ans_pkt)
  1419. iobuffer_dec_ref(ans_pkt);
  1420. if (msg_str)
  1421. free(msg_str);
  1422. }
  1423. break;
  1424. case MSG_ON_EVENT:
  1425. {
  1426. reg_entry *entry = (reg_entry*)e->param1;
  1427. iobuffer_t *evt_pkt = (iobuffer_t *)e->param2;
  1428. post_event(tbs, entry, 0, entry->register_id, &evt_pkt);
  1429. if (evt_pkt)
  1430. iobuffer_dec_ref(evt_pkt);
  1431. }
  1432. break;
  1433. default:
  1434. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unknown msg type! %s %d", _GetFileName(__FILE__), __LINE__);
  1435. TOOLKIT_ASSERT(0);
  1436. break;
  1437. }
  1438. free(e);
  1439. } else if (dwRet == WAIT_OBJECT_0 + SRV_EVT_IDX) { //
  1440. WSANETWORKEVENTS netevents;
  1441. if (WSAEnumNetworkEvents(tbs->server_fd, tbs->conn_evt[SRV_EVT_IDX], &netevents) != SOCKET_ERROR) {
  1442. if (netevents.lNetworkEvents & FD_ACCEPT) {
  1443. if (netevents.iErrorCode[FD_ACCEPT_BIT] == 0) {
  1444. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("FD_ACCEPT trigger!");
  1445. on_accept(tbs);
  1446. } else {
  1447. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("listen accept error bit! %s, %d", _GetFileName(__FILE__), __LINE__);
  1448. }
  1449. }
  1450. if (netevents.lNetworkEvents & FD_CLOSE) {
  1451. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("listen socket closed detected! %s, %d", _GetFileName(__FILE__), __LINE__);
  1452. break;
  1453. }
  1454. } else {
  1455. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("WSAEnumNetworkEvents failed, LastError=%d", WSAGetLastError());
  1456. }
  1457. } else if (dwRet < WAIT_OBJECT_0 + evt_cnt) {
  1458. WSANETWORKEVENTS netevents;
  1459. int idx = dwRet - WAIT_OBJECT_0;
  1460. sock_connection *conn = tbs->conn[idx];
  1461. TOOLKIT_ASSERT(conn);
  1462. if (WSAEnumNetworkEvents(conn->fd, tbs->conn_evt[idx], &netevents) != SOCKET_ERROR) {
  1463. if (netevents.lNetworkEvents & FD_READ) {
  1464. if (netevents.iErrorCode[FD_READ_BIT] == 0) {
  1465. on_read(tbs, conn);
  1466. }
  1467. }
  1468. if (netevents.lNetworkEvents & FD_WRITE) {
  1469. if (netevents.iErrorCode[FD_WRITE_BIT] == 0) {
  1470. on_write(tbs, conn);
  1471. }
  1472. }
  1473. if (netevents.lNetworkEvents & FD_CLOSE) {
  1474. on_close(tbs, conn);
  1475. }
  1476. }
  1477. } else {
  1478. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unexpected dwRet! %s %d", _GetFileName(__FILE__), __LINE__);
  1479. break;
  1480. }
  1481. }
  1482. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("tbs server thread exit!");
  1483. on_error:
  1484. if (tbs->server_fd != INVALID_SOCKET) {
  1485. if (tbs->conn_evt[SRV_EVT_IDX])
  1486. WSAEventSelect(tbs->server_fd, tbs->conn_evt[SRV_EVT_IDX], 0);
  1487. closesocket(tbs->server_fd);
  1488. tbs->server_fd = INVALID_SOCKET;
  1489. }
  1490. if (tbs->conn_evt[SRV_EVT_IDX]) {
  1491. WSACloseEvent(tbs->conn_evt[SRV_EVT_IDX]);
  1492. tbs->conn_evt[SRV_EVT_IDX] = NULL;
  1493. tbs->conn_cnt--;
  1494. }
  1495. if (tbs->ready_evt_result) {
  1496. SetEvent(tbs->ready_evt);
  1497. }
  1498. return 0;
  1499. }
  1500. int sp_tbs_create(sp_ses_mgr_t *ses_mgr, const char *ipaddr, unsigned short port, sp_tbs_t **p_tbs)
  1501. {
  1502. sp_tbs_t *tbs;
  1503. sp_svc_t *svc = sp_ses_mgr_get_svc(ses_mgr);
  1504. TOOLKIT_ASSERT(ipaddr);
  1505. TOOLKIT_ASSERT(ses_mgr);
  1506. tbs = ZALLOC_T(sp_tbs_t);
  1507. tbs->conn_evt[0] = CreateSemaphoreA(NULL, 0, 0x7fffffff, NULL);
  1508. tbs->ready_evt = CreateEventA(NULL, TRUE, FALSE, NULL);
  1509. sp_log_client_create(svc, sp_svc_get_iom(svc), &tbs->log_client);
  1510. tbs->conn_cnt = 1;
  1511. tbs->server_fd = INVALID_SOCKET;
  1512. tbs->server_ip = inet_addr(ipaddr);
  1513. tbs->server_port = htons(port);
  1514. tbs->sub_session_seq = (unsigned int)GetTickCount();
  1515. INIT_LIST_HEAD(&tbs->cmd_list);
  1516. spinlock_init(&tbs->cmd_list_lock);
  1517. tbs->ses_mgr = ses_mgr;
  1518. sp_var_client_create(svc, &tbs->var_client);
  1519. *p_tbs = tbs;
  1520. return 0;
  1521. }
  1522. int sp_tbs_start(sp_tbs_t *tbs)
  1523. {
  1524. if (tbs->work_thread) {
  1525. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("may be already started! %s %d", _GetFileName(__FILE__), __LINE__);
  1526. return Error_Duplication;
  1527. }
  1528. tbs->ready_evt_result = 0;
  1529. ResetEvent(tbs->ready_evt);
  1530. tbs->work_thread = (HANDLE)_beginthreadex(NULL, 0, &server_proc, tbs, 0, (unsigned*)&tbs->work_thread_id);
  1531. if (!tbs->work_thread) {
  1532. return Error_Resource;
  1533. }
  1534. WaitForSingleObject(tbs->ready_evt, INFINITE);
  1535. if (tbs->ready_evt_result) {
  1536. CloseHandle(tbs->work_thread);
  1537. tbs->work_thread = NULL;
  1538. }
  1539. return tbs->ready_evt_result;
  1540. }
  1541. void sp_tbs_stop(sp_tbs_t *tbs)
  1542. {
  1543. TOOLKIT_ASSERT(tbs->work_thread);
  1544. post_msg(tbs, MSG_STOP, 0, 0);
  1545. WaitForSingleObject(tbs->work_thread, INFINITE);
  1546. CloseHandle(tbs->work_thread);
  1547. tbs->work_thread = NULL;
  1548. }
  1549. void sp_tbs_destroy(sp_tbs_t *tbs)
  1550. {
  1551. TOOLKIT_ASSERT(tbs->conn_cnt == 1);
  1552. TOOLKIT_ASSERT(tbs->server_fd == INVALID_SOCKET);
  1553. CloseHandle(tbs->conn_evt[0]);
  1554. CloseHandle(tbs->ready_evt);
  1555. sp_log_client_destroy(tbs->log_client);
  1556. sp_var_client_destroy(tbs->var_client);
  1557. free(tbs);
  1558. }