2007-09-27 [colin] 3.0.1cvs35
[claws.git] / src / ldapupdate.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 2003-2007 Michael Rasmussen and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 /*
21  * Functions necessary to access LDAP servers.
22  */
23
24 /*
25  * Outstanding bugs
26  * 1) When adding a contact to an empty addressbook from the pop-up menu
27  * when right-clicking on an email address causes claws-mail to crash in
28  * addritem.c line 965. Severity: Show stopper. Solved in 2.9.2cvs17
29  * 2) Updating a contact gets lost if the user makes a new search on the
30  * same LdapServer. Severity: Medium. Solved in 2.9.2cvs17 (patch added to solve 1) also solved this bug)
31  * 3) After adding a new contact the displayName for the contact is empty
32  * until the user makes a reread from the LdapServer. Severity: minor.
33  * Solved in 2.9.2cvs24
34  */
35
36 #ifdef HAVE_CONFIG_H
37 #  include "config.h"
38 #endif
39
40 #ifdef USE_LDAP
41
42 #include <glib.h>
43 #include <glib/gi18n.h>
44 #include <sys/time.h>
45 #include <string.h>
46 #include <ldap.h>
47 #include <lber.h>
48
49 #include "ldapupdate.h"
50 #include "mgutils.h"
51 #include "addritem.h"
52 #include "addrcache.h"
53 #include "ldapctrl.h"
54 #include "ldapquery.h"
55 #include "ldapserver.h"
56 #include "ldaputil.h"
57 #include "utils.h"
58 #include "adbookbase.h"
59 #include "editaddress_other_attributes_ldap.h"
60
61 /**
62  * Structure to hold user defined attributes
63  * from contacts
64  */
65 typedef struct _AttrKeyValue AttrKeyValue;
66 struct _AttrKeyValue {
67         gchar *key;
68         gchar *value;
69 };
70
71 /**
72  * Structure to hold contact information.
73  * Each addressbook will have 0..N contacts.
74  */
75 typedef struct _EmailKeyValue EmailKeyValue;
76 struct _EmailKeyValue {
77         gchar *mail;
78         gchar *alias;
79         gchar *remarks;
80 };
81
82 /**
83  * Structure to hold information about RDN.
84  */
85 typedef struct _Rdn Rdn;
86 struct _Rdn {
87         gchar *attribute;
88         gchar *value;
89         gchar *new_dn;
90 };
91
92 /**
93  * Retrieve address group item for update.
94  * \param group  Group to print.
95  * \param array  GHashTAble of item_group, or <i>NULL</i> if none created.
96  */
97 void ldapsvr_retrieve_item_group(ItemGroup *group, GHashTable *array) {
98         /* Not implemented in this release */
99         g_return_if_fail(group != NULL);
100 }
101
102 /**
103  * Create an initial EmailKeyValue structure
104  * \return empty structure
105  */
106 EmailKeyValue *emailkeyvalue_create() {
107         EmailKeyValue *buf;
108
109         buf = g_new0(EmailKeyValue, 1);
110         buf->alias = NULL;
111         buf->mail = NULL;
112         buf->remarks = NULL;
113         return buf;
114 }
115
116 /**
117  * Create an initial AttrKeyValue structure
118  * \return empty structure
119  */
120 AttrKeyValue *attrkeyvalue_create() {
121         AttrKeyValue *buf;
122
123         buf = g_new0(AttrKeyValue, 1);
124         buf->key = NULL;
125         buf->value = NULL;
126         return buf;
127 }
128
129 /**
130  * Free created AttrKeyValue structure
131  * \param akv AttrKeyValue structure to free
132  */
133 void attrkeyvalue_free(AttrKeyValue *akv) {
134         if (akv->key) {
135                 g_free(akv->key);
136                 akv->key = NULL;
137         }
138         if (akv->value) {
139                 g_free(akv->value);
140                 akv->value = NULL;
141         }
142         g_free(akv);
143         akv = NULL;
144 }
145
146 /**
147  * Retrieve E-Mail address object for update.
148  * \param item   ItemEmail to update.
149  * \return object, or <i>NULL</i> if none created.
150  */
151 EmailKeyValue *ldapsvr_retrieve_item_email(ItemEMail *item) {
152         EmailKeyValue *newItem;
153         g_return_val_if_fail(item != NULL, NULL);
154         newItem = emailkeyvalue_create();               
155         newItem->alias = g_strdup(ADDRITEM_NAME(item));
156         newItem->mail = g_strdup(item->address);
157         newItem->remarks = g_strdup(item->remarks);
158         return newItem;
159 }
160
161 /**
162  * Retrieve user attribute object for update.
163  * \param item   UserAttribute to update.
164  * \return object, or <i>NULL</i> if none created.
165  */
166 AttrKeyValue *ldapsvr_retrieve_attribute(UserAttribute *item) {
167         AttrKeyValue *newItem;
168         g_return_val_if_fail(item != NULL, NULL);
169         newItem = attrkeyvalue_create();
170         newItem->key = g_strdup(item->name);
171         newItem->value = g_strdup(item->value);
172         return newItem;
173 }
174
175 /**
176  * Retrieve person object for update.
177  * \param person ItemPerson to update.
178  * \param array GHashTable with user input.
179  * \return false if update is not needed, or true if update is needed.
180  */
181 gboolean ldapsvr_retrieve_item_person(ItemPerson *person, GHashTable *array) {
182         GList *node, *attr;
183
184         g_return_val_if_fail(person != NULL, FALSE);
185         switch (person->status) {
186                 case NONE: return FALSE;
187                 case ADD_ENTRY: g_hash_table_insert(array, "status", "new"); break;
188                 case UPDATE_ENTRY: g_hash_table_insert(array, "status", "update"); break;
189                 case DELETE_ENTRY: g_hash_table_insert(array, "status", "delete"); break;
190                 default: g_critical(_("ldapsvr_retrieve_item_person->Unknown status: %d"), person->status);
191         }
192         g_hash_table_insert(array, "uid", ADDRITEM_ID(person));
193         g_hash_table_insert(array, "cn", ADDRITEM_NAME(person));
194         g_hash_table_insert(array, "givenName", person->firstName);
195         g_hash_table_insert(array, "sn", person->lastName);
196         g_hash_table_insert(array, "nickName", person->nickName);
197         g_hash_table_insert(array, "dn", person->externalID);
198         node = person->listEMail;
199         attr = NULL;
200         while (node) {
201                 EmailKeyValue *newEmail = ldapsvr_retrieve_item_email(node->data);
202                 if (newEmail)
203                         attr = g_list_append(attr, newEmail);
204                 node = g_list_next(node);
205         }
206         g_hash_table_insert(array, "mail", attr);
207         node = person->listAttrib;
208         attr = NULL;
209         while (node) {
210                 AttrKeyValue *newAttr = ldapsvr_retrieve_attribute(node->data);
211                 if (newAttr)
212                         attr = g_list_append(attr, newAttr);
213                 node = g_list_next(node);
214         }
215         g_hash_table_insert(array, "attribute", attr);
216         return TRUE;
217 }
218
219 /**
220  * Print contents of contacts hashtable for debug.
221  * This function must be called with g_hash_table_foreach.
222  * \param key Key to process.
223  * \param data Data to process.
224  * \param fd Output stream.
225  */
226 void ldapsvr_print_contacts_hashtable(gpointer key, gpointer data, gpointer fd) {
227         gchar *keyName = (gchar *) key;
228         GList *node;
229
230         if (g_ascii_strcasecmp("mail", keyName) == 0) {
231                 node = (GList *) data;
232                 while (node) {
233                         EmailKeyValue *item = node->data;
234                         if (debug_get_mode()) {
235                                 debug_print("\t\talias = %s\n", item->alias?item->alias:"null");
236                                 debug_print("\t\tmail = %s\n", item->mail?item->mail:"null");
237                                 debug_print("\t\tremarks = %s\n", item->remarks?item->remarks:"null");
238                         }
239                         else if (fd) {
240                                 FILE *stream = (FILE *) fd;
241                                 fprintf(stream, "\t\talias = %s\n", item->alias?item->alias:"null");
242                                 fprintf(stream, "\t\tmail = %s\n", item->mail?item->mail:"null");
243                                 fprintf(stream, "\t\tremarks = %s\n", item->remarks?item->remarks:"null");
244                         }
245                         node = g_list_next(node);
246                 }
247         }
248         else if (g_ascii_strcasecmp("attribute", keyName) == 0) {
249                 node = (GList *) data;
250                 while (node) {
251                         AttrKeyValue *item = node->data;
252                         if (debug_get_mode()) {
253                                 debug_print("\t\t%s = %s\n", item->key?item->key:"null",
254                                                 item->value?item->value:"null");
255                         }
256                         else if (fd) {
257                                 FILE *stream = (FILE *) fd;
258                                 fprintf(stream, "\t\t%s = %s\n", item->key?item->key:"null",
259                                                 item->value?item->value:"null");
260                         }
261                         node = g_list_next(node);
262                 }
263         }
264         else {
265                 if (debug_get_mode())
266                         debug_print("\t\t%s = %s\n", keyName?keyName:"null", data?(gchar *)data:"null");
267                 else if (fd) {
268                         FILE *stream = (FILE *) fd;
269                         fprintf(stream, "\t\t%s = %s\n", keyName?keyName:"null", data?(gchar *)data:"null");
270                 }
271         }
272 }
273
274 /**
275  * Free list of changed contacts
276  *
277  * \param list List of GHashTable
278  */
279 void ldapsvr_free_hashtable(GList *list) {
280         GList *tmp = list;
281         while (tmp) {
282                 g_hash_table_destroy(tmp->data);
283                 tmp->data = NULL;
284                 tmp = g_list_next(tmp);
285         }
286         g_list_free(list);
287         list = NULL;
288 }
289
290 /**
291  * Get person object from cache
292  *
293  * \param server Resource to LDAP
294  * \param uid PersonID in cache
295  * \return person object, or <i>NULL</i> if fail
296  */
297 ItemPerson *ldapsvr_get_contact(LdapServer *server, gchar *uid) {
298         AddrItemObject *aio;
299         g_return_val_if_fail(server != NULL || uid != NULL, NULL);
300         aio = addrcache_get_object(server->addressCache, uid);
301         if (aio) {
302                 if(aio->type == ITEMTYPE_PERSON) {
303                         return (ItemPerson *) aio;
304                 }
305         }
306         return NULL;
307 }
308
309 /**
310  * Connect to LDAP server.
311  * \param  ctl Control object to process.
312  * \return LDAP Resource to LDAP.
313  */
314 LDAP *ldapsvr_connect(LdapControl *ctl) {
315         LDAP *ld = NULL;
316         gint rc;
317         gint version;
318         gchar *uri = NULL;
319
320         g_return_val_if_fail(ctl != NULL, NULL);
321
322         ldapsrv_set_options (ctl->timeOut, NULL);
323         uri = g_strdup_printf("ldap%s://%s:%d",
324                                 ctl->enableSSL?"s":"",
325                                 ctl->hostName, ctl->port);
326         ldap_initialize(&ld, uri);
327         g_free(uri);
328
329         if (ld == NULL)
330                 return NULL;
331
332
333         debug_print("connected to LDAP host %s on port %d\n", ctl->hostName, ctl->port);
334
335 #ifdef USE_LDAP_TLS
336         /* Handle TLS */
337         version = LDAP_VERSION3;
338         rc = ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version);
339         if (rc == LDAP_OPT_SUCCESS) {
340                 ctl->version = LDAP_VERSION3;
341         }
342
343         if (ctl->version == LDAP_VERSION3) {
344                 if (ctl->enableTLS && !ctl->enableSSL) {
345                         rc = ldap_start_tls_s(ld, NULL, NULL);
346                         
347                         if (rc != LDAP_SUCCESS) {
348                                 g_printerr("LDAP Error(tls): ldap_simple_bind_s: %s\n",
349                                         ldap_err2string(rc));
350                                 return NULL;
351                         }
352                 }
353         }
354 #endif
355
356         /* Bind to the server, if required */
357         if (ctl->bindDN) {
358                 if (* ctl->bindDN != '\0') {
359                         rc = claws_ldap_simple_bind_s(ld, ctl->bindDN, ctl->bindPass);
360                         if (rc != LDAP_SUCCESS) {
361                                 g_printerr("bindDN: %s, bindPass: %s\n", ctl->bindDN, ctl->bindPass);
362                                 g_printerr("LDAP Error(bind): ldap_simple_bind_s: %s\n",
363                                         ldap_err2string(rc));
364                                 return NULL;
365                         }
366                 }
367         }
368         return ld;
369 }
370
371 /**
372  * Disconnect to LDAP server.
373  * \param ld Resource to LDAP.
374  */
375 void ldapsvr_disconnect(LDAP *ld) {
376         /* Disconnect */
377         g_return_if_fail(ld != NULL);
378         ldap_unbind_ext(ld, NULL, NULL);
379 }
380
381 /**
382  * Create an initial Rdn structure
383  *
384  * \return empty structure
385  */
386 Rdn *rdn_create() {
387         Rdn *buf;
388
389         buf = g_new0(Rdn, 1);
390         buf->attribute = NULL;
391         buf->value = NULL;
392         buf->new_dn = NULL;
393         return buf;
394 }
395
396 /**
397  * Free a created Rdn structure
398  * \param rdn Structure to free
399  */
400 void rdn_free(Rdn *rdn) {
401         if (rdn->attribute) {
402                 g_free(rdn->attribute);
403                 rdn->attribute = NULL;
404         }
405         if (rdn->value) {
406                 g_free(rdn->value);
407                 rdn->value = NULL;
408         }
409         if (rdn->new_dn) {
410                 g_free(rdn->new_dn);
411                 rdn->new_dn = NULL;
412         }
413         g_free(rdn);
414         rdn = NULL;
415 }
416
417 /**
418  * update Rdn structure
419  *
420  * \param rdn Rdn structure to update
421  * \param head Uniq part of dn
422  * \param tail Common part of dn
423  */
424 void update_rdn(Rdn *rdn, gchar *head, gchar *tail) {
425         rdn->value = g_strdup(head);
426         rdn->new_dn = g_strdup_printf("mail=%s%s", head, tail);
427 }
428
429 /**
430  * Deside if dn needs to be changed
431  *
432  * \param hash GHashTable with user input.
433  * \param dn dn for current object
434  * \return Rdn structure
435  */
436 Rdn *ldapsvr_modify_dn(GHashTable *hash, gchar *dn) {
437         Rdn *rdn;
438         gchar *pos, *compare;
439         gchar *rest;
440         gchar *val;
441         g_return_val_if_fail(hash != NULL || dn != NULL, NULL);
442         
443         pos = g_strstr_len(dn, strlen(dn), "=");
444         compare = g_strndup(dn, pos - dn);
445
446         if (!pos)
447                 return NULL;
448         pos++;
449         rest = g_strstr_len(pos, strlen(pos), ",");
450         val = g_strndup(pos, rest - pos);
451         if (val == NULL) {
452                 if (compare)
453                         g_free(compare);
454                 return NULL;
455         }
456         rdn = rdn_create();
457         rdn->value = g_strdup(val);
458         rdn->attribute = g_strdup(compare);
459         g_free(val);
460         if (strcmp("mail", rdn->attribute) == 0) {
461                 GList *list = g_hash_table_lookup(hash, rdn->attribute);
462                 while (list) {
463                         EmailKeyValue *item = list->data;
464                         compare = g_strdup((gchar *) item->mail);
465                         if (strcmp(compare, rdn->value) == 0) {
466                                 update_rdn(rdn, compare, rest);
467                                 g_free(compare);
468                                 return rdn;
469                         }
470                         list = g_list_next(list);
471                 }
472                 /* if compare and rdn->attribute are equal then last email removed/empty  */
473                 if (strcmp(compare, rdn->attribute) != 0) {
474                         /* RDN changed. Find new */
475                         update_rdn(rdn, compare, rest);
476                         g_free(compare);
477                         return rdn;
478                 }
479                 else {
480                         /* We cannot remove dn */
481                         g_free(compare);
482                         rdn_free(rdn);
483                         return NULL;
484                 }
485         }
486         else {
487                 compare = g_hash_table_lookup(hash, rdn->attribute);
488                 /* if compare and rdn->attribute are equal then dn removed/empty */
489                 if (strcmp(compare, rdn->attribute) != 0) {
490                         update_rdn(rdn, compare, rest);
491                         return rdn;
492                 }
493                 else {
494                         /* We cannot remove dn */
495                         rdn_free(rdn);
496                         return NULL;
497                 }
498         }
499         rdn_free(rdn);
500         return NULL;
501 }
502
503 /**
504  * This macro is borrowed from the Balsa project
505  * Creates a LDAPMod structure
506  *
507  * \param mods Empty LDAPMod structure
508  * \param modarr Array with values to insert
509  * \param op Operation to perform on LDAP
510  * \param attr Attribute to insert
511  * \param strv Empty array which is NULL terminated
512  * \param val Value for attribute
513  */
514 #define SETMOD(mods,modarr,op,attr,strv,val) \
515    do { (mods) = &(modarr); (modarr).mod_type=attr; (modarr).mod_op=op;\
516         (strv)[0]=(val); (modarr).mod_values=strv; \
517       } while(0)
518
519 /**
520  * Creates a LDAPMod structure
521  *
522  * \param mods Empty LDAPMod structure
523  * \param modarr Array with values to insert
524  * \param op Operation to perform on LDAP
525  * \param attr Attribute to insert
526  * \param strv Array with values to insert. Must be NULL terminated
527  */
528 #define SETMODS(mods,modarr,op,attr,strv) \
529    do { (mods) = &(modarr); (modarr).mod_type=attr; \
530                 (modarr).mod_op=op; (modarr).mod_values=strv; \
531       } while(0)
532 #define MODSIZE 10
533
534 /**
535  * Clean up, close LDAP connection, and refresh cache
536  *
537  * \param ld Resource to LDAP
538  * \param server AddressBook resource
539  * \param contact GHashTable with current changed object
540  */
541 void clean_up(LDAP *ld, LdapServer *server, GHashTable *contact) {
542         ItemPerson *person = 
543                 ldapsvr_get_contact(server, g_hash_table_lookup(contact , "uid"));
544         if (person) {
545                 gchar *displayName;
546                 person->status = NONE;
547                 displayName = g_hash_table_lookup(contact, "displayName");
548                 if (displayName)
549                         person->nickName = g_strdup(displayName);
550         }
551         if (server->retVal != LDAPRC_SUCCESS) {
552                 if (person) {
553                         ItemPerson *res = 
554                                 addrcache_remove_person(server->addressCache, person);
555                         if (!res)
556                                 g_critical(N_("ldapsvr_update_book: Could not clean cache\n"));
557                         else
558                                 addritem_free_item_person(res);
559                 }
560         }
561         if (ld)
562                 ldapsvr_disconnect(ld);
563 }
564
565 /**
566  * Get cn attribute from dn
567  *
568  * \param dn Distinguesh Name for current object
569  * \return AttrKeyValue, or <i>NULL</i> if none created
570  */
571 AttrKeyValue *get_cn(gchar *dn) {
572         AttrKeyValue *cn;
573         gchar *start;
574         gchar *end;
575         gchar *item;
576         gchar **key_value;
577         g_return_val_if_fail(dn != NULL, NULL);
578         
579         cn = attrkeyvalue_create();
580         start = g_strstr_len(dn, strlen(dn), "cn");
581         if (start == NULL) {
582                 attrkeyvalue_free(cn);
583                 return NULL;
584         }
585         end = g_strstr_len(start, strlen(start), ",");
586         item = g_strndup(start, end - start);
587         if (item == NULL) {
588                 attrkeyvalue_free(cn);
589                 return NULL;
590         }
591         key_value = g_strsplit(item, "=", 2);
592         cn->key = g_strdup(key_value[0]);
593         cn->value = g_strdup(key_value[1]);
594         g_strfreev(key_value);
595         g_free(item);
596         return cn;
597 }
598
599 /**
600  * Get mail attribute from dn
601  *
602  * \param dn Distinguesh Name for current object
603  * \return AttrKeyValue, or <i>NULL</i> if none created
604  */
605 AttrKeyValue *get_mail(gchar *dn) {
606         AttrKeyValue *mail;
607         gchar *start;
608         gchar *end;
609         gchar *item;
610         gchar **key_value;
611         g_return_val_if_fail(dn != NULL, NULL);
612         
613         mail = attrkeyvalue_create();
614         start = g_strstr_len(dn, strlen(dn), "mail");
615         if (start == NULL) {
616                 attrkeyvalue_free(mail);
617                 return NULL;
618         }
619         end = g_strstr_len(start, strlen(start), ",");
620         item = g_strndup(start, end - start);
621         if (item == NULL) {
622                 attrkeyvalue_free(mail);
623                 return NULL;
624         }
625         key_value = g_strsplit(item, "=", 2);
626         mail->key = g_strdup(key_value[0]);
627         mail->value = g_strdup(key_value[1]);
628         g_strfreev(key_value);
629         g_free(item);
630         return mail;
631 }
632
633 /**
634  * Get ou or o attribute from dn
635  *
636  * \param dn Distinguesh Name for current object
637  * \return AttrKeyValue, or <i>NULL</i> if none created
638  */
639 AttrKeyValue *get_ou(gchar *dn) {
640         AttrKeyValue *ou;
641         gchar *start;
642         gchar *end;
643         gchar *item;
644         gchar **key_value;
645         
646         g_return_val_if_fail(dn != NULL, NULL);
647         ou = attrkeyvalue_create();
648         start = g_strstr_len(dn, strlen(dn), ",o=");
649         if (start == NULL)
650                 start = g_strstr_len(dn, strlen(dn), ",ou=");
651         if (start == NULL) {
652                 attrkeyvalue_free(ou);
653                 return NULL;
654         }
655         start++;
656         end = g_strstr_len(start, strlen(start), ",");
657         item = g_strndup(start, end - start);
658         if (item == NULL) {
659                 attrkeyvalue_free(ou);
660                 return NULL;
661         }
662         key_value = g_strsplit(item, "=", 2);
663         ou->key = g_strdup(key_value[0]);
664         ou->value = g_strdup(key_value[1]);
665         g_strfreev(key_value);
666         g_free(item);
667         return ou;
668 }
669
670 /**
671  * Print the contents of a LDAPMod structure for debuging purposes
672  *
673  * \param mods LDAPMod structure
674  */
675 void ldapsvr_print_ldapmod(LDAPMod *mods[]) {
676         gchar *mod_op;
677         int i;
678
679         g_return_if_fail(mods != NULL);
680         g_printerr( "Type\n");
681         for (i = 0; NULL != mods[i]; i++) {
682                 LDAPMod *mod = (LDAPMod *) mods[i];
683                 gchar **vals;
684                 switch (mod->mod_op) {
685                         case LDAP_MOD_ADD: mod_op = g_strdup("ADD"); break;
686                         case LDAP_MOD_REPLACE: mod_op = g_strdup("MODIFY"); break;
687                         case LDAP_MOD_DELETE: mod_op = g_strdup("DELETE"); break;
688                         default: mod_op = g_strdup("UNKNOWN");
689                 }
690                 g_printerr( "Operation: %s\tType:%s\nValues:\n", mod_op, mod->mod_type);
691                 vals = mod->mod_vals.modv_strvals;
692                 while (*vals) {
693                         g_printerr( "\t%s\n", *vals++);
694                 }
695         }
696 }
697
698 /**
699  * Make a compare for every new value we want to store in the
700  * directory with the current values. Great tool for debugging
701  * against invalid syntax in attributes
702  *
703  * \param ld AddressBook resource
704  * \param dn dn for the entry
705  * \param cnt Number of attributes to compare
706  * \param  mods LDAPMod structure
707  */
708 void ldapsvr_compare_attr(LDAP *ld, gchar *dn, gint cnt, LDAPMod *mods[]) {
709         int i, rc;
710         
711         g_return_if_fail(ld != NULL || dn != NULL || cnt >= 0 || mods != NULL);
712         for (i = 0; i < cnt; i++) {
713                 gchar *value = g_strdup(mods[i]->mod_vals.modv_strvals[0]);
714                 if (!value || strcmp(value, "") == 0)
715                         value = g_strdup("thisisonlyadummy");
716                 rc = ldap_compare_s(ld, dn, mods[i]->mod_type, value);
717                 g_printerr("ldap_compare for (%s:%s)\" failed[0x%x]: %s\n",
718                 mods[i]->mod_type, value, rc, ldap_err2string(rc));
719                 g_free(value);
720         }
721 }
722
723 /**
724  * compare attribute to LDAP in case of LDAP_INAPPROPRIATE_MATCHING
725  *
726  * \param ld AddressBook resource
727  * \param server Reference to server
728  * \param dn dn for the entry
729  * \param attr Attribute
730  * \param value New value
731  * \return int, return will be LDAP_MOD_ADD, LDAP_MOD_REPLACE, or LDAP_MOD_DELETE
732  */
733 int ldapsvr_compare_manual_attr(LDAP *ld, LdapServer *server, gchar *dn, char *attr, char *value) {
734         LDAPMessage *res, *e = NULL;
735         BerElement *ber;
736         struct berval **vals;
737         int rc;
738         LdapControl *ctl;
739         gchar *filter;
740         gchar *attribute;
741         int retVal = -2, i;
742         AttrKeyValue *mail;
743
744         g_return_val_if_fail(ld != NULL || server != NULL || attr != NULL, -1);
745         ctl = server->control;
746         mail = get_mail(dn);
747         if (! mail)
748                 return -2;
749         filter = g_strdup_printf("(&(mail=%s)(%s=*))", mail->value, attr);
750         attrkeyvalue_free(mail);
751         if (ctl) {
752                 rc = ldap_search_s(ld, ctl->baseDN, /*LDAP_SCOPE_SUBTREE*/LDAP_SCOPE_ONELEVEL, filter, NULL, 0, &res);
753                 if (rc) {
754                         g_printerr("ldap_search for attr=%s\" failed[0x%x]: %s\n",attr, rc, ldap_err2string(rc));
755                         retVal = -2;
756                 }
757                 else {
758                         e = ldap_first_entry(ld, res);
759                         /* entry has this attribute */
760                         if (e) {
761                                 attribute = ldap_first_attribute( ld, e, &ber );
762                                 if (attribute) {
763                                         if (value) {
764                                                 if( ( vals = ldap_get_values_len( ld, e, attr ) ) != NULL ) {
765                                                         for( i = 0; vals[i] != NULL; i++ ) {
766                                                                 debug_print("Compare: %s=%s\n", attr, vals[i]->bv_val);
767                                                                 /* attribute has same value */
768                                                                 if (strcmp(vals[i]->bv_val, value) == 0)
769                                                                         retVal = -1;
770                                                                 /* attribute has new value */
771                                                                 else
772                                                                         retVal = LDAP_MOD_REPLACE;
773                                                         }
774                                                 }
775                                                 ldap_value_free_len(vals);
776                                         }
777                                         else
778                                                 retVal = LDAP_MOD_DELETE;
779                                 }
780                                 if( ber != NULL ) {
781                                         ber_free( ber, 0 );
782                                 }
783                                 ldap_memfree(attribute);
784                         }
785                         /* entry does not have this attribute */
786                         else {
787                                 /* Only add if this is a real attribute */
788                                 if (value)
789                                         retVal = LDAP_MOD_ADD;
790                                 /* This is dummy value used to avoid ldap_compare error */
791                                 else
792                                         retVal = -1;
793                         }
794                 }
795         }
796         else
797                 retVal = -2;
798         g_free(filter);
799         return retVal;
800 }
801
802 /**
803  * Deside which kind of operation is required to handle
804  * updating the specified attribute
805  *
806  * \param ld AddressBook resource
807  * \param server Reference to server
808  * \param dn dn for the entry
809  * \param attr Attribute
810  * \param value New value
811  * \return int, return will be LDAP_MOD_ADD, LDAP_MOD_REPLACE, or LDAP_MOD_DELETE
812  */
813 int ldapsvr_deside_operation(LDAP *ld, LdapServer *server, char *dn, char *attr, char *value) {
814         int rc;
815         gboolean dummy = FALSE;
816
817         g_return_val_if_fail(ld != NULL || server != NULL || dn != NULL || attr != NULL, -1);
818         if (value == NULL)
819                 return -1;
820         /* value containing empty string cause invalid syntax. A bug in
821          * the LDAP library? Therefore we add a dummy value
822          */
823         if (strcmp(value,"") == 0) {
824                 value = g_strdup("thisisonlyadummy");
825                 dummy = TRUE;
826         }
827         rc = ldap_compare_s(ld, dn, attr, value);
828         debug_print("ldap_compare for (%s:%s)\" error_code[0x%x]: %s\n",
829         attr, value, rc, ldap_err2string(rc));
830         switch (rc) {
831                 case LDAP_COMPARE_FALSE: 
832                         if (dummy)
833                                 return LDAP_MOD_DELETE;
834                         else
835                                 return LDAP_MOD_REPLACE;
836                 case LDAP_COMPARE_TRUE: return -1;
837                 case LDAP_NO_SUCH_ATTRIBUTE: return LDAP_MOD_ADD;
838                 /* LDAP_INAPPROPRIATE_MATCHING needs extensive testing because I
839                  * am not aware off the condition causing this return value!
840                  */
841                 case LDAP_INAPPROPRIATE_MATCHING:
842                         if (dummy)
843                                 value = NULL;
844                         return ldapsvr_compare_manual_attr(ld, server, dn, attr, value);
845                 case LDAP_UNDEFINED_TYPE: return -2;
846                 case LDAP_INVALID_SYNTAX: return -2;
847                 default: return -2;
848         }
849 }
850
851 /**
852  * Check if attribute is part of the current search criteria
853  *
854  * \param list Array containing attributes in the current search criteria
855  * \param attr Attribute to check
856  * \result <i>TRUE</i> if attribute is found in the current search criteria
857  */
858 gboolean ldapsvr_check_search_attributes(char **list, char *attr) {
859         while (*list) {
860                 if (strcmp(*list++, attr) == 0)
861                         return TRUE;
862         }
863         return FALSE;
864 }
865
866 /**
867  * Deside which other attributes needs updating
868  *
869  * \param ld LDAP resource
870  * \param server AddressBook resource
871  * \param dn dn for the entry
872  * \param contact GHashTable with information for the current contact
873  */
874 void ldapsvr_handle_other_attributes(LDAP *ld, LdapServer *server, char *dn, GHashTable *contact) {
875         GList *node;
876         gboolean CHECKED_ATTRIBUTE[ATTRIBUTE_SIZE + 1];
877         LDAPMod *mods[ATTRIBUTE_SIZE + 1];
878         LDAPMod modarr[ATTRIBUTE_SIZE];
879         gint cnt = 0;
880         char *attr[ATTRIBUTE_SIZE + 1][2];
881         int mod_op, rc, i;
882
883         g_return_if_fail(server != NULL || dn != NULL || contact != NULL);
884         for (i = 0; i <= ATTRIBUTE_SIZE; i++) {
885                 CHECKED_ATTRIBUTE[i] = FALSE;
886                 attr[i][0] = attr[i][1] = NULL;
887         }
888         node = g_hash_table_lookup(contact , "attribute");
889         while (node) {
890                 AttrKeyValue *item = node->data;
891                 if (item) {
892                         int index = get_attribute_index(item->key);
893                         if (index >= 0) {
894                                 debug_print("Found other attribute: %s = %s\n",
895                                                 item->key?item->key:"null", item->value?item->value:"null");
896                                 mod_op = ldapsvr_deside_operation(ld, server, dn, item->key, item->value);
897                                 /* Only consider attributes which we no how to handle.
898                                  * Set to TRUE in CHECKED_ATTRIBUTE array to indicate no further action
899                                  */
900                                 if (mod_op < 0) {
901                                         CHECKED_ATTRIBUTE[index] = TRUE;
902                                         node = g_list_next(node);
903                                         continue;
904                                 }
905                                 if (mod_op == LDAP_MOD_DELETE) {
906                                         /* Setting param to NULL instructs OpenLDAP to remove any
907                                         * value stored for this attribute and remove the attribute
908                                         * completely. Should multiple instances of an attribute be
909                                         * allowed in the future param is required to have the value
910                                         * store for the attribute which is going to be deleted
911                                         */
912                                         item->value = NULL;
913                                 }
914                                 if (mod_op == LDAP_MOD_REPLACE && strcmp(item->value, "") == 0) {
915                                         /* Having an empty string is considered a syntax error in
916                                         * ldap. E.g attributes with empty strings are not allowed
917                                         * in which case we treate this as a request for deleting
918                                         * the attribute.
919                                         */
920                                         mod_op = LDAP_MOD_DELETE;
921                                         item->value = NULL;
922                                 }
923                                 if (mod_op == LDAP_MOD_ADD && strcmp(item->value, "") == 0) {
924                                         /* Adding an empty string is considered a syntax error in
925                                         * ldap. E.g attributes with empty strings are not allowed
926                                         * in which case we silently refuse to add this entry
927                                         */
928                                 }
929                                 else {
930                                         SETMOD(mods[cnt], modarr[cnt], mod_op, g_strdup(item->key), attr[cnt], g_strdup(item->value));
931                                         cnt++;
932                                         CHECKED_ATTRIBUTE[index] = TRUE;
933                                 }
934                         }
935                 }
936                 node = g_list_next(node);
937         }
938         char **attribs = ldapctl_full_attribute_array(server->control);
939         for (i = 0; i < ATTRIBUTE_SIZE; i++) {
940                 /* Attributes which holds no information are to be removed */
941                 if (CHECKED_ATTRIBUTE[i] == FALSE) {
942                         /* Only consider those attributes which is currently part of the search criteria.
943                          * If attributes are not part of the search criteria they would seem to hold
944                          * no information since their values will not be populated in the GUI
945                          */
946                         if (ldapsvr_check_search_attributes(attribs, (char *) ATTRIBUTE[i])) {
947                                 mod_op = ldapsvr_deside_operation(ld, server, dn, (char *) ATTRIBUTE[i], "");
948                                 if (mod_op == LDAP_MOD_DELETE) {
949                                         SETMOD(mods[cnt], modarr[cnt], LDAP_MOD_DELETE, g_strdup((char *) ATTRIBUTE[i]), attr[cnt], NULL);
950                                         cnt++;
951                                 }
952                         }
953                 }
954         }
955         ldapctl_free_attribute_array(attribs);
956         mods[cnt] = NULL;
957         if (debug_get_mode())
958                 ldapsvr_print_ldapmod(mods);
959         server->retVal = LDAPRC_SUCCESS;
960         rc = ldap_modify_ext_s(ld, dn, mods, NULL, NULL);
961         if (rc) {
962                 switch (rc) {
963                         case LDAP_ALREADY_EXISTS: 
964                                 server->retVal = LDAPRC_ALREADY_EXIST;
965                                 break;
966                         default:
967                                 g_printerr("ldap_modify for dn=%s\" failed[0x%x]: %s\n", dn, rc, ldap_err2string(rc));
968                                 if (rc == 0x8)
969                                         server->retVal = LDAPRC_STRONG_AUTH;
970                                 else
971                                         server->retVal = LDAPRC_NAMING_VIOLATION;
972                 }
973         }
974         else {
975                 char **attribs = ldapctl_full_attribute_array(server->control);
976                 for (i = 0; i < ATTRIBUTE_SIZE; i++) {
977                         if (ldapsvr_check_search_attributes(attribs, (char *) ATTRIBUTE[i])) {
978                                 if (CHECKED_ATTRIBUTE[i] == FALSE) {
979                                         AddrItemObject *aio = addrcache_get_object(server->addressCache, g_hash_table_lookup(contact , "uid"));
980                                         ItemPerson *person = (ItemPerson *) aio;
981                                         addritem_person_remove_attribute(person, (const gchar *) ATTRIBUTE[i]);
982                                 }
983                         }
984                 }
985                 ldapctl_free_attribute_array(attribs);
986         }
987 }
988
989 /**
990  * Add new contact to LDAP
991  *
992  * \param server AddressBook resource
993  * \param contact GHashTable with object to add
994  */
995 void ldapsvr_add_contact(LdapServer *server, GHashTable *contact) {
996         gchar *email = NULL, *param = NULL;
997         LDAP *ld = NULL;
998         LDAPMod *mods[MODSIZE];
999         LDAPMod modarr[7];
1000         gint cnt = 0;
1001         char *cn[] = {NULL, NULL};
1002         char *displayName[] = {NULL, NULL};
1003         char *givenName[] = {NULL, NULL};
1004         char **mail = NULL;
1005         char *sn[] = {NULL, NULL};
1006         char *org[] = {NULL, NULL};
1007         char *obj[] = {/*"top",*/ "person", "organizationalPerson", "inetOrgPerson", NULL}; 
1008         int rc=0;
1009         GList *node;
1010         AttrKeyValue *ou, *commonName;
1011         ItemPerson *person;
1012         gchar *base_dn;
1013         GList *mailList;
1014
1015         g_return_if_fail(server != NULL || contact != NULL);
1016         node = g_hash_table_lookup(contact , "mail");
1017         if (node) {
1018                 EmailKeyValue *newEmail = node->data;
1019                 email = g_strdup(newEmail->mail);
1020         }
1021         if (email == NULL) {
1022                 server->retVal = LDAPRC_NODN;
1023                 clean_up(ld, server, contact);
1024                 return;
1025         }
1026         base_dn = g_strdup_printf("mail=%s,%s",
1027                         email, server->control->baseDN?server->control->baseDN:"null");
1028         g_free(email);
1029         person = 
1030                 ldapsvr_get_contact(server, g_hash_table_lookup(contact , "uid"));
1031         person->externalID = g_strdup(base_dn);
1032         debug_print("dn: %s\n", base_dn);
1033         ld = ldapsvr_connect(server->control);
1034         if (ld == NULL) {
1035                 clean_up(ld, server, contact);
1036                 debug_print("no ldap found\n");
1037                 return;
1038         }
1039         SETMODS(mods[cnt], modarr[cnt], LDAP_MOD_ADD, "objectClass", obj);
1040         cnt++;
1041         ou = get_ou(base_dn);
1042         if (ou != NULL) {
1043                 SETMOD(mods[cnt], modarr[cnt], LDAP_MOD_ADD, g_strdup(ou->key), org, g_strdup(ou->value));
1044                 cnt++;
1045                 attrkeyvalue_free(ou);
1046         }
1047         
1048         commonName = get_cn(base_dn);
1049         if (commonName == NULL) {
1050                 param = g_hash_table_lookup(contact , "cn");
1051                 if (param) {
1052                         SETMOD(mods[cnt], modarr[cnt], LDAP_MOD_ADD, "cn", cn, param);
1053                 }
1054                 else {
1055                         clean_up(ld, server, contact);
1056                         debug_print("no CN found\n");
1057                         return;
1058                 }
1059         }
1060         else {
1061                 SETMOD(mods[cnt], modarr[cnt], LDAP_MOD_ADD, g_strdup(commonName->key), cn, g_strdup(commonName->value));
1062                 cnt++;
1063                 param = g_hash_table_lookup(contact , "cn");
1064                 SETMOD(mods[cnt], modarr[cnt], LDAP_MOD_ADD, "displayName", displayName, param);
1065                 g_hash_table_insert(contact, "displayName", param);
1066                 attrkeyvalue_free(commonName);
1067         }
1068         cnt++;
1069         param = g_hash_table_lookup(contact , "givenName");
1070         if (param) {
1071                 SETMOD(mods[cnt], modarr[cnt], LDAP_MOD_ADD, "givenName", givenName, param);
1072                 cnt++;
1073         }
1074         mailList = g_hash_table_lookup(contact , "mail");
1075         if (mailList) {
1076                 char **tmp;
1077                 tmp = g_malloc(sizeof(*tmp) * (g_list_length(mailList)+1));
1078                 mail = tmp;
1079                 while (mailList) {
1080                         EmailKeyValue *item = mailList->data;
1081                         *tmp++ = g_strdup((gchar *) item->mail);
1082                         mailList = g_list_next(mailList);
1083                 }
1084                 *tmp = NULL;
1085                 SETMODS(mods[cnt], modarr[cnt], LDAP_MOD_ADD, "mail", mail);
1086                 cnt++;
1087         }
1088         param = g_hash_table_lookup(contact, "sn");
1089         if (param == NULL)
1090                 param = g_strdup(N_("Some SN"));
1091         SETMOD(mods[cnt], modarr[cnt], LDAP_MOD_ADD, "sn", sn, param);
1092         cnt++;
1093         mods[cnt] = NULL;
1094         if (debug_get_mode()) {
1095                 ldapsvr_print_ldapmod(mods);
1096         }
1097         server->retVal = LDAPRC_SUCCESS;
1098         rc = ldap_add_ext_s(ld, base_dn, mods, NULL, NULL);
1099         if (rc) {
1100                 switch (rc) {
1101                         case LDAP_ALREADY_EXISTS: 
1102                                 server->retVal = LDAPRC_ALREADY_EXIST;
1103                                 break;
1104                         default:
1105                                 g_printerr("ldap_modify for dn=%s\" failed[0x%x]: %s\n",
1106                                                 base_dn, rc, ldap_err2string(rc));
1107                                 if (rc == 0x8)
1108                                         server->retVal = LDAPRC_STRONG_AUTH;
1109                                 else
1110                                         server->retVal = LDAPRC_NAMING_VIOLATION;
1111                 }
1112         }
1113         ldapsvr_handle_other_attributes(ld, server, base_dn, contact);
1114         g_free(base_dn);
1115         clean_up(ld, server, contact);
1116 }
1117
1118 /**
1119  * Update contact to LDAP
1120  *
1121  * \param server AddressBook resource
1122  * \param contact GHashTable with object to update
1123  */
1124 void ldapsvr_update_contact(LdapServer *server, GHashTable *contact) {
1125         LDAP *ld = NULL;
1126         LDAPMod *mods[MODSIZE];
1127         LDAPMod modarr[4];
1128         gint cnt = 0;
1129         gchar *param, *dn;
1130         Rdn *NoRemove = NULL;
1131         char *cn[] = {NULL, NULL};
1132         char *givenName[] = {NULL, NULL};
1133         char **mail = NULL;
1134         char *sn[] = {NULL, NULL};
1135         GList *mailList;
1136         int mod_op;
1137
1138         g_return_if_fail(server != NULL || contact != NULL);
1139         ld = ldapsvr_connect(server->control);
1140         if (ld == NULL) {
1141                 clean_up(ld, server, contact);
1142                 return;
1143         }
1144         dn = g_hash_table_lookup(contact, "dn");
1145         if (dn == NULL) {
1146                 clean_up(ld, server, contact);
1147                 return;
1148         }
1149         NoRemove = ldapsvr_modify_dn(contact, dn);
1150         if (NoRemove) {
1151                 /* We are trying to change RDN */
1152                 gchar *newRdn = g_strdup_printf("%s=%s", NoRemove->attribute, NoRemove->value);
1153                 int rc = ldap_modrdn2_s(ld, dn, newRdn, 1);
1154                 if(rc != LDAP_SUCCESS) {
1155                         if (rc ==  LDAP_ALREADY_EXISTS) {
1156                                 /* We are messing with a contact with more than one listed email
1157                                  * address and the email we are changing is not the one used for dn
1158                                  */
1159                                 /* It needs to be able to handle renaming errors to an already defined
1160                                  * dn. For now we just refuse the update. It will be caught later on as
1161                                  * a LDAPRC_NAMING_VIOLATION error.
1162                                  */
1163                         }
1164                         else {
1165                                 g_printerr("Current dn: %s\n", dn);
1166                                 g_printerr("new dn: %s\n", newRdn);
1167                                 g_printerr("LDAP Error(ldap_modrdn2_s) failed[0x%x]: %s\n", rc, ldap_err2string(rc));
1168                                 g_free(newRdn);
1169                                 clean_up(ld, server, contact);
1170                                 return;
1171                         }
1172                 }
1173                 else {
1174                         g_free(newRdn);
1175                         dn = g_strdup(NoRemove->new_dn);
1176                 }
1177         }
1178         else {
1179                 server->retVal = LDAPRC_NODN;
1180                 clean_up(ld, server, contact);
1181                 return;
1182         }
1183         param = g_hash_table_lookup(contact , "cn");
1184         mod_op = ldapsvr_deside_operation(ld, server, dn, "displayName", param);
1185         if (mod_op >= 0 && (strcmp(param, NoRemove->value) != 0 && strcmp("cn", NoRemove->attribute) != 0)) {
1186                 if (mod_op == LDAP_MOD_DELETE) {
1187                         /* Setting param to NULL instructs OpenLDAP to remove any
1188                          * value stored for this attribute and remove the attribute
1189                          * completely. Should multiple instances of an attribute be
1190                          * allowed in the future param is required to have the value
1191                          * store for the attribute which is going to be deleted
1192                          */
1193                         param = NULL;
1194                 }
1195                 if (mod_op == LDAP_MOD_REPLACE && strcmp(param, "") == 0) {
1196                         /* Having an empty string is considered a syntax error in
1197                          * ldap. E.g attributes with empty strings are not allowed
1198                          * in which case we treate this as a request for deleting
1199                          * the attribute.
1200                          */
1201                         mod_op = LDAP_MOD_DELETE;
1202                         param = NULL;
1203                 }
1204                 if (mod_op == LDAP_MOD_ADD && strcmp(param, "") == 0) {
1205                         /* Adding an empty string is considered a syntax error in
1206                          * ldap. E.g attributes with empty strings are not allowed
1207                          * in which case we silently refuse to add this entry
1208                          */
1209                 }
1210                 else {
1211                         SETMOD(mods[cnt], modarr[cnt], mod_op, "displayName", cn, param);
1212                         cnt++;
1213                         g_hash_table_insert(contact, "displayName", param);
1214                 }
1215         }
1216         param = g_hash_table_lookup(contact , "givenName");
1217         mod_op = ldapsvr_deside_operation(ld, server, dn, "givenName", param);
1218         if (mod_op >= 0 && (strcmp(param, NoRemove->value) != 0 && strcmp("givenName", NoRemove->attribute) != 0)) {
1219                 if (mod_op == LDAP_MOD_DELETE) {
1220                         /* Setting param to NULL instructs OpenLDAP to remove any
1221                          * value stored for this attribute and remove the attribute
1222                          * completely. Should multiple instances of an attribute be
1223                          * allowed in the future param is required to have the value
1224                          * store for the attribute which is going to be deleted
1225                          */
1226                         param = NULL;
1227                 }
1228                 if (mod_op == LDAP_MOD_REPLACE && strcmp(param, "") == 0) {
1229                         /* Having an empty string is considered a syntax error in
1230                          * ldap. E.g attributes with empty strings are not allowed
1231                          * in which case we treate this as a request for deleting
1232                          * the attribute.
1233                          */
1234                         mod_op = LDAP_MOD_DELETE;
1235                         param = NULL;
1236                 }
1237                 if (mod_op == LDAP_MOD_ADD && strcmp(param, "") == 0) {
1238                         /* Adding an empty string is considered a syntax error in
1239                          * ldap. E.g attributes with empty strings are not allowed
1240                          * in which case we silently refuse to add this entry
1241                          */
1242                 }
1243                 else {
1244                         SETMOD(mods[cnt], modarr[cnt], mod_op, "givenName", givenName, param);
1245                         cnt++;
1246                 }
1247         }
1248         mailList = g_hash_table_lookup(contact , "mail");
1249         if (mailList) {
1250                 debug_print("# of mail: %d\n", g_list_length(mailList));
1251                 if (!(strcmp("mail", NoRemove->attribute) == 0 && g_list_length(mailList) == 1)) {
1252                         char **tmp;
1253                         tmp = g_malloc(sizeof(*tmp) * (g_list_length(mailList)+1));
1254                         mail = tmp;
1255                         while (mailList) {
1256                                 EmailKeyValue *item = mailList->data;
1257                                 *tmp++ = g_strdup((gchar *) item->mail);
1258                                 mailList = g_list_next(mailList);
1259                         }
1260                         *tmp = NULL;
1261                         /*
1262                          * At least one email address is required
1263                          * in which case it will always be a replace
1264                          */
1265                         SETMODS(mods[cnt], modarr[cnt], LDAP_MOD_REPLACE, "mail", mail);
1266                         cnt++;
1267                 }
1268         }
1269         else {
1270                 /*
1271                  * an error condition since at least one email adress
1272                  * is required. Should never occur though.
1273                  */
1274         }
1275         param = g_hash_table_lookup(contact , "sn");
1276         mod_op = ldapsvr_deside_operation(ld, server, dn, "sn", param);
1277         if (mod_op >= 0 && (strcmp(param, NoRemove->value) != 0 && strcmp("sn", NoRemove->attribute) != 0)) {
1278                 if (mod_op == LDAP_MOD_DELETE) {
1279                         /* Setting param to NULL instructs OpenLDAP to remove any
1280                          * value stored for this attribute and remove the attribute
1281                          * completely. Should multiple instances of an attribute be
1282                          * allowed in the future param is required to have the value
1283                          * store for the attribute which is going to be deleted
1284                          */
1285                         param = NULL;
1286                 }
1287                 if (mod_op == LDAP_MOD_REPLACE && strcmp(param, "") == 0) {
1288                         /* Having an empty string is considered a syntax error in
1289                          * ldap. E.g attributes with empty strings are not allowed
1290                          * in which case we treate this as a request for deleting
1291                          * the attribute.
1292                          */
1293                         mod_op = LDAP_MOD_DELETE;
1294                         param = NULL;
1295                 }
1296                 if (mod_op == LDAP_MOD_ADD && strcmp(param, "") == 0) {
1297                         /* Adding an empty string is considered a syntax error in
1298                          * ldap. E.g attributes with empty strings are not allowed
1299                          * in which case we silently refuse to add this entry
1300                          */
1301                 }
1302                 else {
1303                         SETMOD(mods[cnt], modarr[cnt], mod_op, "sn", sn, param);
1304                         cnt++;
1305                 }
1306         }
1307         debug_print("newDN: %s\n", dn);
1308         if (NoRemove)
1309                 rdn_free(NoRemove);
1310         server->retVal = LDAPRC_SUCCESS;
1311         if (cnt > 0) {
1312                 int rc;
1313                 mods[cnt] = NULL;
1314                 rc = ldap_modify_ext_s(ld, dn, mods, NULL, NULL);
1315                 if (rc) {
1316                         g_printerr("ldap_modify for dn=%s\" failed[0x%x]: %s\n",
1317                     dn, rc, ldap_err2string(rc));
1318                         server->retVal = LDAPRC_NAMING_VIOLATION;
1319                 }
1320                 if (mail)
1321                         g_free(mail);
1322         }
1323         ldapsvr_handle_other_attributes(ld, server, dn, contact);
1324         /* If we do not make changes persistent at this point then changes
1325          * will be lost if the user makes new search on the same server since
1326          * changes are only present in Claws' internal cache. This issue has to
1327          * be solved in addressbook.c since this involves access to structures
1328          * which are only accessible in addressbook.c */
1329         clean_up(ld, server, contact);
1330 }
1331
1332 /**
1333  * Delete contact from LDAP
1334  *
1335  * \param server AddressBook resource
1336  * \param contact GHashTable with object to delete
1337  */
1338 void ldapsvr_delete_contact(LdapServer *server, GHashTable *contact) {
1339         LDAP *ld = NULL;
1340         gchar *dn;
1341         int rc;
1342
1343         g_return_if_fail(server != NULL || contact != NULL);
1344         ld = ldapsvr_connect(server->control);
1345         if (ld == NULL) {
1346                 clean_up(ld, server, contact);
1347                 return;
1348         }
1349         dn = g_hash_table_lookup(contact, "dn");
1350         if (dn == NULL) {
1351                 clean_up(ld, server, contact);
1352                 return;
1353         }
1354         server->retVal = LDAPRC_SUCCESS;
1355         rc = ldap_delete_ext_s(ld, dn, NULL, NULL);
1356         if (rc) {
1357                 g_printerr("ldap_modify for dn=%s\" failed[0x%x]: %s\n",
1358                                 dn, rc, ldap_err2string(rc));
1359                 server->retVal = LDAPRC_NODN;
1360         }
1361         clean_up(ld, server, contact);
1362 }
1363
1364 /**
1365  * Update any changes to the server.
1366  *
1367  * \param server AddressBook resource.
1368  * \param person ItemPerson holding user input.
1369  */
1370 void ldapsvr_update_book(LdapServer *server, ItemPerson *item) {
1371         GList *node = NULL;
1372         GHashTable *contact = NULL;
1373         GList *contacts = NULL, *head = NULL;
1374
1375         g_return_if_fail(server != NULL);
1376         debug_print("updating ldap addressbook\n");
1377
1378         contact = g_hash_table_new(g_str_hash, g_str_equal);
1379         if (item) {
1380                 gboolean result = ldapsvr_retrieve_item_person(item, contact);
1381                 debug_print("Found contact to update: %s\n", result? "Yes" : "No");
1382                 if (result) {
1383                         if (debug_get_mode()) {
1384                                 addritem_print_item_person(item, stdout);
1385                         }
1386                         contacts = g_list_append(contacts, contact);
1387                 }
1388         }
1389         else {
1390                 ItemFolder *folder = server->addressCache->rootFolder;
1391                 node = folder->listFolder;
1392                 if (node) {
1393                         while (node) {
1394                                 AddrItemObject *aio = node->data;
1395                                 if (aio) {
1396                                         if (aio->type == ITEMTYPE_FOLDER) {
1397                                                 ItemFolder *folder = (ItemFolder *) aio;
1398                                                 GList *persons = folder->listPerson;
1399                                                 while (persons) {
1400                                                         AddrItemObject *aio = persons->data;
1401                                                         if (aio) {
1402                                                                 if (aio->type == ITEMTYPE_PERSON) {
1403                                                                         ItemPerson *item = (ItemPerson *) aio;
1404                                                                         gboolean result = ldapsvr_retrieve_item_person(item, contact);
1405                                                                         debug_print("Found contact to update: %s\n", result? "Yes" : "No");
1406                                                                         if (result) {
1407                                                                                 if (debug_get_mode()) {
1408                                                                                         gchar *uid = g_hash_table_lookup(contact, "uid");
1409                                                                                         item = ldapsvr_get_contact(server, uid);
1410                                                                                         addritem_print_item_person(item, stdout);
1411                                                                                 }
1412                                                                                 contacts = g_list_append(contacts, contact);
1413                                                                         }
1414                                                                 }
1415                                                         }
1416                                                         persons = g_list_next(persons);
1417                                                 }
1418                                         }
1419                                 }
1420                                 else {
1421                                         g_printerr("\t\tpid : ???\n");
1422                                 }
1423                                 node = g_list_next(node);
1424                         }
1425                 }
1426         }
1427         head = contacts;
1428         if (debug_get_mode()) {
1429                 if (contacts)
1430                         debug_print("Contacts which must be updated in LDAP:\n");
1431                 while (contacts) {
1432                         debug_print("\tContact:\n");
1433                         g_hash_table_foreach(contacts->data, 
1434                                 ldapsvr_print_contacts_hashtable, stderr);
1435                         contacts = g_list_next(contacts);
1436                 }
1437         }
1438         if (contacts == NULL)
1439                 contacts = head;
1440         while (contacts) {
1441                 gchar *status;
1442                 contact = (GHashTable *) contacts->data;
1443                 status = (gchar *) g_hash_table_lookup(contact, "status");
1444                 if (status == NULL)
1445                         status = g_strdup("NULL");
1446                 if (g_ascii_strcasecmp(status, "new") == 0) {
1447                         ldapsvr_add_contact(server, contact);
1448                 }
1449                 else if (g_ascii_strcasecmp(status, "update") == 0) {
1450                         ldapsvr_update_contact(server, contact);
1451                 }
1452                 else if (g_ascii_strcasecmp(status, "delete") == 0) {
1453                         ldapsvr_delete_contact(server, contact);
1454                 }
1455                 else
1456                         g_critical(_("ldapsvr_update_book->Unknown status: %s\n"), status);
1457                 contacts = g_list_next(contacts);
1458         }
1459         ldapsvr_free_hashtable(head);
1460 }
1461
1462 #endif  /* USE_LDAP */
1463
1464 /*
1465  * End of Source.
1466  */
1467