Merge branch 'master' into senslab2
[sfa.git] / sfa / senslab / LDAPapi.py
1 import random
2 from passlib.hash import ldap_salted_sha1 as lssha
3 from sfa.util.xrn import get_authority 
4 import ldap
5 from sfa.util.config import Config
6 from sfa.trust.hierarchy import Hierarchy
7 #from sfa.trust.certificate import *
8 import ldap.modlist as modlist
9 from sfa.util.sfalogging import logger
10 import os.path
11
12 #API for OpenLDAP
13
14
15 class LdapConfig():
16     def __init__(self, config_file =  '/etc/sfa/ldap_config.py'):
17         try:
18             execfile(config_file, self.__dict__)
19        
20             self.config_file = config_file
21             # path to configuration data
22             self.config_path = os.path.dirname(config_file)
23         except IOError:
24             raise IOError, "Could not find or load the configuration file: %s" \
25                             % config_file
26   
27         
28 class ldap_co:
29     """ Set admin login and server configuration variables."""
30     
31     def __init__(self):
32         #Senslab PROD LDAP parameters
33         self.ldapserv = None
34         ldap_config = LdapConfig()
35         self.config = ldap_config
36         self.ldapHost = ldap_config.LDAP_IP_ADDRESS 
37         self.ldapPeopleDN = ldap_config.LDAP_PEOPLE_DN
38         self.ldapGroupDN = ldap_config.LDAP_GROUP_DN
39         self.ldapAdminDN = ldap_config.LDAP_WEB_DN
40         self.ldapAdminPassword = ldap_config.LDAP_WEB_PASSWORD
41
42
43         self.ldapPort = ldap.PORT
44         self.ldapVersion  = ldap.VERSION3
45         self.ldapSearchScope = ldap.SCOPE_SUBTREE
46
47
48     def connect(self, bind = True):
49         """Enables connection to the LDAP server.
50         Set the bind parameter to True if a bind is needed
51         (for add/modify/delete operations).
52         Set to False otherwise.
53         
54         """
55         try:
56             self.ldapserv = ldap.open(self.ldapHost)
57         except ldap.LDAPError, error:
58             return {'bool' : False, 'message' : error }
59         
60         # Bind with authentification
61         if(bind): 
62             return self.bind()
63         
64         else:     
65             return {'bool': True} 
66     
67     def bind(self):
68         """ Binding method. """
69         try:
70             # Opens a connection after a call to ldap.open in connect:
71             self.ldapserv = ldap.initialize("ldap://" + self.ldapHost)
72                 
73             # Bind/authenticate with a user with apropriate 
74             #rights to add objects
75             self.ldapserv.simple_bind_s(self.ldapAdminDN, \
76                                     self.ldapAdminPassword)
77
78         except ldap.LDAPError, error:
79             return {'bool' : False, 'message' : error }
80
81         return {'bool': True}
82     
83     def close(self):
84         """ Close the LDAP connection """
85         try:
86             self.ldapserv.unbind_s()
87         except ldap.LDAPError, error:
88             return {'bool' : False, 'message' : error }
89             
90         
91 class LDAPapi :
92     def __init__(self):
93         logger.setLevelDebug() 
94         #SFA related config
95         self.senslabauth = Hierarchy()
96         config = Config()
97         
98         self.authname = config.SFA_REGISTRY_ROOT_AUTH
99
100         self.conn =  ldap_co() 
101         self.ldapUserQuotaNFS = self.conn.config.LDAP_USER_QUOTA_NFS 
102         self.ldapUserUidNumberMin = self.conn.config.LDAP_USER_UID_NUMBER_MIN 
103         self.ldapUserGidNumber = self.conn.config.LDAP_USER_GID_NUMBER 
104         self.ldapUserHomePath = self.conn.config.LDAP_USER_HOME_PATH 
105         
106         self.lengthPassword = 8
107         self.baseDN = self.conn.ldapPeopleDN
108         #authinfo=self.senslabauth.get_auth_info(self.authname)
109         
110         
111         self.charsPassword = [ '!','$','(',')','*','+',',','-','.', \
112                                 '0','1','2','3','4','5','6','7','8','9', \
113                                 'A','B','C','D','E','F','G','H','I','J', \
114                                 'K','L','M','N','O','P','Q','R','S','T', \
115                                 'U','V','W','X','Y','Z','_','a','b','c', \
116                                 'd','e','f','g','h','i','j','k','l','m', \
117                                 'n','o','p','q','r','s','t','u','v','w', \
118                                 'x','y','z','\'']
119         
120         self.ldapShell = '/bin/bash'
121
122     
123     def generate_login(self, record):
124         """Generate login for adding a new user in LDAP Directory 
125         (four characters minimum length)
126         Record contains first name and last name.
127         
128         """ 
129         #Remove all special characters from first_name/last name
130         lower_first_name = record['first_name'].replace('-','')\
131                                         .replace('_','').replace('[','')\
132                                         .replace(']','').replace(' ','')\
133                                         .lower()
134         lower_last_name = record['last_name'].replace('-','')\
135                                         .replace('_','').replace('[','')\
136                                         .replace(']','').replace(' ','')\
137                                         .lower()  
138         length_last_name = len(lower_last_name)
139         login_max_length = 8
140         
141         #Try generating a unique login based on first name and last name
142         getAttrs = ['uid']
143         if length_last_name >= login_max_length :
144             login = lower_last_name[0:login_max_length]
145             index = 0
146             logger.debug("login : %s index : %s" %(login, index))
147         elif length_last_name >= 4 :
148             login = lower_last_name
149             index = 0
150             logger.debug("login : %s index : %s" %(login, index))
151         elif length_last_name == 3 :
152             login = lower_first_name[0:1] + lower_last_name
153             index = 1
154             logger.debug("login : %s index : %s" %(login, index))
155         elif length_last_name == 2:
156             if len ( lower_first_name) >=2:
157                 login = lower_first_name[0:2] + lower_last_name
158                 index = 2
159                 logger.debug("login : %s index : %s" %(login, index))
160             else:
161                 logger.error("LoginException : \
162                             Generation login error with \
163                             minimum four characters")
164             
165                 
166         else :
167             logger.error("LDAP generate_login failed : \
168                             impossible to generate unique login for %s %s" \
169                             %(lower_first_name,lower_last_name))
170             
171         login_filter = '(uid=' + login + ')'
172         
173         try :
174             #Check if login already in use
175             while (len(self.LdapSearch(login_filter, getAttrs)) is not 0 ):
176             
177                 index += 1
178                 if index >= 9:
179                     logger.error("LoginException : Generation login error \
180                                     with minimum four characters")
181                 else:
182                     try:
183                         login = lower_first_name[0:index] + \
184                                     lower_last_name[0:login_max_length-index]
185                         login_filter = '(uid='+ login+ ')'
186                     except KeyError:
187                         print "lower_first_name - lower_last_name too short"
188                         
189             logger.debug("LDAP.API \t generate_login login %s" %(login))
190             return login
191                     
192         except  ldap.LDAPError, error :
193             logger.log_exc("LDAP generate_login Error %s" %error)
194             return None
195
196         
197
198     def generate_password(self):
199     
200         """Generate password for adding a new user in LDAP Directory 
201         (8 characters length) return password
202         
203         """
204         password = str()
205         length = len(self.charsPassword)
206         for index in range(self.lengthPassword):
207             char_index = random.randint(0, length-1)
208             password += self.charsPassword[char_index]
209
210         return password
211
212     def encrypt_password(self, password):
213         """ Use passlib library to make a RFC2307 LDAP encrypted password
214         salt size = 8, use sha-1 algorithm. Returns encrypted password.
215         
216         """
217         #Keep consistency with Java Senslab's LDAP API 
218         #RFC2307SSHAPasswordEncryptor so set the salt size to 8 bytres
219         return lssha.encrypt(password,salt_size = 8)
220     
221
222
223     def find_max_uidNumber(self):
224             
225         """Find the LDAP max uidNumber (POSIX uid attribute) .
226         Used when adding a new user in LDAP Directory 
227         returns string  max uidNumber + 1
228         
229         """
230         #First, get all the users in the LDAP
231         getAttrs = "(uidNumber=*)"
232         login_filter = ['uidNumber']
233
234         result_data = self.LdapSearch(getAttrs, login_filter) 
235         #It there is no user in LDAP yet, First LDAP user
236         if result_data == []:
237             max_uidnumber = self.ldapUserUidNumberMin
238         #Otherwise, get the highest uidNumber
239         else:
240             
241             uidNumberList = [int(r[1]['uidNumber'][0])for r in result_data ]
242             logger.debug("LDAPapi.py \tfind_max_uidNumber  \
243                                     uidNumberList %s " %(uidNumberList))
244             max_uidnumber = max(uidNumberList) + 1
245             
246         return str(max_uidnumber)
247          
248          
249     def get_ssh_pkey(self, record):
250         """TODO ; Get ssh public key from sfa record  
251         To be filled by N. Turro ? or using GID pl way?
252         
253         """
254         return 'A REMPLIR '
255
256     def make_ldap_filters_from_record(self, record=None):
257         """TODO Handle OR filtering in the ldap query when 
258         dealing with a list of records instead of doing a for loop in GetPersons   
259         Helper function to make LDAP filter requests out of SFA records.
260         """
261         req_ldap = ''
262         req_ldapdict = {}
263         if record :
264             if 'first_name' in record  and 'last_name' in record:
265                 req_ldapdict['cn'] = str(record['first_name'])+" "\
266                                         + str(record['last_name'])
267             if 'email' in record :
268                 req_ldapdict['mail'] = record['email']
269             if 'mail' in record:
270                 req_ldapdict['mail'] = record['mail']
271             if 'enabled' in record:
272                 if record['enabled'] == True :
273                     req_ldapdict['shadowExpire'] = '-1'
274                 else:
275                     req_ldapdict['shadowExpire'] = '0'
276                 
277             #Hrn should not be part of the filter because the hrn 
278             #presented by a certificate of a SFA user not imported in 
279             #Senslab  does not include the senslab login in it 
280             #Plus, the SFA user may already have an account with senslab
281             #using another login.
282                 
283             #if 'hrn' in record :
284                 #splited_hrn = record['hrn'].split(".")
285                 #if splited_hrn[0] != self.authname :
286                     #logger.warning(" \r\n LDAP.PY \
287                         #make_ldap_filters_from_record I know nothing \
288                         #about %s my authname is %s not %s" \
289                         #%(record['hrn'], self.authname, splited_hrn[0]) )
290                         
291                 #login=splited_hrn[1]
292                 #req_ldapdict['uid'] = login
293             
294
295             logger.debug("\r\n \t LDAP.PY make_ldap_filters_from_record \
296                                 record %s req_ldapdict %s" \
297                                 %(record, req_ldapdict))
298             
299             for k in req_ldapdict:
300                 req_ldap += '('+ str(k)+ '=' + str(req_ldapdict[k]) + ')'
301             if  len(req_ldapdict.keys()) >1 :
302                 req_ldap = req_ldap[:0]+"(&"+req_ldap[0:]
303                 size = len(req_ldap)
304                 req_ldap = req_ldap[:(size-1)] +')'+ req_ldap[(size-1):]
305         else:
306             req_ldap = "(cn=*)"
307         
308         return req_ldap
309         
310     def make_ldap_attributes_from_record(self, record):
311         """When addind a new user to Senslab's LDAP, creates an attributes 
312         dictionnary from the SFA record.
313         
314         """
315
316         attrs = {}
317         attrs['objectClass'] = ["top", "person", "inetOrgPerson", \
318                                     "organizationalPerson", "posixAccount", \
319                                     "shadowAccount", "systemQuotas", \
320                                     "ldapPublicKey"]
321         
322         attrs['givenName'] = str(record['first_name']).lower().capitalize()
323         attrs['sn'] = str(record['last_name']).lower().capitalize()
324         attrs['cn'] = attrs['givenName'] + ' ' + attrs['sn']
325         attrs['gecos'] = attrs['givenName'] + ' ' + attrs['sn']
326         attrs['uid'] = self.generate_login(record)   
327                     
328         attrs['quota'] = self.ldapUserQuotaNFS 
329         attrs['homeDirectory'] = self.ldapUserHomePath + attrs['uid']
330         attrs['loginShell'] = self.ldapShell
331         attrs['gidNumber'] = self.ldapUserGidNumber
332         attrs['uidNumber'] = self.find_max_uidNumber()
333         attrs['mail'] = record['mail'].lower()
334         try:
335             attrs['sshPublicKey'] = record['pkey']
336         except KeyError:
337             attrs['sshPublicKey'] = self.get_ssh_pkey(record) 
338         
339
340         #Password is automatically generated because SFA user don't go 
341         #through the Senslab website  used to register new users, 
342         #There is no place in SFA where users can enter such information
343         #yet.
344         #If the user wants to set his own password , he must go to the Senslab 
345         #website.
346         password = self.generate_password()
347         attrs['userPassword']= self.encrypt_password(password)
348         
349         #Account automatically validated (no mail request to admins)
350         #Set to 0 to disable the account, -1 to enable it,
351         attrs['shadowExpire'] = '-1'
352
353         #Motivation field in Senslab
354         attrs['description'] = 'SFA USER FROM OUTSIDE SENSLAB'
355
356         attrs['ou'] = 'SFA'         #Optional: organizational unit
357         #No info about those here:
358         attrs['l'] = 'To be defined'#Optional: Locality. 
359         attrs['st'] = 'To be defined' #Optional: state or province (country).
360
361         return attrs
362
363
364
365     def LdapAddUser(self, record) :
366         """Add SFA user to LDAP if it is not in LDAP  yet. """
367         
368         user_ldap_attrs = self.make_ldap_attributes_from_record(record)
369
370         
371         #Check if user already in LDAP wih email, first name and last name
372         filter_by = self.make_ldap_filters_from_record(user_ldap_attrs)
373         user_exist = self.LdapSearch(filter_by)
374         if user_exist:
375             logger.warning(" \r\n \t LDAP LdapAddUser user %s %s \
376                         already exists" %(user_ldap_attrs['sn'], \
377                         user_ldap_attrs['mail'])) 
378             return {'bool': False}
379         
380         #Bind to the server
381         result = self.conn.connect()
382         
383         if(result['bool']):
384             
385             # A dict to help build the "body" of the object
386             
387             logger.debug(" \r\n \t LDAP LdapAddUser attrs %s " %user_ldap_attrs)
388
389             # The dn of our new entry/object
390             dn = 'uid=' + user_ldap_attrs['uid'] + "," + self.baseDN 
391
392             try:
393                 ldif = modlist.addModlist(user_ldap_attrs)
394                 logger.debug("LDAPapi.py add attrs %s \r\n  ldif %s"\
395                                 %(user_ldap_attrs,ldif) )
396                 self.conn.ldapserv.add_s(dn,ldif)
397                 
398                 logger.info("Adding user %s login %s in LDAP" \
399                         %(user_ldap_attrs['cn'] ,user_ldap_attrs['uid']))
400                         
401                         
402             except ldap.LDAPError, error:
403                 logger.log_exc("LDAP Add Error %s" %error)
404                 return {'bool' : False, 'message' : error }
405         
406             self.conn.close()
407             return {'bool': True}  
408         else: 
409             return result
410
411         
412     def LdapDelete(self, person_dn):
413         """
414         Deletes a person in LDAP. Uses the dn of the user.
415         """
416         #Connect and bind   
417         result =  self.conn.connect()
418         if(result['bool']):
419             try:
420                 self.conn.ldapserv.delete_s(person_dn)
421                 self.conn.close()
422                 return {'bool': True}
423             
424             except ldap.LDAPError, error:
425                 logger.log_exc("LDAP Delete Error %s" %error)
426                 return {'bool': False}
427         
428     
429     def LdapDeleteUser(self, record_filter): 
430         """
431         Deletes a SFA person in LDAP, based on the user's hrn.
432         """
433         #Find uid of the  person 
434         person = self.LdapFindUser(record_filter,[])
435         logger.debug("LDAPapi.py \t LdapDeleteUser record %s person %s" \
436         %(record_filter, person))
437
438         if person:
439             dn = 'uid=' + person['uid'] + "," +self.baseDN 
440         else:
441             return {'bool': False}
442         
443         result = self.LdapDelete(dn)
444         return result
445         
446
447     def LdapModify(self, dn, old_attributes_dict, new_attributes_dict): 
448         """ Modifies a LDAP entry """
449          
450         ldif = modlist.modifyModlist(old_attributes_dict,new_attributes_dict)
451         # Connect and bind/authenticate    
452         result = self.conn.connect() 
453         if (result['bool']): 
454             try:
455                 self.conn.ldapserv.modify_s(dn,ldif)
456                 self.conn.close()
457                 return {'bool' : True }
458             except ldap.LDAPError, error:
459                 logger.log_exc("LDAP LdapModify Error %s" %error)
460                 return {'bool' : False }
461     
462         
463     def LdapModifyUser(self, user_record, new_attributes_dict):
464         """
465         Gets the record from one user_uid_login based on record_filter 
466         and changes the attributes according to the specified new_attributes.
467         Does not use this if we need to modify the uid. Use a ModRDN 
468         #operation instead ( modify relative DN )
469         """
470         if user_record is None:
471             logger.error("LDAP \t LdapModifyUser Need user record  ")
472             return {'bool': False} 
473         
474         #Get all the attributes of the user_uid_login 
475         #person = self.LdapFindUser(record_filter,[])
476         req_ldap = self.make_ldap_filters_from_record(user_record)
477         person_list = self.LdapSearch(req_ldap,[])
478         logger.debug("LDAPapi.py \t LdapModifyUser person_list : %s" \
479                                                         %(person_list))
480         if person_list and len(person_list) > 1 :
481             logger.error("LDAP \t LdapModifyUser Too many users returned")
482             return {'bool': False}
483         if person_list is None :
484             logger.error("LDAP \t LdapModifyUser  User %s doesn't exist "\
485                         %(user_record))
486             return {'bool': False} 
487         
488         # The dn of our existing entry/object
489         #One result only from ldapSearch
490         person = person_list[0][1]
491         dn  = 'uid=' + person['uid'][0] + "," +self.baseDN  
492        
493         if new_attributes_dict:
494             old = {}
495             for k in new_attributes_dict:
496                 if k not in person:
497                     old[k] =  ''
498                 else :
499                     old[k] = person[k]
500             logger.debug(" LDAPapi.py \t LdapModifyUser  new_attributes %s"\
501                                 %( new_attributes_dict))  
502             result = self.LdapModify(dn, old,new_attributes_dict)
503             return result
504         else:
505             logger.error("LDAP \t LdapModifyUser  No new attributes given. ")
506             return {'bool': False} 
507             
508             
509             
510             
511     def LdapMarkUserAsDeleted(self, record): 
512
513         
514         new_attrs = {}
515         #Disable account
516         new_attrs['shadowExpire'] = '0'
517         logger.debug(" LDAPapi.py \t LdapMarkUserAsDeleted ")
518         ret = self.LdapModifyUser(record, new_attrs)
519         return ret
520
521             
522     def LdapResetPassword(self,record):
523         """
524         Resets password for the user whose record is the parameter and changes
525         the corresponding entry in the LDAP.
526         
527         """
528         password = self.generate_password()
529         attrs = {}
530         attrs['userPassword'] = self.encrypt_password(password)
531         logger.debug("LDAP LdapResetPassword encrypt_password %s"\
532                     %(attrs['userPassword']))
533         result = self.LdapModifyUser(record, attrs)
534         return result
535         
536         
537     def LdapSearch (self, req_ldap = None, expected_fields = None ):
538         """
539         Used to search directly in LDAP, by using ldap filters and
540         return fields. 
541         When req_ldap is None, returns all the entries in the LDAP.
542       
543         """
544         result = self.conn.connect(bind = False)
545         if (result['bool']) :
546             
547             return_fields_list = []
548             if expected_fields == None : 
549                 return_fields_list = ['mail','givenName', 'sn', 'uid', \
550                                         'sshPublicKey', 'shadowExpire']
551             else : 
552                 return_fields_list = expected_fields
553             #No specifc request specified, get the whole LDAP    
554             if req_ldap == None:
555                 req_ldap = '(cn=*)'
556                
557             logger.debug("LDAP.PY \t LdapSearch  req_ldap %s \
558                                     return_fields_list %s" \
559                                     %(req_ldap, return_fields_list))
560
561             try:
562                 msg_id = self.conn.ldapserv.search(
563                                             self.baseDN,ldap.SCOPE_SUBTREE,\
564                                             req_ldap, return_fields_list)     
565                 #Get all the results matching the search from ldap in one 
566                 #shot (1 value)
567                 result_type, result_data = \
568                                         self.conn.ldapserv.result(msg_id,1)
569
570                 self.conn.close()
571
572                 logger.debug("LDAP.PY \t LdapSearch  result_data %s"\
573                             %(result_data))
574
575                 return result_data
576             
577             except  ldap.LDAPError,error :
578                 logger.log_exc("LDAP LdapSearch Error %s" %error)
579                 return []
580             
581             else:
582                 logger.error("LDAP.PY \t Connection Failed" )
583                 return 
584         
585     def LdapFindUser(self, record = None, is_user_enabled=None, \
586             expected_fields = None):
587         """
588         Search a SFA user with a hrn. User should be already registered 
589         in Senslab LDAP. 
590         Returns one matching entry 
591         """   
592         custom_record = {}
593         if is_user_enabled: 
594           
595             custom_record['enabled'] = is_user_enabled
596         if record:  
597             custom_record.update(record)
598
599
600         req_ldap = self.make_ldap_filters_from_record(custom_record)     
601         return_fields_list = []
602         if expected_fields == None : 
603             return_fields_list = ['mail','givenName', 'sn', 'uid', \
604                                     'sshPublicKey']
605         else : 
606             return_fields_list = expected_fields
607             
608         result_data = self.LdapSearch(req_ldap, return_fields_list )
609         logger.debug("LDAP.PY \t LdapFindUser  result_data %s" %(result_data))
610            
611         if len(result_data) is 0:
612             return None
613         #Asked for a specific user
614         if record :
615             #try:
616             ldapentry = result_data[0][1]
617             logger.debug("LDAP.PY \t LdapFindUser ldapentry %s" %(ldapentry))
618             tmpname = ldapentry['uid'][0]
619
620             tmpemail = ldapentry['mail'][0]
621             if ldapentry['mail'][0] == "unknown":
622                 tmpemail = None
623                     
624             #except IndexError: 
625                 #logger.error("LDAP ldapFindHRn : no entry for record %s found"\
626                             #%(record))
627                 #return None
628                 
629             try:
630                 hrn = record['hrn']
631                 parent_hrn = get_authority(hrn)
632                 peer_authority = None
633                 if parent_hrn is not self.authname:
634                     peer_authority = parent_hrn
635
636                 results =  {    
637                             'type': 'user',
638                             'pkey': ldapentry['sshPublicKey'][0],
639                             #'uid': ldapentry[1]['uid'][0],
640                             'uid': tmpname ,
641                             'email':tmpemail,
642                             #'email': ldapentry[1]['mail'][0],
643                             'first_name': ldapentry['givenName'][0],
644                             'last_name': ldapentry['sn'][0],
645                             #'phone': 'none',
646                             'serial': 'none',
647                             'authority': parent_hrn,
648                             'peer_authority': peer_authority,
649                             'pointer' : -1,
650                             'hrn': hrn,
651                             }
652             except KeyError,error:
653                 logger.log_exc("LDAPapi \t LdaFindUser KEyError %s" \
654                                 %error )
655                 return
656         else:
657         #Asked for all users in ldap
658             results = []
659             for ldapentry in result_data:
660                 logger.debug(" LDAP.py LdapFindUser ldapentry name : %s " \
661                                 %(ldapentry[1]['uid'][0]))
662                 tmpname = ldapentry[1]['uid'][0]
663                 hrn=self.authname+"."+ tmpname
664                 
665                 tmpemail = ldapentry[1]['mail'][0]
666                 if ldapentry[1]['mail'][0] == "unknown":
667                     tmpemail = None
668
669         
670                 parent_hrn = get_authority(hrn)
671                 parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
672                 try:
673                     results.append(  {  
674                             'type': 'user',
675                             'pkey': ldapentry[1]['sshPublicKey'][0],
676                             #'uid': ldapentry[1]['uid'][0],
677                             'uid': tmpname ,
678                             'email':tmpemail,
679                             #'email': ldapentry[1]['mail'][0],
680                             'first_name': ldapentry[1]['givenName'][0],
681                             'last_name': ldapentry[1]['sn'][0],
682                             #'phone': 'none',
683                             'serial': 'none',
684                             'authority': self.authname,
685                             'peer_authority': '',
686                             'pointer' : -1,
687                             'hrn': hrn,
688                             } ) 
689                 except KeyError,error:
690                     logger.log_exc("LDAPapi.PY \t LdapFindUser EXCEPTION %s" \
691                                                 %(error))
692                     return
693         return results   
694