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