6 * Copyright (C) 1987, 1988 by the Massachusetts Institute of Technology
7 * For copying and distribution information, please see the file
13 static char *rcsid_qrtn_dc = "$Header$";
16 #include <mit-copyright.h>
19 #include "mr_server.h"
20 EXEC SQL INCLUDE sqlca; /* SQL Communications Area */
21 EXEC SQL INCLUDE sqlda; /* SQL Descriptor Area */
25 EXEC SQL BEGIN DECLARE SECTION;
28 char cdummy[MR_CDUMMY_LEN];
29 char stmt_buf[MR_STMTBUF_LEN];
30 EXEC SQL END DECLARE SECTION;
36 EXEC SQL BEGIN DECLARE SECTION;
37 int query_timeout = 30;
38 char *database = "moira";
39 EXEC SQL END DECLARE SECTION;
43 #define INGRES_BAD_DATE1 40206
44 #define INGRES_BAD_DATE2 40207
45 #define INGRES_DEADLOCK 49900
46 #define INGRES_TIMEOUT 39100
47 #define INGRES_BAD_COLUMN 30110
48 #define INGRES_ASGN_ERR 40204
49 #define INGRES_NO_CURSOR 30120
50 #define INGRES_NO_STMT 30130
53 * ingerr: Called when Ingres indicates an error.
58 EXEC SQL BEGIN DECLARE SECTION;
60 EXEC SQL END DECLARE SECTION;
61 ingres_errno = -sqlca.sqlcode;
63 switch (ingres_errno) {
64 case INGRES_BAD_DATE1:
65 case INGRES_BAD_DATE2:
69 mr_errcode = MR_DEADLOCK;
70 com_err(whoami, 0, "INGRES deadlock detected");
73 /* May be something other than timeout! #39100 is "Unknown error"
74 * Really should parse the error message enough to decide if it's a timeout */
76 com_err(whoami, 0, "timed out getting lock");
78 /* These should never come up unless someone breaks the query table */
79 case INGRES_NO_CURSOR:
80 if (mr_errcode != MR_BUSY &&
81 mr_errcode != MR_DEADLOCK)
82 mr_errcode = MR_INTERNAL;
83 com_err(whoami, 0, "Cursor not opened");
86 mr_errcode = MR_INTERNAL;
87 com_err(whoami, 0, "Statement not declared");
89 case INGRES_BAD_COLUMN:
90 mr_errcode = MR_INTERNAL;
91 com_err(whoami, 0, "Bad column name in query table");
94 mr_errcode = MR_INTERNAL;
95 com_err(whoami, 0, "Error in SQL assignment statement");
99 mr_errcode = MR_INGRES_ERR;
100 com_err(whoami, MR_INGRES_ERR, " code %d\n", ingres_errno);
101 EXEC SQL INQUIRE_SQL(:err_msg = errortext);
102 com_err(whoami, 0, "SQL error text = %s", err_msg);
103 critical_alert("MOIRA", "Moira server encountered INGRES ERROR %d", ingres_errno);
107 /* This is declarative, not executed. Applies from here on, in this file. */
108 EXEC SQL WHENEVER SQLERROR CALL ingerr;
110 int mr_open_database()
114 MR_SQLDA_T *mr_alloc_SQLDA();
115 static first_open = 1;
120 /* initialize local argv */
121 for (i = 0; i < 16; i++)
122 Argv[i] = malloc(ARGLEN);
124 SQLDA = mr_alloc_SQLDA();
133 /* open the database */
135 EXEC SQL CONNECT :database;
137 return (ingres_errno);
138 EXEC SQL set lockmode session where level = table, timeout = :query_timeout;
139 EXEC SQL set lockmode on capacls where readlock = shared;
140 EXEC SQL set lockmode on alias where readlock = shared;
143 EXEC SQL DATABASE moira
149 EXEC SQL SELECT SIZE(signature) INTO :mr_sig_length FROM users WHERE users_id=0; /* Harmless on second open */
150 EXEC SQL COMMIT WORK;
157 int mr_close_database()
165 mr_check_access(cl, name, argc, argv_ro)
172 struct query *get_query_by_name();
177 q = get_query_by_name(name, cl->args->mr_version_no);
178 if (q == (struct query *)0)
179 return(MR_NO_HANDLE);
181 return(mr_verify_query(cl, q, argc, argv_ro));
184 mr_process_query(cl, name, argc, argv_ro, action, actarg)
192 register struct query *q;
194 register struct validate *v;
199 EXEC SQL BEGIN DECLARE SECTION;
201 EXEC SQL END DECLARE SECTION;
202 struct save_queue *sq;
203 struct query *get_query_by_name();
205 struct save_queue *sq_create();
211 /* list queries command */
212 if (!strcmp(name, "_list_queries")) {
213 list_queries(cl->args->mr_version_no, action, actarg);
217 /* help query command */
218 if (!strcmp(name, "_help")) {
221 q = get_query_by_name(argv_ro[0], cl->args->mr_version_no);
222 if (q == (struct query *)0) return(MR_NO_HANDLE);
223 help_query(q, action, actarg);
227 /* get query structure, return error if named query does not exist */
228 q = get_query_by_name(name, cl->args->mr_version_no);
229 if (q == (struct query *)0) return(MR_NO_HANDLE);
232 /* setup argument vector, verify access and arguments */
233 if ((status = mr_verify_query(cl, q, argc, argv_ro)) != MR_SUCCESS)
236 /* perform any special query pre-processing */
237 if (v && v->pre_rtn) {
238 status = (*v->pre_rtn)(q, Argv, cl, 0);
239 if (status != MR_SUCCESS)
245 /* for queries that do not permit wildcarding, check if row
248 status = validate_row(q, Argv, v);
249 if (status != MR_EXISTS) break;
252 /* build "where" clause if needed */
254 build_qual(q->qual, q->argc, Argv, qual);
260 /* build "sort" clause if needed */
261 if (v && v->valobj) {
262 psort = build_sort(v, sort);
267 /* if there is a followup routine, then we must save the results */
268 /* of the first query for use by the followup routine */
269 /* if q->rvar = NULL, perform post_rtn only */
271 if (v && v->post_rtn) {
273 status = do_retrieve(q, pqual, psort, sq_save_args, sq);
274 if (status != MR_SUCCESS) {
278 status = (*v->post_rtn)(q, sq, v, action, actarg, cl);
280 /* normal retrieve */
281 status = do_retrieve(q, pqual, psort, action, actarg);
283 if (status != MR_SUCCESS) break;
285 status = (*v->post_rtn)(q, Argv, cl, action, actarg);
291 /* see if row already exists */
293 status = validate_row(q, Argv, v);
294 if (status != MR_EXISTS) break;
297 /* build "where" clause and perform update */
298 /* if q->rvar = NULL, perform post_rtn only */
300 build_qual(q->qual, q->argc, Argv, qual);
301 incremental_before(q->rtable, qual, argv_ro);
302 status = do_update(q, &Argv[q->argc], qual, action, actarg);
303 incremental_after(q->rtable, qual, argv_ro);
304 if (status != MR_SUCCESS) break;
305 flush_name(argv_ro[0], q->rtable);
306 table_name = q->rtable;
307 if (strcmp(q->shortname, "sshi") && strcmp(q->shortname, "ssif")) {
308 EXEC SQL UPDATE tblstats
309 SET updates = updates + 1, modtime = 'now'
310 WHERE table_name = :table_name;
314 /* execute followup routine (if any) */
315 if (v->post_rtn) status = (*v->post_rtn)(q, Argv, cl);
320 /* see if row already exists */
322 status = validate_row(q, Argv, v);
323 if (status != MR_NO_MATCH) break;
326 /* build "where" clause if needed */
328 build_qual(q->qual, q->argc, Argv, qual);
334 /* perform the append */
335 /* if q->rvar = NULL, perform post_rtn only */
337 incremental_clear_before();
338 status = do_append(q, &Argv[q->argc], pqual, action, actarg);
339 if (status != MR_SUCCESS) break;
340 if (v && v->object_id) {
341 sprintf(qual, "%s.%s = %s",q->rvar, v->object_id,
342 Argv[q->argc+q->vcnt]);
343 incremental_after(q->rtable, qual, argv_ro);
345 incremental_after(q->rtable, pqual, argv_ro);
347 table_name = q->rtable;
348 EXEC SQL UPDATE tblstats
349 SET appends = appends + 1, modtime = 'now'
350 WHERE table_name = :table_name;
353 /* execute followup routine */
354 if (v->post_rtn) status = (*v->post_rtn)(q, Argv, cl);
358 /* see if row already exists */
360 status = validate_row(q, Argv, v);
361 if (status != MR_EXISTS) break;
364 /* build "where" clause and perform delete */
365 /* if q->rvar = NULL, perform post_rtn only */
367 build_qual(q->qual, q->argc, Argv, qual);
368 table_name = q->rtable;
369 incremental_before(q->rtable, qual, argv_ro);
370 status = do_delete(q, qual, action, actarg);
371 incremental_clear_after();
372 if (status != MR_SUCCESS) break;
373 flush_name(argv_ro[0], q->rtable);
374 EXEC SQL UPDATE tblstats
375 SET deletes = deletes + 1, modtime = 'now'
376 WHERE table_name = :table_name;
379 /* execute followup routine */
380 if (v->post_rtn) status = (*v->post_rtn)(q, Argv, cl);
386 if (status == MR_SUCCESS && ingres_errno != 0) {
387 com_err(whoami, MR_INTERNAL, "Server didn't notice INGRES ERROR %d",
392 if (q->type == RETRIEVE) {
393 EXEC SQL COMMIT WORK;
395 if (status == MR_SUCCESS) {
396 EXEC SQL COMMIT WORK;
402 fprintf(journal, "%% %s %s %s",
403 cl->clname, cl->entity, ctime(&now));
404 fprintf(journal, "%s[%d] ", q->name, cl->args->mr_version_no);
405 for (i = 0; i < argc; i++) {
409 requote(buf, argv_ro[i], sizeof(buf));
415 incremental_update();
418 if (ingres_errno != INGRES_DEADLOCK) {
419 EXEC SQL ROLLBACK WORK;
424 cache_commit(); /* commit following abort is safe */
426 if (status != MR_SUCCESS && log_flags & LOG_RES)
427 com_err(whoami, status, " (Query failed)");
431 build_qual(fmt, argc, argv, qual)
443 for (i = 0; i < argc; i++) {
445 if (c++ == (char *)0) return(MR_ARGS);
449 *(int *)&args[i] = *(int *)argv[i]; /* sigh */
451 return(MR_INGRES_ERR);
453 if (c = index(c, '%')) {
454 args[i] = args[i - 1];
463 sprintf(qual, fmt, args[0]);
467 sprintf(qual, fmt, args[0], args[1]);
471 sprintf(qual, fmt, args[0], args[1], args[2]);
475 sprintf(qual, fmt, args[0], args[1], args[2], args[3]);
479 com_err(whoami, MR_INTERNAL,
480 "Internal arg count error processing query");
488 register struct validate *v;
491 register struct valobj *vo;
500 if (vo->type == V_SORT) {
501 sprintf(elem, "%d", vo->index + 1); /* Result column number */
502 if (*sort) strcat(sort, ", ");
508 return ((*sort) ? sort : 0);
512 /* Build arguement vector, verify query and arguments */
514 mr_verify_query(cl, q, argc, argv_ro)
522 register struct validate *v = q->validate;
524 register int privileged = 0;
525 register char *to,*fr,*stop;
527 /* copy the arguments into a local argv that we can modify */
528 if (argc >= QMAXARGS)
530 for (i = 0; i < argc; i++) {
531 /* Single quotes must be doubled for SQL */
532 for (to=Argv[i], fr=argv_ro[i], stop=to+ARGLEN; (*fr) && (to<stop);) {
538 return(MR_ARG_TOO_LONG);
545 /* check initial query access */
546 status = check_query_access(q, Argv, cl);
547 if (status != MR_SUCCESS && status != MR_PERM)
549 if (status == MR_SUCCESS)
552 /* check argument count */
554 if (q->type == UPDATE || q->type == APPEND) argreq += q->vcnt;
555 if (argc != argreq) return(MR_ARGS);
557 /* validate arguments */
558 if (v && v->valobj) {
559 status = validate_fields(q, Argv, v->valobj, v->objcnt);
560 if (status != MR_SUCCESS) return(status);
563 /* perform special query access check */
564 if (!privileged && v && v->acs_rtn) {
565 status = (*v->acs_rtn)(q, Argv, cl);
566 if (status != MR_SUCCESS && status != MR_PERM)
568 if (status == MR_SUCCESS)
572 return(privileged ? MR_SUCCESS : MR_PERM);
576 /* This routine caches info from the database. Each query acl is stored
577 * in the query structure, and whether that acl contains everybody.
580 check_query_access(q, argv, cl)
585 EXEC SQL BEGIN DECLARE SECTION;
591 EXEC SQL END DECLARE SECTION;
596 /* initialize default uid */
598 EXEC SQL SELECT users_id INTO :def_uid FROM users WHERE login='default';
601 /* get query access control list */
606 EXEC SQL SELECT list_id INTO :acl_id FROM capacls WHERE tag = :name;
607 if (sqlca.sqlcode < 0) return(MR_INGRES_ERR);
608 if (sqlca.sqlcode == 100) return(MR_PERM);
611 /* check for default access */
612 EXEC SQL SELECT member_id INTO :acl_id FROM imembers
613 WHERE list_id = :acl_id AND member_type = 'USER'
614 AND member_id = :def_uid;
615 if (sqlca.sqlerrd[2] == 0)
624 if (get_client(cl, &client_type, &client_id) != MR_SUCCESS)
626 if (find_member("LIST", acl_id, client_type, client_id, 0))
633 get_client(cl, client_type, client_id)
638 if (cl->users_id > 0) {
639 *client_id = cl->users_id;
640 *client_type = "USER";
644 if (cl->client_id < 0) {
645 *client_id = -cl->users_id;
646 *client_type = "KERBEROS";
653 find_member(list_type, list_id, member_type, member_id)
655 EXEC SQL BEGIN DECLARE SECTION;
659 EXEC SQL END DECLARE SECTION;
661 EXEC SQL BEGIN DECLARE SECTION;
663 EXEC SQL END DECLARE SECTION;
665 if (!strcmp(strtrim(list_type), strtrim(member_type)) &&
666 list_id == member_id)
669 /* see if client is a direct member of list */
671 EXEC SQL SELECT member_id INTO :flag FROM imembers
672 WHERE list_id = :list_id AND member_type = :member_type
673 AND member_id = :member_id;
674 if(flag!=0) flag=1; /** Not strictly necessary */
675 if (sqlca.sqlcode == 0)
681 do_retrieve(q, pqual, psort, action, actarg)
682 register struct query *q;
683 EXEC SQL BEGIN DECLARE SECTION;
686 EXEC SQL END DECLARE SECTION;
690 static char **vaddrs = (char **)NULL;
696 if ((vaddrs = (char **)malloc(sizeof(char *) * QMAXARGS)) == NULL) {
697 com_err(whoami, MR_NO_MEM, "setting up static argv");
700 for (i = 0; i < QMAXARGS; i++) {
701 vaddrs[i]=SQLDA->sqlvar[i].sqldata;
705 build_sql_stmt(stmt_buf,"SELECT",q->tlist,vaddrs,pqual);
706 if(psort) { strcat(stmt_buf," ORDER BY "); strcat(stmt_buf,psort); }
707 EXEC SQL PREPARE stmt INTO :SQLDA USING NAMES FROM :stmt_buf;
710 EXEC SQL DECLARE csr001 CURSOR FOR stmt;
711 EXEC SQL OPEN csr001;
714 EXEC SQL FETCH csr001 USING DESCRIPTOR :SQLDA;
715 if(sqlca.sqlcode != 0) break;
716 (*action)(q->vcnt, vaddrs, actarg);
719 EXEC SQL CLOSE csr001;
721 if (mr_errcode) return(mr_errcode);
722 return ((rowcount == 0) ? MR_NO_MATCH : MR_SUCCESS);
725 char *sqlstrstr(str,pat)
729 register char *p=pat;
732 if(*str=='\'') { /* Skip over single-quote delimited substrings */
733 while(*++str && (*str!='\''))
740 while(*++p && (*++s==*p))
742 if(*p) p=pat; /* failed */
744 } while(*p && *++str);
750 void optimize_sql_stmt(buf)
753 char *point=buf, *pat, *eopat, *esc1, *esc2, *csr;
755 for(point=buf; point=sqlstrstr(point,"LIKE"); point++) {
756 /* Now pointing to string "LIKE" */
758 /* Look at next word */
759 for(pat=point+4; *pat==' '; pat++) ;
761 /* Is it a single-quote delimited string? */
762 if(*pat!='\'') continue;
764 /* look for "escape" clause - save escape character */
765 /* 1. Find end of pattern */
766 for(eopat=pat+1; 1; eopat++) {
768 if(eopat[1]=='\'') /* single-quote is self-escaping */
775 /* 2. Look at next word */
776 for(esc1=eopat; *++esc1==' ';) ;
778 /* 3. esc1=0 if not "ESCAPE '?'", where the ? may be any character. */
779 if(strncmp(esc1,"ESCAPE",6)) esc1=NULL;
782 for(esc2=esc1+6; *esc2==' '; esc2++) ;
784 if(*esc2++!='\'') continue; /* Bad SQL syntax. Skip. */
785 /* esc2 now points at the escape character itself */
786 if(esc2[1]!='\'') continue; /* Weird escape string. Skip. */
791 /* Is pattern free from special characters? */
792 for(csr=pat; csr<eopat; csr++)
793 if((*csr=='%') || (*csr=='_') || (*csr==*esc2)) break;
794 if(csr!=eopat) continue; /* Uses pattern matching. Skip. */
796 /* Optimize the query statement */
797 /* 1. Change "LIKE" to " = " */
798 memcpy(point," = ",4);
800 /* 2. Change "ESCAPE" to " " */
803 /* 3. Change "'*'" to " " */
804 /* (Changes '''' to " ") */
805 if(esc2) memset(esc2-1,' ',(*esc2=='\'')?4:3);
810 build_sql_stmt(result_buf,cmd,targetlist,argv,qual)
817 char fmt_buf[MR_STMTBUF_LEN];
818 register char *res, *fmt;
821 sprintf(fmt_buf,"%s %s WHERE %s",cmd,targetlist,qual);
823 sprintf(fmt_buf,"%s %s",cmd,targetlist);
825 for(res=result_buf, fmt=fmt_buf; *fmt; fmt++) {
829 case '%': /* %% -> % */
841 sprintf(res,"%d",*(int *)*argv++); /* print to result buffer */
844 default: /* Swallow other %? pairs */
848 } else *res++ = *fmt; /* text -> result buffer */
852 optimize_sql_stmt(result_buf);
855 do_update(q, argv, qual, action, actarg)
856 register struct query *q;
862 build_sql_stmt(stmt_buf,"UPDATE",q->tlist,argv,qual);
863 EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
864 if (mr_errcode) return(mr_errcode);
868 do_append(q, argv, pqual, action, actarg)
869 register struct query *q;
875 build_sql_stmt(stmt_buf,"INSERT",q->tlist,argv,pqual);
876 EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
877 if (mr_errcode) return(mr_errcode);
881 do_delete(q, qual, action, actarg)
882 register struct query *q;
887 sprintf(stmt_buf,"DELETE FROM %s WHERE %s",q->rtable,qual);
888 EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
889 if (mr_errcode) return(mr_errcode);
895 ** set_next_object_id - set next object id in values table
897 ** Inputs: object - object name in values table and in objects
898 ** table - name of table objects are found in
899 ** limit - should the ID be range limited
901 ** - called before an APPEND operation to set the next object id to
902 ** be used for the new record to the next free value
906 set_next_object_id(object, table_name, limit)
907 EXEC SQL BEGIN DECLARE SECTION;
911 EXEC SQL END DECLARE SECTION;
913 EXEC SQL BEGIN DECLARE SECTION;
915 EXEC SQL END DECLARE SECTION;
918 EXEC SQL SELECT value INTO :value FROM numvalues WHERE name = :object;
919 if (sqlca.sqlerrd[2] != 1)
922 starting_value=value;
924 if (limit && value > MAX_ID_VALUE)
925 value = MIN_ID_VALUE;
927 sprintf(stmt_buf,"SELECT %s FROM %s WHERE %s=%d",object,table_name,object,value);
928 EXEC SQL PREPARE stmt INTO :SQLDA USING NAMES FROM :stmt_buf;
931 EXEC SQL DECLARE csr002 CURSOR FOR stmt;
932 EXEC SQL OPEN csr002;
933 EXEC SQL FETCH csr002 USING DESCRIPTOR :SQLDA;
934 if (sqlca.sqlcode < 0) return(mr_errcode);
935 if (sqlca.sqlcode == 100) break;
937 EXEC SQL CLOSE csr002;
939 if (limit && value == starting_value) {
940 com_err(whoami,0,"All id values have been used");
944 EXEC SQL CLOSE csr002;
947 com_err(whoami, 0, "setting ID %s to %d", object, value);
948 EXEC SQL UPDATE numvalues SET value = :value WHERE name = :object;
953 /* Turn a kerberos name into the user's ID of the account that principal
954 * owns. Sets the kerberos ID and user ID.
957 int set_krb_mapping(name, login, ok, kid, uid)
964 EXEC SQL BEGIN DECLARE SECTION;
967 EXEC SQL END DECLARE SECTION;
973 EXEC SQL SELECT km.users_id, km.string_id INTO :u_id, :k_id
974 FROM krbmap km, strings str
975 WHERE km.string_id = str.string_id AND str.string = :krbname;
976 EXEC SQL COMMIT WORK;
978 if (ingres_errno) return(mr_errcode);
980 if (sqlca.sqlerrd[2] == 1) { /* rowcount */
986 if (name_to_id(name, "STRINGS", &k_id) == MR_SUCCESS)
994 if (name_to_id(login, "USERS", uid) != MR_SUCCESS)
999 if (ingres_errno) return(mr_errcode);
1004 /* For now this just checks the argc's. It should also see that there
1005 * are no duplicate names.
1008 sanity_check_queries()
1011 int maxv = 0, maxa = 0;
1012 #ifdef MULTIPROTOCOLS
1013 extern int QueryCount1, QueryCount2;
1014 extern struct query Queries1[], Queries2[];
1016 extern int QueryCount2;
1017 extern struct query Queries2[];
1018 #endif MULTIPROTOCOLS
1020 #define MAX(x,y) ((x) > (y) ? (x) : (y))
1022 #ifdef MULTIPROTOCOLS
1023 for (i = 0; i < QueryCount1; i++) {
1024 maxv = MAX(maxv, Queries1[i].vcnt);
1025 maxa = MAX(maxa, Queries1[i].argc);
1027 #endif MULTIPROTOCOLS
1028 for (i = 0; i < QueryCount2; i++) {
1029 maxv = MAX(maxv, Queries2[i].vcnt);
1030 maxa = MAX(maxa, Queries2[i].argc);
1032 if (MAX(maxv, maxa) > QMAXARGS) {
1033 com_err(whoami, 0, "A query has more args than QMAXARGS");