ldb-samba: ldif_read_objectSid avoids VLA
[samba.git] / ctdb / 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 "replace.h"
21 #include "system/network.h"
22 #include "system/filesys.h"
23 #include "system/wait.h"
24 #include "lib/util/util_file.h"
25
26 #include <tdb.h>
27
28 #include "lib/util/debug.h"
29 #include "lib/util/samba_util.h"
30
31 #include "ctdb_private.h"
32
33 #include "protocol/protocol_util.h"
34
35 #include "common/reqid.h"
36 #include "common/system.h"
37 #include "common/common.h"
38 #include "common/logging.h"
39
40 /*
41   return error string for last error
42 */
43 const char *ctdb_errstr(struct ctdb_context *ctdb)
44 {
45         return ctdb->err_msg;
46 }
47
48
49 /*
50   remember an error message
51 */
52 void ctdb_set_error(struct ctdb_context *ctdb, const char *fmt, ...)
53 {
54         va_list ap;
55         talloc_free(ctdb->err_msg);
56         va_start(ap, fmt);
57         ctdb->err_msg = talloc_vasprintf(ctdb, fmt, ap);
58         DEBUG(DEBUG_ERR,("ctdb error: %s\n", ctdb->err_msg));
59         va_end(ap);
60 }
61
62 /*
63   a fatal internal error occurred - no hope for recovery
64 */
65 void ctdb_fatal(struct ctdb_context *ctdb, const char *msg)
66 {
67         DEBUG(DEBUG_ALERT,("ctdb fatal error: %s\n", msg));
68         abort();
69 }
70
71 /*
72   like ctdb_fatal() but a core/backtrace would not be useful
73 */
74 void ctdb_die(struct ctdb_context *ctdb, const char *msg)
75 {
76         DEBUG(DEBUG_ALERT,("ctdb exiting with error: %s\n", msg));
77         exit(1);
78 }
79
80 /* Set the path of a helper program from envvar, falling back to
81  * dir/file if envvar unset. type is a string to print in log
82  * messages.  helper is assumed to point to a statically allocated
83  * array of size bytes, initialised to "".  If file is NULL don't fall
84  * back if envvar is unset.  If dir is NULL and envvar is unset (but
85  * file is not NULL) then this is an error.  Returns true if helper is
86  * set, either previously or this time. */
87 bool ctdb_set_helper(const char *type, char *helper, size_t size,
88                      const char *envvar,
89                      const char *dir, const char *file)
90 {
91         const char *t;
92         struct stat st;
93
94         if (helper[0] != '\0') {
95                 /* Already set */
96                 return true;
97         }
98
99         t = getenv(envvar);
100         if (t != NULL) {
101                 if (strlen(t) >= size) {
102                         DEBUG(DEBUG_ERR,
103                               ("Unable to set %s - path too long\n", type));
104                         return false;
105                 }
106
107                 strncpy(helper, t, size);
108         } else if (file == NULL) {
109                 return false;
110         } else if (dir == NULL) {
111                         DEBUG(DEBUG_ERR,
112                               ("Unable to set %s - dir is NULL\n", type));
113                 return false;
114         } else {
115                 int ret;
116
117                 ret = snprintf(helper, size, "%s/%s", dir, file);
118                 if (ret < 0 || (size_t)ret >= size) {
119                         DEBUG(DEBUG_ERR,
120                               ("Unable to set %s - path too long\n", type));
121                         return false;
122                 }
123         }
124
125         if (stat(helper, &st) != 0) {
126                 DEBUG(DEBUG_ERR,
127                       ("Unable to set %s \"%s\" - %s\n",
128                        type, helper, strerror(errno)));
129                 return false;
130         }
131         if (!(st.st_mode & S_IXUSR)) {
132                 DEBUG(DEBUG_ERR,
133                       ("Unable to set %s \"%s\" - not executable\n",
134                        type, helper));
135                 return false;
136         }
137
138         DEBUG(DEBUG_NOTICE,
139               ("Set %s to \"%s\"\n", type, helper));
140         return true;
141 }
142
143 /*
144   parse a IP:port pair
145 */
146 int ctdb_parse_address(TALLOC_CTX *mem_ctx, const char *str,
147                        ctdb_sock_addr *address)
148 {
149         struct servent *se;
150         int port;
151         int ret;
152
153         setservent(0);
154         se = getservbyname("ctdb", "tcp");
155         endservent();
156
157         if (se == NULL) {
158                 port = CTDB_PORT;
159         } else {
160                 port = ntohs(se->s_port);
161         }
162
163         ret = ctdb_sock_addr_from_string(str, address, false);
164         if (ret != 0) {
165                 return -1;
166         }
167         ctdb_sock_addr_set_port(address, port);
168
169         return 0;
170 }
171
172
173 /*
174   check if two addresses are the same
175 */
176 bool ctdb_same_address(ctdb_sock_addr *a1, ctdb_sock_addr *a2)
177 {
178         return ctdb_same_ip(a1, a2) &&
179                 ctdb_addr_to_port(a1) == ctdb_addr_to_port(a2);
180 }
181
182
183 /*
184   hash function for mapping data to a VNN - taken from tdb
185 */
186 uint32_t ctdb_hash(const TDB_DATA *key)
187 {
188         return tdb_jenkins_hash(discard_const(key));
189 }
190
191
192 static uint32_t ctdb_marshall_record_size(TDB_DATA key,
193                                           struct ctdb_ltdb_header *header,
194                                           TDB_DATA data)
195 {
196         return offsetof(struct ctdb_rec_data_old, data) + key.dsize +
197                data.dsize + (header ? sizeof(*header) : 0);
198 }
199
200 static void ctdb_marshall_record_copy(struct ctdb_rec_data_old *rec,
201                                       uint32_t reqid,
202                                       TDB_DATA key,
203                                       struct ctdb_ltdb_header *header,
204                                       TDB_DATA data,
205                                       uint32_t length)
206 {
207         uint32_t offset;
208
209         rec->length = length;
210         rec->reqid = reqid;
211         rec->keylen = key.dsize;
212         memcpy(&rec->data[0], key.dptr, key.dsize);
213         offset = key.dsize;
214
215         if (header) {
216                 rec->datalen = data.dsize + sizeof(*header);
217                 memcpy(&rec->data[offset], header, sizeof(*header));
218                 offset += sizeof(*header);
219         } else {
220                 rec->datalen = data.dsize;
221         }
222         memcpy(&rec->data[offset], data.dptr, data.dsize);
223 }
224
225 /*
226   form a ctdb_rec_data record from a key/data pair
227   
228   note that header may be NULL. If not NULL then it is included in the data portion
229   of the record
230  */
231 struct ctdb_rec_data_old *ctdb_marshall_record(TALLOC_CTX *mem_ctx,
232                                                uint32_t reqid,
233                                                TDB_DATA key,
234                                                struct ctdb_ltdb_header *header,
235                                                TDB_DATA data)
236 {
237         size_t length;
238         struct ctdb_rec_data_old *d;
239
240         length = ctdb_marshall_record_size(key, header, data);
241
242         d = (struct ctdb_rec_data_old *)talloc_size(mem_ctx, length);
243         if (d == NULL) {
244                 return NULL;
245         }
246
247         ctdb_marshall_record_copy(d, reqid, key, header, data, length);
248         return d;
249 }
250
251
252 /* helper function for marshalling multiple records */
253 struct ctdb_marshall_buffer *ctdb_marshall_add(TALLOC_CTX *mem_ctx,
254                                                struct ctdb_marshall_buffer *m,
255                                                uint32_t db_id,
256                                                uint32_t reqid,
257                                                TDB_DATA key,
258                                                struct ctdb_ltdb_header *header,
259                                                TDB_DATA data)
260 {
261         struct ctdb_rec_data_old *r;
262         struct ctdb_marshall_buffer *m2;
263         uint32_t length, offset;
264
265         length = ctdb_marshall_record_size(key, header, data);
266
267         if (m == NULL) {
268                 offset = offsetof(struct ctdb_marshall_buffer, data);
269                 m2 = talloc_zero_size(mem_ctx, offset + length);
270         } else {
271                 offset = talloc_get_size(m);
272                 m2 = talloc_realloc_size(mem_ctx, m, offset + length);
273         }
274         if (m2 == NULL) {
275                 TALLOC_FREE(m);
276                 return NULL;
277         }
278
279         if (m == NULL) {
280                 m2->db_id = db_id;
281         }
282
283         r = (struct ctdb_rec_data_old *)((uint8_t *)m2 + offset);
284         ctdb_marshall_record_copy(r, reqid, key, header, data, length);
285         m2->count++;
286
287         return m2;
288 }
289
290 /* we've finished marshalling, return a data blob with the marshalled records */
291 TDB_DATA ctdb_marshall_finish(struct ctdb_marshall_buffer *m)
292 {
293         TDB_DATA data;
294         data.dptr = (uint8_t *)m;
295         data.dsize = talloc_get_size(m);
296         return data;
297 }
298
299 /* 
300    loop over a marshalling buffer 
301    
302      - pass r==NULL to start
303      - loop the number of times indicated by m->count
304 */
305 struct ctdb_rec_data_old *ctdb_marshall_loop_next(
306                                 struct ctdb_marshall_buffer *m,
307                                 struct ctdb_rec_data_old *r,
308                                 uint32_t *reqid,
309                                 struct ctdb_ltdb_header *header,
310                                 TDB_DATA *key, TDB_DATA *data)
311 {
312         if (r == NULL) {
313                 r = (struct ctdb_rec_data_old *)&m->data[0];
314         } else {
315                 r = (struct ctdb_rec_data_old *)(r->length + (uint8_t *)r);
316         }
317
318         if (reqid != NULL) {
319                 *reqid = r->reqid;
320         }
321         
322         if (key != NULL) {
323                 key->dptr   = &r->data[0];
324                 key->dsize  = r->keylen;
325         }
326         if (data != NULL) {
327                 data->dptr  = &r->data[r->keylen];
328                 data->dsize = r->datalen;
329                 if (header != NULL) {
330                         data->dptr += sizeof(*header);
331                         data->dsize -= sizeof(*header);
332                 }
333         }
334
335         if (header != NULL) {
336                 if (r->datalen < sizeof(*header)) {
337                         return NULL;
338                 }
339                 memcpy(header, &r->data[r->keylen], sizeof(*header));
340         }
341
342         return r;
343 }
344
345 /*
346    This is used to canonicalize a ctdb_sock_addr structure.
347 */
348 void ctdb_canonicalize_ip(const ctdb_sock_addr *ip, ctdb_sock_addr *cip)
349 {
350         ZERO_STRUCTP(cip);
351
352         if (ip->sa.sa_family == AF_INET6) {
353                 const char prefix[12] = { 0,0,0,0,0,0,0,0,0,0,0xff,0xff };
354                 if (memcmp(&ip->ip6.sin6_addr, prefix, sizeof(prefix)) == 0) {
355                         /* Copy IPv4-mapped IPv6 addresses as IPv4 */
356                         cip->ip.sin_family = AF_INET;
357 #ifdef HAVE_SOCK_SIN_LEN
358                         cip->ip.sin_len = sizeof(ctdb_sock_addr);
359 #endif
360                         cip->ip.sin_port   = ip->ip6.sin6_port;
361                         memcpy(&cip->ip.sin_addr,
362                                &ip->ip6.sin6_addr.s6_addr[12],
363                                sizeof(cip->ip.sin_addr));
364                 } else {
365                         cip->ip6.sin6_family = AF_INET6;
366 #ifdef HAVE_SOCK_SIN6_LEN
367                         cip->ip6.sin6_len = sizeof(ctdb_sock_addr);
368 #endif
369                         cip->ip6.sin6_port   = ip->ip6.sin6_port;
370                         memcpy(&cip->ip6.sin6_addr,
371                                &ip->ip6.sin6_addr,
372                                sizeof(cip->ip6.sin6_addr));
373                 }
374
375                 return;
376         }
377
378         if (ip->sa.sa_family == AF_INET) {
379                 cip->ip.sin_family = AF_INET;
380 #ifdef HAVE_SOCK_SIN_LEN
381                 cip->ip.sin_len = sizeof(ctdb_sock_addr);
382 #endif
383                 cip->ip.sin_port = ip->ip.sin_port;
384                 memcpy(&cip->ip.sin_addr,
385                        &ip->ip.sin_addr,
386                        sizeof(ip->ip.sin_addr));
387
388                 return;
389         }
390 }
391
392 void ctdb_canonicalize_ip_inplace(ctdb_sock_addr *ip)
393 {
394         ctdb_sock_addr tmp;
395         ctdb_canonicalize_ip(ip, &tmp);
396         memcpy(ip, &tmp, sizeof(tmp));
397 }
398
399 bool ctdb_same_ip(const ctdb_sock_addr *tip1, const ctdb_sock_addr *tip2)
400 {
401         ctdb_sock_addr ip1, ip2;
402
403         ctdb_canonicalize_ip(tip1, &ip1);
404         ctdb_canonicalize_ip(tip2, &ip2);
405         
406         if (ip1.sa.sa_family != ip2.sa.sa_family) {
407                 return false;
408         }
409
410         switch (ip1.sa.sa_family) {
411         case AF_INET:
412                 return ip1.ip.sin_addr.s_addr == ip2.ip.sin_addr.s_addr;
413         case AF_INET6:
414                 return !memcmp(&ip1.ip6.sin6_addr.s6_addr[0],
415                                 &ip2.ip6.sin6_addr.s6_addr[0],
416                                 16);
417         default:
418                 DEBUG(DEBUG_ERR, (__location__ " CRITICAL Can not compare sockaddr structures of type %u\n", ip1.sa.sa_family));
419                 return false;
420         }
421
422         return true;
423 }
424
425 /*
426   compare two ctdb_sock_addr structures
427  */
428 bool ctdb_same_sockaddr(const ctdb_sock_addr *ip1, const ctdb_sock_addr *ip2)
429 {
430         return ctdb_same_ip(ip1, ip2) && ip1->ip.sin_port == ip2->ip.sin_port;
431 }
432
433 char *ctdb_addr_to_str(ctdb_sock_addr *addr)
434 {
435         static char cip[128] = "";
436
437         switch (addr->sa.sa_family) {
438         case AF_INET:
439                 inet_ntop(addr->ip.sin_family, &addr->ip.sin_addr, cip, sizeof(cip));
440                 break;
441         case AF_INET6:
442                 inet_ntop(addr->ip6.sin6_family, &addr->ip6.sin6_addr, cip, sizeof(cip));
443                 break;
444         default:
445                 DEBUG(DEBUG_ERR, (__location__ " ERROR, unknown family %u\n", addr->sa.sa_family));
446         }
447
448         return cip;
449 }
450
451 unsigned ctdb_addr_to_port(ctdb_sock_addr *addr)
452 {
453         switch (addr->sa.sa_family) {
454         case AF_INET:
455                 return ntohs(addr->ip.sin_port);
456                 break;
457         case AF_INET6:
458                 return ntohs(addr->ip6.sin6_port);
459                 break;
460         default:
461                 DEBUG(DEBUG_ERR, (__location__ " ERROR, unknown family %u\n", addr->sa.sa_family));
462         }
463
464         return 0;
465 }
466
467 /* Add a node to a node map with given address and flags */
468 static bool node_map_add(TALLOC_CTX *mem_ctx,
469                          const char *nstr, uint32_t flags,
470                          struct ctdb_node_map_old **node_map)
471 {
472         ctdb_sock_addr addr;
473         uint32_t num;
474         size_t s;
475         struct ctdb_node_and_flags *n;
476
477         /* Might as well do this before trying to allocate memory */
478         if (ctdb_parse_address(mem_ctx, nstr, &addr) == -1) {
479                 return false;
480         }
481
482         num = (*node_map)->num + 1;
483         s = offsetof(struct ctdb_node_map_old, nodes) +
484                 num * sizeof(struct ctdb_node_and_flags);
485         *node_map = talloc_realloc_size(mem_ctx, *node_map, s);
486         if (*node_map == NULL) {
487                 DEBUG(DEBUG_ERR, (__location__ " Out of memory\n"));
488                 return false;
489         }
490
491         n = &(*node_map)->nodes[(*node_map)->num];
492         n->addr = addr;
493         n->pnn = (*node_map)->num;
494         n->flags = flags;
495
496         (*node_map)->num++;
497
498         return true;
499 }
500
501 /* Read a nodes file into a node map */
502 struct ctdb_node_map_old *ctdb_read_nodes_file(TALLOC_CTX *mem_ctx,
503                                            const char *nlist)
504 {
505         char **lines;
506         int nlines;
507         int i;
508         struct ctdb_node_map_old *ret;
509
510         /* Allocate node map header */
511         ret = talloc_zero_size(mem_ctx, offsetof(struct ctdb_node_map_old, nodes));
512         if (ret == NULL) {
513                 DEBUG(DEBUG_ERR, (__location__ " Out of memory\n"));
514                 return false;
515         }
516
517         lines = file_lines_load(nlist, &nlines, 0, mem_ctx);
518         if (lines == NULL) {
519                 DEBUG(DEBUG_ERR, ("Failed to read nodes file \"%s\"\n", nlist));
520                 return false;
521         }
522         while (nlines > 0 && strcmp(lines[nlines-1], "") == 0) {
523                 nlines--;
524         }
525
526         for (i=0; i < nlines; i++) {
527                 char *node;
528                 uint32_t flags;
529                 size_t len;
530
531                 node = lines[i];
532                 /* strip leading spaces */
533                 while((*node == ' ') || (*node == '\t')) {
534                         node++;
535                 }
536
537                 len = strlen(node);
538
539                 while ((len > 1) &&
540                        ((node[len-1] == ' ') || (node[len-1] == '\t')))
541                 {
542                         node[len-1] = '\0';
543                         len--;
544                 }
545
546                 if (len == 0) {
547                         continue;
548                 }
549                 if (*node == '#') {
550                         /* A "deleted" node is a node that is
551                            commented out in the nodes file.  This is
552                            used instead of removing a line, which
553                            would cause subsequent nodes to change
554                            their PNN. */
555                         flags = NODE_FLAGS_DELETED;
556                         node = discard_const("0.0.0.0");
557                 } else {
558                         flags = 0;
559                 }
560                 if (!node_map_add(mem_ctx, node, flags, &ret)) {
561                         talloc_free(lines);
562                         TALLOC_FREE(ret);
563                         return NULL;
564                 }
565         }
566
567         talloc_free(lines);
568         return ret;
569 }
570
571 struct ctdb_node_map_old *
572 ctdb_node_list_to_map(struct ctdb_node **nodes, uint32_t num_nodes,
573                       TALLOC_CTX *mem_ctx)
574 {
575         uint32_t i;
576         size_t size;
577         struct ctdb_node_map_old *node_map;
578
579         size = offsetof(struct ctdb_node_map_old, nodes) +
580                 num_nodes * sizeof(struct ctdb_node_and_flags);
581         node_map  = (struct ctdb_node_map_old *)talloc_zero_size(mem_ctx, size);
582         if (node_map == NULL) {
583                 DEBUG(DEBUG_ERR,
584                       (__location__ " Failed to allocate nodemap array\n"));
585                 return NULL;
586         }
587
588         node_map->num = num_nodes;
589         for (i=0; i<num_nodes; i++) {
590                 node_map->nodes[i].addr  = nodes[i]->address;
591                 node_map->nodes[i].pnn   = nodes[i]->pnn;
592                 node_map->nodes[i].flags = nodes[i]->flags;
593         }
594
595         return node_map;
596 }
597
598 /* Runstate handling */
599 void ctdb_set_runstate(struct ctdb_context *ctdb, enum ctdb_runstate runstate)
600 {
601         DEBUG(DEBUG_NOTICE,("Set runstate to %s (%d)\n",
602                             ctdb_runstate_to_string(runstate), runstate));
603
604         if (runstate <= ctdb->runstate) {
605                 ctdb_fatal(ctdb, "runstate must always increase");
606         }
607
608         ctdb->runstate = runstate;
609 }
610
611 /* Convert arbitrary data to 4-byte boundary padded uint32 array */
612 uint32_t *ctdb_key_to_idkey(TALLOC_CTX *mem_ctx, TDB_DATA key)
613 {
614         uint32_t idkey_size, *k;
615
616         idkey_size = 1 + (key.dsize + sizeof(uint32_t)-1) / sizeof(uint32_t);
617
618         k = talloc_zero_array(mem_ctx, uint32_t, idkey_size);
619         if (k == NULL) {
620                 return NULL;
621         }
622
623         k[0] = idkey_size;
624         memcpy(&k[1], key.dptr, key.dsize);
625
626         return k;
627 }