utils.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. /****************************************************************************
  2. *
  3. * UTILS.C - NRPE Utility Functions
  4. *
  5. * License: GPL
  6. * Copyright (c) 1999-2006 Ethan Galstad (nagios@nagios.org)
  7. *
  8. * Last Modified: 12-11-2006
  9. *
  10. * Description:
  11. *
  12. * This file contains common network functions used in nrpe and check_nrpe.
  13. *
  14. * License Information:
  15. *
  16. * This program is free software; you can redistribute it and/or modify
  17. * it under the terms of the GNU General Public License as published by
  18. * the Free Software Foundation; either version 2 of the License, or
  19. * (at your option) any later version.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU General Public License
  27. * along with this program; if not, write to the Free Software
  28. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  29. *
  30. ****************************************************************************/
  31. #include "../include/common.h"
  32. #include "../include/utils.h"
  33. #ifndef NI_MAXSERV
  34. #define NI_MAXSERV 32
  35. #endif
  36. #ifndef NI_MAXHOST
  37. #define NI_MAXHOST 1025
  38. #endif
  39. static unsigned long crc32_table[256];
  40. /* build the crc table - must be called before calculating the crc value */
  41. void generate_crc32_table(void){
  42. unsigned long crc, poly;
  43. int i, j;
  44. poly=0xEDB88320L;
  45. for(i=0;i<256;i++){
  46. crc=i;
  47. for(j=8;j>0;j--){
  48. if(crc & 1)
  49. crc=(crc>>1)^poly;
  50. else
  51. crc>>=1;
  52. }
  53. crc32_table[i]=crc;
  54. }
  55. return;
  56. }
  57. /* calculates the CRC 32 value for a buffer */
  58. unsigned long calculate_crc32(char *buffer, int buffer_size){
  59. register unsigned long crc;
  60. int this_char;
  61. int current_index;
  62. crc=0xFFFFFFFF;
  63. for(current_index=0;current_index<buffer_size;current_index++){
  64. this_char=(int)buffer[current_index];
  65. crc=((crc>>8) & 0x00FFFFFF) ^ crc32_table[(crc ^ this_char) & 0xFF];
  66. }
  67. return (crc ^ 0xFFFFFFFF);
  68. }
  69. /* fill a buffer with semi-random data */
  70. void randomize_buffer(char *buffer,int buffer_size){
  71. FILE *fp;
  72. int x;
  73. int seed;
  74. /**** FILL BUFFER WITH RANDOM ALPHA-NUMERIC CHARACTERS ****/
  75. /***************************************************************
  76. Only use alpha-numeric characters becase plugins usually
  77. only generate numbers and letters in their output. We
  78. want the buffer to contain the same set of characters as
  79. plugins, so its harder to distinguish where the real output
  80. ends and the rest of the buffer (padded randomly) starts.
  81. ***************************************************************/
  82. /* try to get seed value from /dev/urandom, as its a better source of entropy */
  83. fp=fopen("/dev/urandom","r");
  84. if(fp!=NULL){
  85. seed=fgetc(fp);
  86. fclose(fp);
  87. }
  88. /* else fallback to using the current time as the seed */
  89. else
  90. seed=(int)time(NULL);
  91. srand(seed);
  92. for(x=0;x<buffer_size;x++)
  93. buffer[x]=(int)'0'+(int)(72.0*rand()/(RAND_MAX+1.0));
  94. return;
  95. }
  96. /* opens a connection to a remote host */
  97. int my_connect(const char *host, struct sockaddr_storage * hostaddr, u_short port,
  98. int address_family, const char *bind_address){
  99. int gaierr;
  100. int sock = -1;
  101. char ntop[NI_MAXHOST], strport[NI_MAXSERV];
  102. struct addrinfo hints, *ai, *aitop;
  103. memset(&hints, 0, sizeof(hints));
  104. hints.ai_family = address_family;
  105. hints.ai_socktype = SOCK_STREAM;
  106. snprintf(strport, sizeof strport, "%u", port);
  107. if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
  108. fprintf(stderr,"Could not resolve hostname %.100s: %s\n", host,
  109. gai_strerror(gaierr));
  110. exit(1);
  111. }
  112. /*
  113. * Loop through addresses for this host, and try each one in
  114. * sequence until the connection succeeds.
  115. */
  116. for (ai = aitop; ai; ai = ai->ai_next) {
  117. if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) continue;
  118. if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
  119. strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
  120. fprintf(stderr, "my_connect: getnameinfo failed\n");
  121. continue;
  122. }
  123. /* Create a socket for connecting. */
  124. sock = my_create_socket(ai, bind_address);
  125. if (sock < 0) {
  126. /* Any error is already output */
  127. continue;
  128. }
  129. if (connect(sock, ai->ai_addr, ai->ai_addrlen) >= 0) {
  130. /* Successful connection. */
  131. memcpy(hostaddr, ai->ai_addr, ai->ai_addrlen);
  132. break;
  133. }
  134. else {
  135. fprintf(stderr,"connect to address %s port %s: %s\n", ntop, strport,
  136. strerror(errno));
  137. close(sock);
  138. sock = -1;
  139. }
  140. }
  141. freeaddrinfo(aitop);
  142. /* Return failure if we didn't get a successful connection. */
  143. if (sock == -1) {
  144. fprintf(stderr, "connect to host %s port %s: %s", host, strport,
  145. strerror(errno));
  146. return -1;
  147. }
  148. return sock;
  149. }
  150. /* Creates a socket for the connection. */
  151. int my_create_socket(struct addrinfo *ai, const char *bind_address) {
  152. int sock, gaierr;
  153. struct addrinfo hints, *res;
  154. sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  155. if (sock < 0) fprintf(stderr,"socket: %.100s\n", strerror(errno));
  156. /* Bind the socket to an alternative local IP address */
  157. if (bind_address == NULL) return sock;
  158. memset(&hints, 0, sizeof(hints));
  159. hints.ai_family = ai->ai_family;
  160. hints.ai_socktype = ai->ai_socktype;
  161. hints.ai_protocol = ai->ai_protocol;
  162. hints.ai_flags = AI_PASSIVE;
  163. gaierr = getaddrinfo(bind_address, NULL, &hints, &res);
  164. if(gaierr) {
  165. fprintf(stderr, "getaddrinfo: %s: %s\n", bind_address,
  166. gai_strerror(gaierr));
  167. close(sock);
  168. return -1;
  169. }
  170. if(bind(sock, res->ai_addr, res->ai_addrlen) < 0) {
  171. fprintf(stderr, "bind: %s: %s\n", bind_address, strerror(errno));
  172. close(sock);
  173. freeaddrinfo(res);
  174. return -1;
  175. }
  176. freeaddrinfo(res);
  177. return sock;
  178. }
  179. void add_listen_addr(struct addrinfo **listen_addrs, int address_family,
  180. char *addr, int port) {
  181. struct addrinfo hints, *ai, *aitop;
  182. char strport[NI_MAXSERV];
  183. int gaierr;
  184. memset(&hints, 0, sizeof(hints));
  185. hints.ai_family = address_family;
  186. hints.ai_socktype = SOCK_STREAM;
  187. hints.ai_flags = (addr == NULL) ? AI_PASSIVE : 0;
  188. snprintf(strport, sizeof strport, "%d", port);
  189. if((gaierr = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
  190. syslog(LOG_ERR,"bad addr or host: %s (%s)\n", addr ? addr : "<NULL>",
  191. gai_strerror(gaierr));
  192. exit(1);
  193. }
  194. for(ai = aitop; ai->ai_next; ai = ai->ai_next);
  195. ai->ai_next = *listen_addrs;
  196. *listen_addrs = aitop;
  197. }
  198. void strip(char *buffer){
  199. int x;
  200. int index;
  201. for(x=strlen(buffer);x>=1;x--){
  202. index=x-1;
  203. if(buffer[index]==' ' || buffer[index]=='\r' || buffer[index]=='\n' || buffer[index]=='\t')
  204. buffer[index]='\x0';
  205. else
  206. break;
  207. }
  208. return;
  209. }
  210. /* sends all data - thanks to Beej's Guide to Network Programming */
  211. int sendall(int s, char *buf, int *len){
  212. int total=0;
  213. int bytesleft=*len;
  214. int n=0;
  215. /* send all the data */
  216. while(total<*len){
  217. /* send some data */
  218. n=send(s,buf+total,bytesleft,0);
  219. /* break on error */
  220. if(n==-1)
  221. break;
  222. /* apply bytes we sent */
  223. total+=n;
  224. bytesleft-=n;
  225. }
  226. /* return number of bytes actually send here */
  227. *len=total;
  228. /* return -1 on failure, 0 on success */
  229. return n==-1?-1:0;
  230. }
  231. /* receives all data - modelled after sendall() */
  232. int recvall(int s, char *buf, int *len, int timeout){
  233. int total=0;
  234. int bytesleft=*len;
  235. int n=0;
  236. time_t start_time;
  237. time_t current_time;
  238. /* clear the receive buffer */
  239. bzero(buf,*len);
  240. time(&start_time);
  241. /* receive all data */
  242. while(total<*len){
  243. /* receive some data */
  244. n=recv(s,buf+total,bytesleft,0);
  245. /* no data has arrived yet (non-blocking socket) */
  246. if(n==-1 && errno==EAGAIN){
  247. time(&current_time);
  248. if(current_time-start_time>timeout)
  249. break;
  250. sleep(1);
  251. continue;
  252. }
  253. /* receive error or client disconnect */
  254. else if(n<=0)
  255. break;
  256. /* apply bytes we received */
  257. total+=n;
  258. bytesleft-=n;
  259. }
  260. /* return number of bytes actually received here */
  261. *len=total;
  262. /* return <=0 on failure, bytes received on success */
  263. return (n<=0)?n:total;
  264. }
  265. /* fixes compiler problems under Solaris, since strsep() isn't included */
  266. /* this code is taken from the glibc source */
  267. char *my_strsep (char **stringp, const char *delim){
  268. char *begin, *end;
  269. begin = *stringp;
  270. if (begin == NULL)
  271. return NULL;
  272. /* A frequent case is when the delimiter string contains only one
  273. character. Here we don't need to call the expensive `strpbrk'
  274. function and instead work using `strchr'. */
  275. if(delim[0]=='\0' || delim[1]=='\0'){
  276. char ch = delim[0];
  277. if(ch=='\0')
  278. end=NULL;
  279. else{
  280. if(*begin==ch)
  281. end=begin;
  282. else
  283. end=strchr(begin+1,ch);
  284. }
  285. }
  286. else
  287. /* Find the end of the token. */
  288. end = strpbrk (begin, delim);
  289. if(end){
  290. /* Terminate the token and set *STRINGP past NUL character. */
  291. *end++='\0';
  292. *stringp=end;
  293. }
  294. else
  295. /* No more delimiters; this is the last token. */
  296. *stringp=NULL;
  297. return begin;
  298. }
  299. int b64_decode(unsigned char *encoded)
  300. {
  301. static const char *b64 = { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" };
  302. int i, j, l, padding = 0;
  303. unsigned char c[4], *outp = encoded;
  304. union {
  305. unsigned c3;
  306. struct {
  307. unsigned f1:6;
  308. unsigned f2:6;
  309. unsigned f3:6;
  310. unsigned f4:6;
  311. } fields;
  312. } enc;
  313. enc.c3 = 0;
  314. l = strlen((char*)encoded);
  315. for (i = 0; i < l; i += 4) {
  316. for (j = 0; j < 4; ++j) {
  317. if (encoded[i+j] == '=') {
  318. c[j] = 0;
  319. ++padding;
  320. } else if (encoded[i+j] >= 'A' && encoded[i+j] <= 'Z')
  321. c[j] = encoded[i+j] - 'A';
  322. else if (encoded[i+j] >= 'a' && encoded[i+j] <= 'z')
  323. c[j] = encoded[i+j] - 'a' + 26;
  324. else if (encoded[i+j] >= '0' && encoded[i+j] <= '9')
  325. c[j] = encoded[i+j] - '0' + 52;
  326. else if (encoded[i+j] == '+')
  327. c[j] = encoded[i+j] - '+' + 62;
  328. else
  329. c[j] = encoded[i+j] - '/' + 63;
  330. }
  331. enc.fields.f1 = c[3];
  332. enc.fields.f2 = c[2];
  333. enc.fields.f3 = c[1];
  334. enc.fields.f4 = c[0];
  335. *outp++ = (enc.c3 >> 16) & 0xff;
  336. *outp++ = (enc.c3 >> 8) & 0xff;
  337. *outp++ = (enc.c3) & 0xff;
  338. }
  339. *outp = '\0';
  340. return outp - encoded - padding;
  341. }
  342. /* show license */
  343. void display_license(void){
  344. printf("This program is released under the GPL (see below) with the additional\n");
  345. printf("exemption that compiling, linking, and/or using OpenSSL is allowed.\n\n");
  346. printf("This program is free software; you can redistribute it and/or modify\n");
  347. printf("it under the terms of the GNU General Public License as published by\n");
  348. printf("the Free Software Foundation; either version 2 of the License, or\n");
  349. printf("(at your option) any later version.\n\n");
  350. printf("This program is distributed in the hope that it will be useful,\n");
  351. printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
  352. printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n");
  353. printf("GNU General Public License for more details.\n\n");
  354. printf("You should have received a copy of the GNU General Public License\n");
  355. printf("along with this program; if not, write to the Free Software\n");
  356. printf("Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n");
  357. return;
  358. }