source: libabac/abac_pl_yap.c @ bf68132

mei_rt2mei_rt2_fix_1
Last change on this file since bf68132 was bf68132, checked in by Mei <mei@…>, 12 years ago

1) get example directory to work with yap with use_malloc option
2) swap in new performance graphs

  • Property mode set to 100644
File size: 12.4 KB
Line 
1
2/* copied from abac_graph.c
3   implementation of the low level using
4   yap prolog
5*/
6
7#include <err.h>
8#include <stdio.h>
9#include <assert.h>
10#include <stdlib.h>
11#include <string.h>
12#include <Yap/YapInterface.h>
13
14#include "abac_internal.h"
15
16#include "abac_pl_yap.h"
17#include "abac_util.h"
18
19#include "uthash.h"
20
21extern abac_list_t *abac_credential_clauses(abac_credential_t *);
22extern char *abac_id_clause(abac_id_credential_t *);
23extern abac_aspect_t *abac_yy_get_rule_tail_aspect();
24extern abac_aspect_t *abac_yy_get_rule_head_aspect();
25
26/* XXXX */
27extern YAP_Term  YAP_WriteBuffer(YAP_Term, char *, unsigned int, int);
28
29static int debug=0;
30
31/* track constraint's external clause's -unique name id */
32
33static int constraint_label_count=0;
34static char *constraint_label="isABAC_constraint";
35
36// pl -- place holder for now
37struct _abac_pl_t {
38    FILE *fptr;
39    char *fname;
40    char *yap_certs;
41};
42
43/***********************************************************/
44static int _get_next_constraint_label_idx()
45{
46    constraint_label_count++;
47    return constraint_label_count;
48}
49
50static int _get_constraint_label_idx()
51{
52    return constraint_label_count;
53}
54
55/***********************************************************/
56
57static int _insert_clause(char *str)
58{
59    YAP_Term *eterm;
60    YAP_Term goalArgs=YAP_ReadBuffer(str, eterm);
61    char *tmp=YAP_CompileClause(goalArgs);
62    if (tmp!=NULL) { /* something is wrong */
63        printf("error: result of compile clause (%s)\n", tmp);
64        printf("error: str used (%s)\n", str);
65        return 1;
66    }
67    return 0;
68}
69
70static int _insert_cred_clause(char *cstr)
71{
72    int ret=ABAC_CERT_SUCCESS;
73    int rc=_insert_clause(cstr);
74    if (rc)
75        return ABAC_CERT_BAD_YAP;
76    return ABAC_CERT_SUCCESS;
77}
78
79void show_yap_db(const char *msg)
80{
81    char lstr[]="listing";
82    YAP_Term *eterm; /* error term */
83
84    printf("\n\n========= yap db (%s)\n",msg);
85    YAP_Term goal=YAP_ReadBuffer(lstr, eterm);
86    int rc =YAP_RunGoal( goal );
87    if (rc) {
88        printf("listing ok.. \n");
89    } else {
90        printf("listing's rc is bad.. \n");
91        YAP_Exit(1);
92    }
93    printf("========= \n\n");
94}
95
96/**
97 * Include some utility routines
98 */
99abac_pl_t *abac_pl_utility(void) {
100/*
101append([],L,L).
102append([X|L1],L2,[X|L3]):-append(L1,L2,L3).
103
104appendL([],[]).
105appendL([H|T], L) :-
106   appendL(T,L2), append(H,L2,L).
107*/
108    if(_insert_clause("append([],L,L)"))
109        YAP_Exit(1);
110    if(_insert_clause("append([X|L1],L2,[X|L3]):-append(L1,L2,L3)"))
111        YAP_Exit(1);
112    if(_insert_clause("appendL([],[])"))
113        YAP_Exit(1);
114    if(_insert_clause("appendL([H|T], L) :- appendL(T,L2), append(H,L2,L)"))
115        YAP_Exit(1);
116}
117
118/**
119 * Create a new yap structure.
120 */
121abac_pl_t *abac_pl_new(void) {
122
123    if (YAP_FastInit(NULL) == YAP_BOOT_ERROR)
124        YAP_Exit(1);
125
126    if (YAP_RunGoal(YAP_MkAtomTerm(YAP_LookupAtom("source")))) {
127        if(debug) fprintf(stderr, "calling source..\n");
128        } else {
129            if(debug) fprintf(stderr,"calling source failed..\n");
130            YAP_Exit(1);
131    }
132
133    abac_pl_utility();
134 
135    abac_pl_t *pl = abac_xmalloc(sizeof(abac_pl_t));
136    pl->fptr=NULL;
137    pl->fname=NULL;
138    pl->yap_certs=NULL;
139    return pl;
140}
141
142/**
143 * Add a credential to the db, not duplicating a copy and so
144 * don't try to free it after this call.
145 */
146int abac_pl_add_credential(abac_pl_t *pl, abac_credential_t *cred)
147{
148    int rc=0;
149    abac_list_t *clauses=abac_credential_clauses(cred);
150    if (clauses != NULL) {
151        char *cur;
152        abac_list_foreach(clauses, cur,
153            if(cur) {
154                if(debug) fprintf(stderr,"inserting =>%s\n",cur);
155                rc=_insert_cred_clause(cur);
156            }
157        );
158    }
159    return rc;
160}
161
162int abac_pl_add_type_credential(abac_pl_t *pl, abac_id_credential_t *id_cert)
163{
164    char *clause=abac_id_clause(id_cert);
165    if (clause != NULL) {
166        int rc=_insert_cred_clause(clause);
167        return rc;
168    }
169    return 0;
170}
171
172/*  string1(S):- S="abc";S="efg";S="ijk" */
173char *abac_pl_add_range_constraint_clause(char *var, char *tmplist)
174{
175    int i=_get_next_constraint_label_idx();
176    char *tmp=NULL;
177    asprintf(&tmp,"%s_%d(%s) :- %s", constraint_label, i, var, tmplist); 
178    int rc=_insert_cred_clause(tmp);
179    free(tmp);
180    if(rc) 
181        panic("abac_pl_add_range_constraint_clause, failed to insert");
182    asprintf(&tmp,"%s_%d(%s)", constraint_label, i, var);
183    return tmp;
184}
185
186/* cases,
187     ['str']
188     ['str1','str2']
189     ([] is not possible, and don't care)
190*/
191static void _credentials_from_string(abac_stack_t *credentials,char *slist) {
192    char *cptr=slist; /* current ptr */
193    char *sptr; /* string ptr */
194    char *ptr;
195    int len=0;
196    char *string;
197    abac_credential_t *cred=NULL;
198    int cnt=0;
199
200    /* find first [' */ 
201    ptr=strstr(cptr,"['");
202    if(ptr == NULL) 
203         return;
204    cptr=ptr+2;
205    sptr=cptr;
206    while (1) {
207        /* find next ',' or '] */
208        ptr=strstr(cptr,"','");
209        if(ptr!=NULL) {
210             cptr=ptr+3;
211             len=(ptr-sptr);
212             string=strndup(sptr,len);
213             cred=abac_credential_lookup(string);
214             free(string); 
215             if(cred) {
216                 int i=abac_stack_unique_push(credentials, cred);
217                 if(i) cnt++;
218                 } else {
219                 printf("BAD BAD\n");
220             }
221             sptr=cptr;
222             } else {
223             ptr=strstr(cptr,"']");
224             if(ptr!=NULL) {
225                 len=(ptr-sptr);
226                 string=strndup(sptr,len);
227                 cred=abac_credential_lookup(string);
228                 free(string);
229                 if(cred) {
230                     int i=abac_stack_unique_push(credentials, cred);
231                     if(i) cnt++;
232                     } else {
233                     printf("BAD BAD BAD\n");
234                 }
235                 break;
236             }
237        }
238    }
239    if(debug)
240        fprintf(stderr,"DEBUG:total %d credentials\n", cnt);
241}
242
243/* MAX 1024x1024, double as it goes */
244static int try_again(int sz, char **tptr)
245{
246   int blk=1024*2; /* 2048 */
247   int max=1024*1024;
248   int size;
249   char *tmp = NULL;
250
251   if(sz==0) {
252       size = (sizeof(char) * (blk+1));
253       } else {
254           if (sz>=max) {
255               size=0;
256               *tptr=tmp;
257               return 0;
258           }
259           size=sz*2+1;
260           if(size > max) size=max;
261   }
262
263   tmp = (char *) YAP_AllocSpaceFromYap(size);
264   if(tmp==NULL) {
265       fprintf(stderr,"ERROR: malloc failed !!!\n");
266       YAP_Exit(1);
267   }
268   *tptr=tmp;
269   return size;
270}
271
272/* make a query and extract just 1 set of result */
273static abac_stack_t *_make_yap_query(char *prin, char *rule, char* estring)
274{
275    YAP_Term *eterm0;
276    YAP_Term *eterm1;
277    YAP_Term arg[3];
278
279    abac_stack_t *cred_list = abac_stack_new();
280
281    if(debug) fprintf(stderr," the principal part(%s)\n", prin);
282    if(prin[0]=='\'' || prin[0]=='"') {
283        arg[0]=YAP_ReadBuffer(prin,eterm0);
284        } else {
285            arg[0]=YAP_MkAtomTerm(YAP_LookupAtom(prin)); 
286    }
287    if(debug) fprintf(stderr," the role/oset part(%s)\n", estring);
288    arg[1]=YAP_ReadBuffer(estring,eterm1);
289
290    /* var for credential list */
291    arg[2]=YAP_MkVarTerm();
292
293    YAP_Atom f = YAP_LookupAtom("isMember");
294    YAP_Functor func = YAP_MkFunctor(f, 3);
295    YAP_Term goal=YAP_MkApplTerm(func, 3, arg);
296
297    int rc =YAP_RunGoal( goal );
298    if (rc) {
299        printf("YAP query succeed\n");
300        char *tmp=NULL;
301        int tmp_sz=try_again(0, &tmp);
302        while(1) {
303            YAP_WriteBuffer(arg[2], tmp, tmp_sz,YAP_WRITE_HANDLE_VARS);
304            if(strlen(tmp)>15) break;
305            tmp_sz=try_again(tmp_sz,&tmp);
306            if(tmp_sz==0) {
307                fprintf(stderr," PANIC, run out of heap space..\n");
308                YAP_Exit(1);
309            }
310/*XXXXX
311            YAP_Term wrc=YAP_WriteBuffer(arg[2], tmp, tmp_sz,YAP_WRITE_HANDLE_VARS);
312            if(debug) {
313                if(wrc != arg[2])
314                    fprintf(stderr," PANIC should be the same ...\n");
315                /* if returned is FALSE, then it is error !!! */
316                if( wrc )
317                    fprintf(stderr," PANIC PANIC\n");
318            }
319            if(wrc == arg[2])
320                break;
321            if(debug)
322                fprintf(stderr," PANIC, try again \n");
323            tmp_sz=try_again(tmp_sz,&tmp);
324            if(tmp_sz==0) {
325                fprintf(stderr," PANIC, run out of heap space..\n");
326                YAP_Exit(1);
327****/
328            }
329        }
330        /* this is returned as ['string1','string2'] */
331        if(debug) fprintf(stderr,"    query answer : %s(%d)\n", tmp, strlen(tmp));
332        _credentials_from_string(cred_list,tmp); 
333        if(abac_stack_size(cred_list)==0) {
334            fprintf(stderr,"CAN NOT retrieve result properly from YAP!!!\n");
335            YAP_Exit(1);
336        }
337        YAP_FreeSpaceFromYap(tmp);
338/**** XXX
339        while (YAP_RestartGoal()) {
340            if(debug) fprintf(stderr,"another success\n");
341            YAP_WriteBuffer(arg[2], tmp, 5000,YAP_WRITE_HANDLE_VARS);
342        if(debug) fprintf(stderr,"    restart query answer : %s\n", tmp);
343            _credentials_from_string(cred_list,tmp);
344        }
345***/
346    } else {
347        printf("YAP query failed\n");
348        /* YAP_Exit(1); */
349    }
350/*** MEI ***/
351    YAP_Reset();
352    return cred_list;
353}
354
355/* 2 types
356      acme.buys_rocket <- coyote (coyote=prin, acme.buys_rocket=role)
357        ==> isMember(coyote,role(acme,buys_rocket), L)
358      acme.buys_rocket <- acme.preferred_customer  -- NOT valid
359*/
360static abac_stack_t *_query_with_aspect(abac_pl_t *pl, abac_aspect_t* head, abac_aspect_t* tail)
361{
362    abac_stack_t *ret=NULL;
363    char *tmp=NULL;
364
365    if(0)
366        show_yap_db("DEBUG:calling within _query_with_aspect");
367
368    char *nm;
369    PROLOG(nm=abac_aspect_principal_name(head););
370
371    /* could be obj or principal */
372    char *prin_nm=NULL;
373    if(abac_aspect_is_object(tail)) {
374        prin_nm=abac_aspect_object_name(tail);
375        } else {
376            PROLOG(prin_nm=abac_aspect_principal_name(tail););
377    }
378
379    if(abac_aspect_aspect_name(tail)!=NULL) {
380        printf("fail, a.o <- b.o and a.r <- a.r query is not implemented yet !!!\n");
381        YAP_Exit(1);
382    }
383
384    if (prin_nm == NULL || nm == NULL) {
385        printf("fail, query's call got bad aspect names .. \n");
386        YAP_Exit(1);
387    }
388
389    if(debug) fprintf(stderr,"printing up the yap query ..\n");
390
391    char *pstring;
392    PROLOG(pstring=abac_aspect_aspect_param_string(head););
393
394    char *stub=abac_aspect_type_string(head);
395    if(pstring) {
396        asprintf(&tmp,"%s(%s,%s,%s)", stub, nm, abac_aspect_aspect_name(head),pstring);
397        free(pstring);
398        } else {
399            asprintf(&tmp,"%s(%s,%s)", stub, nm, abac_aspect_aspect_name(head));
400    }
401
402    ret=_make_yap_query(prin_nm,nm,tmp);
403    return ret;
404}
405
406/**
407 * Get all the credentials (attribute/issuer cert pairs) from prolog
408 * (which returns in string form)
409 */
410abac_stack_t *abac_pl_credentials(abac_pl_t *pl)
411{
412    abac_stack_t *ret=abac_verifier_dump_creds();
413    return ret;
414}
415
416abac_stack_t *abac_pl_principals(abac_pl_t *pl)
417{
418    abac_stack_t *ret=abac_verifier_dump_principals();
419    return ret;
420}
421
422/**
423 * Make a query into prolog db
424--role acme.preferred_customer --principal coyote
425--role acme.prefer_customer.buy_rockets --principlal coyote
426--oset acme.rockets -- object mrx-21
427--oset acme.villans -- principal coyote
428 */
429abac_stack_t *abac_pl_query(abac_pl_t *pl, char *roleoset, char *prinobj)
430{
431    abac_stack_t *ret=NULL;
432    int len=strlen(roleoset)+strlen(prinobj)+5;
433    char* attr_string=(char *) abac_xmalloc(sizeof(char)*len);
434    sprintf(attr_string,"%s<-%s", roleoset, prinobj);
435
436    if(debug)
437        fprintf(stderr,"abac_pl_query, query string is (%s)\n",attr_string);
438
439    /* call into yacc parser */
440    abac_reset_yyfptr(attr_string);
441    abac_yy_init();
442    int rc=yyparse();
443    if (rc) {
444        free(attr_string);
445        return NULL;
446    }
447
448    abac_aspect_t *head_aspect = abac_yy_get_rule_head_aspect();
449    abac_aspect_t *tail_aspect = abac_yy_get_rule_tail_aspect();
450
451    ret=_query_with_aspect(pl,head_aspect,tail_aspect);
452
453    return ret;
454}
455
456abac_stack_t *abac_pl_query_with_structure(abac_pl_t *pl, abac_aspect_t *head_aspect, abac_aspect_t *tail_aspect)
457{
458    abac_stack_t *ret=NULL;
459    ret=_query_with_aspect(pl,head_aspect,tail_aspect);
460
461    return ret;
462}
463
464void abac_pl_free(abac_pl_t *pl) {
465    if(pl->fptr) {
466        fflush(pl->fptr);
467        free(pl->fptr);
468    }
469    if(pl->fname) {
470        unlink(pl->fname);
471        free(pl->fname);
472    }
473    free(pl);
474}
475
Note: See TracBrowser for help on using the repository browser.