ZOOOO

Untitled

Apr 19th, 2016
6,928
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.13 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstring>
  4. #include <cstdlib>
  5. #include <vector>
  6. #include <sstream>
  7. #include <iterator>
  8. #include <algorithm>
  9. #include <memory>
  10.  
  11. #include <sys/types.h>
  12. #include <sys/socket.h>
  13. #include <errno.h>
  14. #include <netinet/in.h>
  15. #include <sys/poll.h>
  16. #include <arpa/inet.h>
  17. #include <unistd.h>
  18. #include <fcntl.h>
  19. #include <asn1/Request.h>
  20. #include <asn1/Response.h>
  21.  
  22. #define MAXCOUNT 1024
  23. #define TRUE 1
  24. #define FALSE 0
  25. #define CONST 128 * 128
  26. #define BUF_LEN 1 << 20
  27. #define PORT 5001
  28. #define SSYMBOL(x) #x
  29. #define SYMBOL(X) SSYMBOL(X)
  30. #define F_NAME "log.txt"
  31.  
  32. #define WRITE 1200075747
  33. #define WARN -1897635125
  34. #define INFO -1442228161
  35. #define ERROR -907056764
  36. #define GET 1806773703
  37. #define CLEAR 352069091
  38. #define BEFORE -115185719
  39.  
  40. using namespace std;
  41.  
  42.  
  43. unsigned int HashRot13(const char * str) {
  44. unsigned int hash = 0;
  45.  
  46. for(; *str; str++) {
  47. hash += (unsigned char)(*str); hash -= (hash << 13) | (hash >> 19);
  48. }
  49.  
  50. return hash;
  51. }
  52.  
  53. int recvn(int sock, void *buf, int buflen) {
  54. int n, total = 0;
  55. while (total != buflen) {
  56. n = recv(sock, (char*) buf + total, buflen - total, 0);
  57. if (n <= 0)
  58. return n;
  59. total += n;
  60. }
  61. return total;
  62. }
  63.  
  64. vector<string> lexer(char* str) {
  65. vector<string> lexems {};
  66. for(string tmp = ""; *str; str++) {
  67. for(tmp.clear(); *str && !isspace(*(str)); tmp += *str, str++);
  68. lexems.push_back(tmp);
  69. }
  70. return lexems;
  71. }
  72.  
  73.  
  74. int resolve_command(const char *buffer, Request_t &req) {
  75. istringstream iss { string { buffer } }; //для простого разбиения на токены
  76. string cmd, tmp;
  77. iss >> cmd;
  78. unsigned int cmdHash = HashRot13(cmd.c_str());
  79. switch (cmdHash) {
  80. case WRITE: { //write *level* *msg*
  81. iss >> tmp;
  82. //заполняем поля
  83. req.present = Request_PR_add;
  84. LogLevel_t &level = req.choice.add.level;
  85. MessageText_t &msg = req.choice.add.msg;
  86. msg.buf = nullptr;
  87. unsigned int tmpHash = HashRot13(tmp.c_str());
  88. switch (tmpHash) {
  89. case WARN:
  90. level = LogLevel_warn;
  91. break;
  92. case INFO:
  93. level = LogLevel_info;
  94. break;
  95. case ERROR:
  96. level = LogLevel_error;
  97. break;
  98. default :
  99. printf("wrong level\n");
  100. return 0;
  101. }
  102. //пропуск лидирующих пробелов
  103. char c;
  104. while (isspace(c = iss.get()));
  105. iss.putback(c);
  106. getline(iss, tmp);
  107. OCTET_STRING_fromString(&msg, tmp.c_str());
  108. break;
  109. } case GET: {//get level lvl [from data [to data]] | get from data [to data]
  110. //заполнение полей
  111. req.present = Request_PR_get;
  112. LogLevel_t *&level = req.choice.get.level;
  113. GeneralizedTime_t *&from = req.choice.get.begin, *&to =
  114. req.choice.get.end;
  115. //разбиваем на токены и смотрим, какие есть условия
  116. char* q = (char*)buffer;
  117. vector<string> tokens = lexer(q);
  118. auto l = find(tokens.begin(), tokens.end(), "level") + 1;
  119. auto f = find(tokens.begin(), tokens.end(), "since") + 1;
  120. auto t = find(tokens.begin(), tokens.end(), "before") + 1;
  121. if (l == tokens.end() || f == tokens.end() || t == tokens.end()) {
  122. printf("syntax error\n");
  123. return 0;
  124. }
  125. //вносим условия в структуру
  126. if (l < tokens.end()) {
  127. level = (LogLevel_t*)malloc(sizeof(LogLevel_t));
  128. if (*l == "warn") {
  129. *level = LogLevel_warn;
  130. } else if (*l == "info") {
  131. *level = LogLevel_info;
  132. } else if (*l == "error") {
  133. *level = LogLevel_error;
  134. } else {
  135. delete level;
  136. printf("syntax error\n");
  137. return 0;
  138. }
  139. }
  140. if (f < tokens.end()) {
  141. from = (GeneralizedTime_t*)malloc(sizeof(GeneralizedTime_t));
  142. memset(from, 0, sizeof(GeneralizedTime_t));
  143. //для более удобного ввода даты в виде гггг.мм.дд.чч.мм.сс
  144. f->erase(remove(f->begin(), f->end(), '.'), f->end());
  145. OCTET_STRING_fromString(from, f->c_str());
  146. }
  147. if (t < tokens.end()) {
  148. to = (GeneralizedTime_t*)malloc(sizeof(GeneralizedTime_t));;
  149. memset(to, 0, sizeof(GeneralizedTime_t));
  150. t->erase(remove(t->begin(), t->end(), '.'), t->end());
  151. OCTET_STRING_fromString(to, t->c_str());
  152. }
  153. break;
  154. //xer_fprint(stdout, &asn_DEF_Request, &req);
  155. } case CLEAR : {
  156. //заполнение полей
  157. req.present = Request_PR_clear;
  158. iss >> tmp;
  159. //определение типа все или до
  160. if (tmp == "") {
  161. req.choice.clear.present = ClearRequest_PR_all;
  162. } else if (tmp == "before") {
  163. iss >> tmp;
  164. tmp.erase(remove(tmp.begin(), tmp.end(), '.'), tmp.end());
  165. req.choice.clear.present = ClearRequest_PR_olderThan;
  166. OCTET_STRING_fromString(&req.choice.clear.choice.olderThan,
  167. tmp.c_str());
  168. } else {
  169. printf("syntax error\n");
  170. return 0;
  171. }
  172. //xer_fprint(stdout, &asn_DEF_Request, &req);
  173. break;
  174. } default : {
  175. printf("syntax error\n");
  176. return 0;
  177. }
  178. }
  179. return 1;
  180. }
  181.  
  182.  
  183. void print_resp(Response_t *resp) {
  184. if(resp->present == Response_PR_records) {
  185. int n = resp->choice.records.list.count;
  186. for(int i = 0; i < n; i++) {
  187. LogRecord_t *tmp = resp->choice.records.list.array[i];
  188. switch(tmp->level) {
  189. case LogLevel_warn:
  190. printf("warn ");
  191. break;
  192. case LogLevel_error:
  193. printf("error ");
  194. break;
  195. case LogLevel_info:
  196. printf("info ");
  197. break;
  198. }
  199.  
  200. auto p = tmp->ip.choice.iPBinaryAddress.choice.iPBinV4Address.buf;
  201. printf("%d.%d.%d.%d ", p[0], p[1], p[2], p[3]);
  202.  
  203. tm t;
  204. asn_GT2time(&tmp->timestamp, &t, 0);
  205. char buf[50];
  206. strftime(buf, 50UL, "%F %T", &t);
  207.  
  208. printf("%s %.*s\n",buf, tmp->msg.size, tmp->msg.buf);
  209. }
  210. } else {
  211. printf("nothing found\n");
  212. }
  213. fflush(stdout);
  214. }
  215.  
  216.  
  217.  
  218. int main(void) {
  219. int sock, timeout;
  220. struct sockaddr_in saddr;
  221. memset(&saddr,0,sizeof(saddr));
  222. sock = socket(AF_INET,SOCK_STREAM,0);
  223. saddr.sin_family = AF_INET;
  224. inet_aton("127.0.0.1",&saddr.sin_addr);
  225. saddr.sin_port = htons(12345);
  226. timeout = (3 * 6 * 1000);
  227. struct pollfd fds[2];
  228.  
  229.  
  230. fds[0].fd = sock;
  231. fds[0].events = POLLIN;
  232. connect(sock,(struct sockaddr*) &saddr, sizeof(saddr));
  233. fds[1].fd = STDIN_FILENO;
  234. fds[1].events = POLLIN;
  235.  
  236. std::unique_ptr<char> buffer_h{(char*)calloc(BUF_LEN, sizeof(char))};
  237. char *buffer = buffer_h.get();
  238. string inp = "";
  239. while( poll(fds, 2, timeout)) {
  240.  
  241. printf("download...\n");
  242.  
  243. memset(buffer, 0, BUF_LEN);
  244. getline(cin, inp);
  245. Request_t req;
  246.  
  247. memset(&req, 0, sizeof(Request_t));
  248. //проверка ввода
  249. if (resolve_command(inp.c_str(), req)) {
  250.  
  251. asn_enc_rval_t er;
  252. //если проверка прошла, кодируем
  253.  
  254. er = der_encode_to_buffer(&asn_DEF_Request, &req, buffer, BUF_LEN);
  255. if (er.encoded == -1) {
  256. ASN_STRUCT_FREE_CONTENTS_ONLY(asn_DEF_Request, &req);
  257. perror("encoded");
  258. return 1;
  259. }
  260.  
  261. uint32_t len = er.encoded;
  262. len = htonl(len);
  263. if (send(sock, &len, sizeof(len), 0) < 0) {
  264. perror("send");
  265. ASN_STRUCT_FREE_CONTENTS_ONLY(asn_DEF_Request, &req);
  266. return 1;
  267. }
  268. len = ntohl(len);
  269. if (send(sock, buffer, len, 0) < 0) {
  270. perror("send");
  271. ASN_STRUCT_FREE_CONTENTS_ONLY(asn_DEF_Request, &req);
  272. return 1;
  273. }
  274. ASN_STRUCT_FREE_CONTENTS_ONLY(asn_DEF_Request, &req);
  275. }
  276.  
  277. if (poll(fds, 2, timeout/18)){
  278. //обработка ответа с сервера
  279. uint32_t len, n;
  280. n = recvn(sock, &len, sizeof(len));
  281. if(n <= 0)
  282. continue;
  283. len = ntohl(len);
  284. char *tmp = (char *) malloc(len * sizeof(char));
  285. n = recvn(sock, tmp, len);
  286.  
  287. asn_dec_rval_t rv;
  288. Response_t *resp = nullptr;
  289. //декодировли
  290.  
  291. rv = ber_decode(0, &asn_DEF_Response, (void**) &resp, tmp, len);
  292. //вывели
  293.  
  294. if(rv.code != RC_OK) {
  295. perror("cannot decode");
  296. free(tmp);
  297. ASN_STRUCT_FREE(asn_DEF_Response, resp);
  298. continue;
  299. }
  300. print_resp(resp);
  301. //xer_fprint(stdout, &asn_DEF_Response, resp);
  302. ASN_STRUCT_FREE(asn_DEF_Response, resp);
  303. free(tmp);
  304. }
  305.  
  306. fflush(stdout);
  307. }
  308. free(buffer);
  309.  
  310. return 0;
  311. }
Add Comment
Please, Sign In to add comment