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