we need to set the port properly in the parse_ip helper
[sahlberg/ctdb.git] / common / ctdb_util.c
1 /* 
2    ctdb utility code
3
4    Copyright (C) Andrew Tridgell  2006
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10    
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15    
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21 #include "lib/events/events.h"
22 #include "lib/tdb/include/tdb.h"
23 #include "system/network.h"
24 #include "system/filesys.h"
25 #include "system/wait.h"
26 #include "../include/ctdb_private.h"
27
28 int LogLevel = DEBUG_NOTICE;
29 int this_log_level = 0;
30
31 /*
32   return error string for last error
33 */
34 const char *ctdb_errstr(struct ctdb_context *ctdb)
35 {
36         return ctdb->err_msg;
37 }
38
39
40 /*
41   remember an error message
42 */
43 void ctdb_set_error(struct ctdb_context *ctdb, const char *fmt, ...)
44 {
45         va_list ap;
46         talloc_free(ctdb->err_msg);
47         va_start(ap, fmt);
48         ctdb->err_msg = talloc_vasprintf(ctdb, fmt, ap);
49         DEBUG(DEBUG_ERR,("ctdb error: %s\n", ctdb->err_msg));
50         va_end(ap);
51 }
52
53 /*
54   a fatal internal error occurred - no hope for recovery
55 */
56 void ctdb_fatal(struct ctdb_context *ctdb, const char *msg)
57 {
58         DEBUG(DEBUG_ALERT,("ctdb fatal error: %s\n", msg));
59         abort();
60 }
61
62 /*
63   parse a IP:port pair
64 */
65 int ctdb_parse_address(struct ctdb_context *ctdb,
66                        TALLOC_CTX *mem_ctx, const char *str,
67                        struct ctdb_address *address)
68 {
69         struct servent *se;
70
71         setservent(0);
72         se = getservbyname("ctdb", "tcp");
73         endservent();
74         
75         address->address = talloc_strdup(mem_ctx, str);
76         if (se == NULL) {
77                 address->port = CTDB_PORT;
78         } else {
79                 address->port = ntohs(se->s_port);
80         }
81         return 0;
82 }
83
84
85 /*
86   check if two addresses are the same
87 */
88 bool ctdb_same_address(struct ctdb_address *a1, struct ctdb_address *a2)
89 {
90         return strcmp(a1->address, a2->address) == 0 && a1->port == a2->port;
91 }
92
93
94 /*
95   hash function for mapping data to a VNN - taken from tdb
96 */
97 uint32_t ctdb_hash(const TDB_DATA *key)
98 {
99         uint32_t value; /* Used to compute the hash value.  */
100         uint32_t i;     /* Used to cycle through random values. */
101
102         /* Set the initial value from the key size. */
103         for (value = 0x238F13AF * key->dsize, i=0; i < key->dsize; i++)
104                 value = (value + (key->dptr[i] << (i*5 % 24)));
105
106         return (1103515243 * value + 12345);  
107 }
108
109 /*
110   a type checking varient of idr_find
111  */
112 static void *_idr_find_type(struct idr_context *idp, int id, const char *type, const char *location)
113 {
114         void *p = idr_find(idp, id);
115         if (p && talloc_check_name(p, type) == NULL) {
116                 DEBUG(DEBUG_ERR,("%s idr_find_type expected type %s  but got %s\n",
117                          location, type, talloc_get_name(p)));
118                 return NULL;
119         }
120         return p;
121 }
122
123
124 /*
125   update a max latency number
126  */
127 void ctdb_latency(struct ctdb_db_context *ctdb_db, const char *name, double *latency, struct timeval t)
128 {
129         double l = timeval_elapsed(&t);
130         if (l > *latency) {
131                 *latency = l;
132         }
133
134         if (ctdb_db->ctdb->tunable.log_latency_ms !=0) {
135                 if (l*1000 > ctdb_db->ctdb->tunable.log_latency_ms) {
136                         DEBUG(DEBUG_WARNING, ("High latency %fs for operation %s on database %s\n", l*1000000, name, ctdb_db->db_name));
137                 }
138         }
139 }
140
141 uint32_t ctdb_reqid_new(struct ctdb_context *ctdb, void *state)
142 {
143         uint32_t id;
144
145         id  = ctdb->idr_cnt++ & 0xFFFF;
146         id |= (idr_get_new(ctdb->idr, state, 0xFFFF)<<16);
147         return id;
148 }
149
150 void *_ctdb_reqid_find(struct ctdb_context *ctdb, uint32_t reqid, const char *type, const char *location)
151 {
152         void *p;
153
154         p = _idr_find_type(ctdb->idr, (reqid>>16)&0xFFFF, type, location);
155         if (p == NULL) {
156                 DEBUG(DEBUG_WARNING, ("Could not find idr:%u\n",reqid));
157         }
158
159         return p;
160 }
161
162
163 void ctdb_reqid_remove(struct ctdb_context *ctdb, uint32_t reqid)
164 {
165         int ret;
166
167         ret = idr_remove(ctdb->idr, (reqid>>16)&0xFFFF);
168         if (ret != 0) {
169                 DEBUG(DEBUG_ERR, ("Removing idr that does not exist\n"));
170         }
171 }
172
173
174 /*
175   form a ctdb_rec_data record from a key/data pair
176   
177   note that header may be NULL. If not NULL then it is included in the data portion
178   of the record
179  */
180 struct ctdb_rec_data *ctdb_marshall_record(TALLOC_CTX *mem_ctx, uint32_t reqid, 
181                                            TDB_DATA key, 
182                                            struct ctdb_ltdb_header *header,
183                                            TDB_DATA data)
184 {
185         size_t length;
186         struct ctdb_rec_data *d;
187
188         length = offsetof(struct ctdb_rec_data, data) + key.dsize + 
189                 data.dsize + (header?sizeof(*header):0);
190         d = (struct ctdb_rec_data *)talloc_size(mem_ctx, length);
191         if (d == NULL) {
192                 return NULL;
193         }
194         d->length = length;
195         d->reqid = reqid;
196         d->keylen = key.dsize;
197         memcpy(&d->data[0], key.dptr, key.dsize);
198         if (header) {
199                 d->datalen = data.dsize + sizeof(*header);
200                 memcpy(&d->data[key.dsize], header, sizeof(*header));
201                 memcpy(&d->data[key.dsize+sizeof(*header)], data.dptr, data.dsize);
202         } else {
203                 d->datalen = data.dsize;
204                 memcpy(&d->data[key.dsize], data.dptr, data.dsize);
205         }
206         return d;
207 }
208
209
210 /* helper function for marshalling multiple records */
211 struct ctdb_marshall_buffer *ctdb_marshall_add(TALLOC_CTX *mem_ctx, 
212                                                struct ctdb_marshall_buffer *m,
213                                                uint64_t db_id,
214                                                uint32_t reqid,
215                                                TDB_DATA key,
216                                                struct ctdb_ltdb_header *header,
217                                                TDB_DATA data)
218 {
219         struct ctdb_rec_data *r;
220         size_t m_size, r_size;
221         struct ctdb_marshall_buffer *m2;
222
223         r = ctdb_marshall_record(mem_ctx, reqid, key, header, data);
224         if (r == NULL) {
225                 talloc_free(m);
226                 return NULL;
227         }
228
229         if (m == NULL) {
230                 m = talloc_zero_size(mem_ctx, offsetof(struct ctdb_marshall_buffer, data));
231                 if (m == NULL) {
232                         return NULL;
233                 }
234                 m->db_id = db_id;
235         }
236
237         m_size = talloc_get_size(m);
238         r_size = talloc_get_size(r);
239
240         m2 = talloc_realloc_size(mem_ctx, m,  m_size + r_size);
241         if (m2 == NULL) {
242                 talloc_free(m);
243                 return NULL;
244         }
245
246         memcpy(m_size + (uint8_t *)m2, r, r_size);
247
248         talloc_free(r);
249
250         m2->count++;
251
252         return m2;
253 }
254
255 /* we've finished marshalling, return a data blob with the marshalled records */
256 TDB_DATA ctdb_marshall_finish(struct ctdb_marshall_buffer *m)
257 {
258         TDB_DATA data;
259         data.dptr = (uint8_t *)m;
260         data.dsize = talloc_get_size(m);
261         return data;
262 }
263
264 /* 
265    loop over a marshalling buffer 
266    
267      - pass r==NULL to start
268      - loop the number of times indicated by m->count
269 */
270 struct ctdb_rec_data *ctdb_marshall_loop_next(struct ctdb_marshall_buffer *m, struct ctdb_rec_data *r,
271                                               uint32_t *reqid,
272                                               struct ctdb_ltdb_header *header,
273                                               TDB_DATA *key, TDB_DATA *data)
274 {
275         if (r == NULL) {
276                 r = (struct ctdb_rec_data *)&m->data[0];
277         } else {
278                 r = (struct ctdb_rec_data *)(r->length + (uint8_t *)r);
279         }
280
281         if (reqid != NULL) {
282                 *reqid = r->reqid;
283         }
284         
285         if (key != NULL) {
286                 key->dptr   = &r->data[0];
287                 key->dsize  = r->keylen;
288         }
289         if (data != NULL) {
290                 data->dptr  = &r->data[r->keylen];
291                 data->dsize = r->datalen;
292                 if (header != NULL) {
293                         data->dptr += sizeof(*header);
294                         data->dsize -= sizeof(*header);
295                 }
296         }
297
298         if (header != NULL) {
299                 if (r->datalen < sizeof(*header)) {
300                         return NULL;
301                 }
302                 *header = *(struct ctdb_ltdb_header *)&r->data[r->keylen];
303         }
304
305         return r;
306 }
307
308
309 #if HAVE_SCHED_H
310 #include <sched.h>
311 #endif
312
313 /*
314   if possible, make this task real time
315  */
316 void ctdb_set_scheduler(struct ctdb_context *ctdb)
317 {
318 #if HAVE_SCHED_SETSCHEDULER     
319         struct sched_param p;
320         if (ctdb->saved_scheduler_param == NULL) {
321                 ctdb->saved_scheduler_param = talloc_size(ctdb, sizeof(p));
322         }
323         
324         if (sched_getparam(0, (struct sched_param *)ctdb->saved_scheduler_param) == -1) {
325                 DEBUG(DEBUG_ERR,("Unable to get old scheduler params\n"));
326                 return;
327         }
328
329         p = *(struct sched_param *)ctdb->saved_scheduler_param;
330         p.sched_priority = 1;
331
332         if (sched_setscheduler(0, SCHED_FIFO, &p) == -1) {
333                 DEBUG(DEBUG_CRIT,("Unable to set scheduler to SCHED_FIFO (%s)\n", 
334                          strerror(errno)));
335         } else {
336                 DEBUG(DEBUG_NOTICE,("Set scheduler to SCHED_FIFO\n"));
337         }
338 #endif
339 }
340
341 /*
342   restore previous scheduler parameters
343  */
344 void ctdb_restore_scheduler(struct ctdb_context *ctdb)
345 {
346 #if HAVE_SCHED_SETSCHEDULER     
347         if (ctdb->saved_scheduler_param == NULL) {
348                 ctdb_fatal(ctdb, "No saved scheduler parameters\n");
349         }
350         if (sched_setscheduler(0, SCHED_OTHER, (struct sched_param *)ctdb->saved_scheduler_param) == -1) {
351                 ctdb_fatal(ctdb, "Unable to restore old scheduler parameters\n");
352         }
353 #endif
354 }
355
356 void set_nonblocking(int fd)
357 {
358         unsigned v;
359         v = fcntl(fd, F_GETFL, 0);
360         fcntl(fd, F_SETFL, v | O_NONBLOCK);
361 }
362
363 void set_close_on_exec(int fd)
364 {
365         unsigned v;
366         v = fcntl(fd, F_GETFD, 0);
367         fcntl(fd, F_SETFD, v | FD_CLOEXEC);
368 }
369
370
371 bool parse_ipv4(const char *s, unsigned port, struct sockaddr_in *sin)
372 {
373         sin->sin_family = AF_INET;
374         sin->sin_port   = htons(port);
375
376         if (inet_pton(AF_INET, s, &sin->sin_addr) != 1) {
377                 DEBUG(DEBUG_ERR, (__location__ " Failed to translate %s into sin_addr\n", s));
378                 return false;
379         }
380
381         return true;
382 }
383
384 static bool parse_ipv6(const char *s, const char *iface, unsigned port, ctdb_sock_addr *saddr)
385 {
386         saddr->ip6.sin6_family   = AF_INET6;
387         saddr->ip6.sin6_port     = htons(port);
388         saddr->ip6.sin6_flowinfo = 0;
389         saddr->ip6.sin6_scope_id = 0;
390
391         if (inet_pton(AF_INET6, s, &saddr->ip6.sin6_addr) != 1) {
392                 DEBUG(DEBUG_ERR, (__location__ " Failed to translate %s into sin6_addr\n", s));
393                 return false;
394         }
395
396         if (iface && IN6_IS_ADDR_LINKLOCAL(&saddr->ip6.sin6_addr)) {
397                 saddr->ip6.sin6_scope_id = if_nametoindex(iface);
398         }
399
400         return true;
401 }
402 /*
403   parse a ip:port pair
404  */
405 bool parse_ip_port(const char *addr, ctdb_sock_addr *saddr)
406 {
407         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
408         char *s, *p;
409         unsigned port;
410         char *endp = NULL;
411         bool ret;
412
413         s = talloc_strdup(tmp_ctx, addr);
414         if (s == NULL) {
415                 DEBUG(DEBUG_ERR, (__location__ " Failed strdup()\n"));
416                 talloc_free(tmp_ctx);
417                 return false;
418         }
419
420         p = rindex(s, ':');
421         if (p == NULL) {
422                 DEBUG(DEBUG_ERR, (__location__ " This addr: %s does not contain a port number\n", s));
423                 talloc_free(tmp_ctx);
424                 return false;
425         }
426
427         port = strtoul(p+1, &endp, 10);
428         if (endp == NULL || *endp != 0) {
429                 /* trailing garbage */
430                 DEBUG(DEBUG_ERR, (__location__ " Trailing garbage after the port in %s\n", s));
431                 talloc_free(tmp_ctx);
432                 return false;
433         }
434         *p = 0;
435
436
437         /* now is this a ipv4 or ipv6 address ?*/
438         ret = parse_ip(s, NULL, port, saddr);
439
440         talloc_free(tmp_ctx);
441         return ret;
442 }
443
444 /*
445   parse an ip
446  */
447 bool parse_ip(const char *addr, const char *iface, unsigned port, ctdb_sock_addr *saddr)
448 {
449         char *p;
450         bool ret;
451
452         /* now is this a ipv4 or ipv6 address ?*/
453         p = index(addr, ':');
454         if (p == NULL) {
455                 ret = parse_ipv4(addr, port, &saddr->ip);
456         } else {
457                 ret = parse_ipv6(addr, iface, port, saddr);
458         }
459
460         return ret;
461 }
462
463 /*
464   parse a ip/mask pair
465  */
466 bool parse_ip_mask(const char *str, const char *iface, ctdb_sock_addr *addr, unsigned *mask)
467 {
468         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
469         char *s, *p;
470         char *endp = NULL;
471         bool ret;
472
473         ZERO_STRUCT(*addr);
474         s = talloc_strdup(tmp_ctx, str);
475         if (s == NULL) {
476                 DEBUG(DEBUG_ERR, (__location__ " Failed strdup()\n"));
477                 talloc_free(tmp_ctx);
478                 return false;
479         }
480
481         p = rindex(s, '/');
482         if (p == NULL) {
483                 DEBUG(DEBUG_ERR, (__location__ " This addr: %s does not contain a mask\n", s));
484                 talloc_free(tmp_ctx);
485                 return false;
486         }
487
488         *mask = strtoul(p+1, &endp, 10);
489         if (endp == NULL || *endp != 0) {
490                 /* trailing garbage */
491                 DEBUG(DEBUG_ERR, (__location__ " Trailing garbage after the mask in %s\n", s));
492                 talloc_free(tmp_ctx);
493                 return false;
494         }
495         *p = 0;
496
497
498         /* now is this a ipv4 or ipv6 address ?*/
499         ret = parse_ip(s, iface, 0, addr);
500
501         talloc_free(tmp_ctx);
502         return ret;
503 }
504
505 /*
506    This is used to canonicalize a ctdb_sock_addr structure.
507 */
508 void ctdb_canonicalize_ip(const ctdb_sock_addr *ip, ctdb_sock_addr *cip)
509 {
510         char prefix[12] = { 0,0,0,0,0,0,0,0,0,0,0xff,0xff };
511
512         memcpy(cip, ip, sizeof (*cip));
513
514         if ( (ip->sa.sa_family == AF_INET6)
515         && !memcmp(&ip->ip6.sin6_addr, prefix, 12)) {
516                 memset(cip, 0, sizeof(*cip));
517 #ifdef HAVE_SOCK_SIN_LEN
518                 cip->ip.sin_len = sizeof(*cip);
519 #endif
520                 cip->ip.sin_family = AF_INET;
521                 cip->ip.sin_port   = ip->ip6.sin6_port;
522                 memcpy(&cip->ip.sin_addr, &ip->ip6.sin6_addr.s6_addr32[3], 4);
523         }
524 }
525
526 bool ctdb_same_ip(const ctdb_sock_addr *tip1, const ctdb_sock_addr *tip2)
527 {
528         ctdb_sock_addr ip1, ip2;
529
530         ctdb_canonicalize_ip(tip1, &ip1);
531         ctdb_canonicalize_ip(tip2, &ip2);
532         
533         if (ip1.sa.sa_family != ip2.sa.sa_family) {
534                 return false;
535         }
536
537         switch (ip1.sa.sa_family) {
538         case AF_INET:
539                 return ip1.ip.sin_addr.s_addr == ip2.ip.sin_addr.s_addr;
540         case AF_INET6:
541                 return !memcmp(&ip1.ip6.sin6_addr.s6_addr[0],
542                                 &ip2.ip6.sin6_addr.s6_addr[0],
543                                 16);
544         default:
545                 DEBUG(DEBUG_ERR, (__location__ " CRITICAL Can not compare sockaddr structures of type %u\n", ip1.sa.sa_family));
546                 return false;
547         }
548
549         return true;
550 }
551
552 /*
553   compare two ctdb_sock_addr structures
554  */
555 bool ctdb_same_sockaddr(const ctdb_sock_addr *ip1, const ctdb_sock_addr *ip2)
556 {
557         return ctdb_same_ip(ip1, ip2) && ip1->ip.sin_port == ip2->ip.sin_port;
558 }
559
560 char *ctdb_addr_to_str(ctdb_sock_addr *addr)
561 {
562         static char cip[128] = "";
563
564         switch (addr->sa.sa_family) {
565         case AF_INET:
566                 inet_ntop(addr->ip.sin_family, &addr->ip.sin_addr, cip, sizeof(cip));
567                 break;
568         case AF_INET6:
569                 inet_ntop(addr->ip6.sin6_family, &addr->ip6.sin6_addr, cip, sizeof(cip));
570                 break;
571         default:
572                 DEBUG(DEBUG_ERR, (__location__ " ERROR, unknown family %u\n", addr->sa.sa_family));
573         }
574
575         return cip;
576 }
577
578 unsigned ctdb_addr_to_port(ctdb_sock_addr *addr)
579 {
580         switch (addr->sa.sa_family) {
581         case AF_INET:
582                 return ntohs(addr->ip.sin_port);
583                 break;
584         case AF_INET6:
585                 return ntohs(addr->ip6.sin6_port);
586                 break;
587         default:
588                 DEBUG(DEBUG_ERR, (__location__ " ERROR, unknown family %u\n", addr->sa.sa_family));
589         }
590
591         return 0;
592 }
593
594 void ctdb_block_signal(int signum)
595 {
596         sigset_t set;
597         sigemptyset(&set);
598         sigaddset(&set,signum);
599         sigprocmask(SIG_BLOCK,&set,NULL);
600 }
601
602 void ctdb_unblock_signal(int signum)
603 {
604         sigset_t set;
605         sigemptyset(&set);
606         sigaddset(&set,signum);
607         sigprocmask(SIG_UNBLOCK,&set,NULL);
608 }