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