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 EXEC SQL END DECLARE SECTION;
42 #define INGRES_BAD_DATE1 40206
43 #define INGRES_BAD_DATE2 40207
44 #define INGRES_DEADLOCK 49900
45 #define INGRES_TIMEOUT 39100
46 #define INGRES_BAD_COLUMN 30110
47 #define INGRES_ASGN_ERR 40204
48 #define INGRES_NO_CURSOR 30120
49 #define INGRES_NO_STMT 30130
52 * ingerr: Called when Ingres indicates an error.
57 EXEC SQL BEGIN DECLARE SECTION;
59 EXEC SQL END DECLARE SECTION;
60 ingres_errno = -sqlca.sqlcode;
62 switch (ingres_errno) {
63 case INGRES_BAD_DATE1:
64 case INGRES_BAD_DATE2:
68 mr_errcode = MR_DEADLOCK;
69 com_err(whoami, 0, "INGRES deadlock detected");
72 /* May be something other than timeout! #39100 is "Unknown error"
73 * Really should parse the error message enough to decide if it's a timeout */
75 com_err(whoami, 0, "timed out getting lock");
77 /* These should never come up unless someone breaks the query table */
78 case INGRES_NO_CURSOR:
79 mr_errcode = MR_INTERNAL;
80 com_err(whoami, 0, "Cursor not opened");
83 mr_errcode = MR_INTERNAL;
84 com_err(whoami, 0, "Statement not declared");
86 case INGRES_BAD_COLUMN:
87 mr_errcode = MR_INTERNAL;
88 com_err(whoami, 0, "Bad column name in query table");
91 mr_errcode = MR_INTERNAL;
92 com_err(whoami, 0, "Error in SQL assignment statement");
96 mr_errcode = MR_INGRES_ERR;
97 com_err(whoami, MR_INGRES_ERR, " code %d\n", ingres_errno);
98 EXEC SQL INQUIRE_SQL(:err_msg = errortext);
99 com_err(whoami, 0, "SQL error text = %s", err_msg);
100 critical_alert("MOIRA", "Moira server encountered INGRES ERROR %d", ingres_errno);
104 /* This is declarative, not executed. Applies from here on, in this file. */
105 EXEC SQL WHENEVER SQLERROR CALL ingerr;
107 int mr_open_database()
111 MR_SQLDA_T *mr_alloc_SQLDA();
112 static first_open = 1;
117 /* initialize local argv */
118 for (i = 0; i < 16; i++)
119 Argv[i] = malloc(ARGLEN);
121 SQLDA = mr_alloc_SQLDA();
130 /* open the database */
132 EXEC SQL CONNECT moira;
134 return (ingres_errno);
135 EXEC SQL set lockmode session where level = table, timeout = :query_timeout;
136 EXEC SQL set lockmode on capacls where readlock = shared;
137 EXEC SQL set lockmode on alias where readlock = shared;
140 EXEC SQL DATABASE moira
146 EXEC SQL SELECT SIZE(signature) INTO :mr_sig_length FROM users WHERE users_id=0; /* Harmless on second open */
153 int mr_close_database()
161 mr_check_access(cl, name, argc, argv_ro)
168 struct query *get_query_by_name();
173 q = get_query_by_name(name, cl->args->mr_version_no);
174 if (q == (struct query *)0)
175 return(MR_NO_HANDLE);
177 return(mr_verify_query(cl, q, argc, argv_ro));
180 mr_process_query(cl, name, argc, argv_ro, action, actarg)
188 register struct query *q;
190 register struct validate *v;
195 EXEC SQL BEGIN DECLARE SECTION;
197 EXEC SQL END DECLARE SECTION;
198 struct save_queue *sq;
199 struct query *get_query_by_name();
201 struct save_queue *sq_create();
207 /* list queries command */
208 if (!strcmp(name, "_list_queries")) {
209 list_queries(cl->args->mr_version_no, action, actarg);
213 /* help query command */
214 if (!strcmp(name, "_help")) {
217 q = get_query_by_name(argv_ro[0], cl->args->mr_version_no);
218 if (q == (struct query *)0) return(MR_NO_HANDLE);
219 help_query(q, action, actarg);
223 /* get query structure, return error if named query does not exist */
224 q = get_query_by_name(name, cl->args->mr_version_no);
225 if (q == (struct query *)0) return(MR_NO_HANDLE);
228 /* setup argument vector, verify access and arguments */
229 if ((status = mr_verify_query(cl, q, argc, argv_ro)) != MR_SUCCESS)
232 /* perform any special query pre-processing */
233 if (v && v->pre_rtn) {
234 status = (*v->pre_rtn)(q, Argv, cl, 0);
235 if (status != MR_SUCCESS)
241 /* for queries that do not permit wildcarding, check if row
244 status = validate_row(q, Argv, v);
245 if (status != MR_EXISTS) break;
248 /* build "where" clause if needed */
250 build_qual(q->qual, q->argc, Argv, qual);
256 /* build "sort" clause if needed */
257 if (v && v->valobj) {
258 psort = build_sort(v, sort);
263 /* if there is a followup routine, then we must save the results */
264 /* of the first query for use by the followup routine */
265 /* if q->rvar = NULL, perform post_rtn only */
267 if (v && v->post_rtn) {
269 status = do_retrieve(q, pqual, psort, sq_save_args, sq);
270 if (status != MR_SUCCESS) {
274 status = (*v->post_rtn)(q, sq, v, action, actarg, cl);
276 /* normal retrieve */
277 status = do_retrieve(q, pqual, psort, action, actarg);
279 if (status != MR_SUCCESS) break;
281 status = (*v->post_rtn)(q, Argv, cl, action, actarg);
287 /* see if row already exists */
289 status = validate_row(q, Argv, v);
290 if (status != MR_EXISTS) break;
293 /* build "where" clause and perform update */
294 /* if q->rvar = NULL, perform post_rtn only */
296 build_qual(q->qual, q->argc, Argv, qual);
297 incremental_before(q->rtable, qual, argv_ro);
298 status = do_update(q, &Argv[q->argc], qual, action, actarg);
299 incremental_after(q->rtable, qual, argv_ro);
300 if (status != MR_SUCCESS) break;
301 flush_name(argv_ro[0], q->rtable);
302 table_name = q->rtable;
303 if (strcmp(q->shortname, "sshi") && strcmp(q->shortname, "ssif")) {
304 EXEC SQL UPDATE tblstats
305 SET updates = updates + 1, modtime = 'now'
306 WHERE table_name = :table_name;
310 /* execute followup routine (if any) */
311 if (v->post_rtn) status = (*v->post_rtn)(q, Argv, cl);
316 /* see if row already exists */
318 status = validate_row(q, Argv, v);
319 if (status != MR_NO_MATCH) break;
322 /* build "where" clause if needed */
324 build_qual(q->qual, q->argc, Argv, qual);
330 /* perform the append */
331 /* if q->rvar = NULL, perform post_rtn only */
333 incremental_clear_before();
334 status = do_append(q, &Argv[q->argc], pqual, action, actarg);
335 if (status != MR_SUCCESS) break;
336 if (v && v->object_id) {
337 sprintf(qual, "%s.%s = %s",q->rvar, v->object_id,
338 Argv[q->argc+q->vcnt]);
339 incremental_after(q->rtable, qual, argv_ro);
341 incremental_after(q->rtable, pqual, argv_ro);
343 table_name = q->rtable;
344 EXEC SQL UPDATE tblstats
345 SET appends = appends + 1, modtime = 'now'
346 WHERE table_name = :table_name;
349 /* execute followup routine */
350 if (v->post_rtn) status = (*v->post_rtn)(q, Argv, cl);
354 /* see if row already exists */
356 status = validate_row(q, Argv, v);
357 if (status != MR_EXISTS) break;
360 /* build "where" clause and perform delete */
361 /* if q->rvar = NULL, perform post_rtn only */
363 build_qual(q->qual, q->argc, Argv, qual);
364 table_name = q->rtable;
365 incremental_before(q->rtable, qual, argv_ro);
366 status = do_delete(q, qual, action, actarg);
367 incremental_clear_after();
368 if (status != MR_SUCCESS) break;
369 flush_name(argv_ro[0], q->rtable);
370 EXEC SQL UPDATE tblstats
371 SET deletes = deletes + 1, modtime = 'now'
372 WHERE table_name = :table_name;
375 /* execute followup routine */
376 if (v->post_rtn) status = (*v->post_rtn)(q, Argv, cl);
382 if (status == MR_SUCCESS && ingres_errno != 0) {
383 com_err(whoami, MR_INTERNAL, "Server didn't notice INGRES ERROR %d",
388 if (q->type == RETRIEVE) {
389 EXEC SQL COMMIT WORK;
391 if (status == MR_SUCCESS) {
392 EXEC SQL COMMIT WORK;
398 fprintf(journal, "%% %s %s %s",
399 cl->clname, cl->entity, ctime(&now));
400 fprintf(journal, "%s[%d] ", q->name, cl->args->mr_version_no);
401 for (i = 0; i < argc; i++) {
405 requote(buf, argv_ro[i], sizeof(buf));
411 incremental_update();
414 if (ingres_errno != INGRES_DEADLOCK) {
415 EXEC SQL ROLLBACK WORK;
420 cache_commit(); /* commit following abort is safe */
422 if (status != MR_SUCCESS && log_flags & LOG_RES)
423 com_err(whoami, status, " (Query failed)");
427 build_qual(fmt, argc, argv, qual)
439 for (i = 0; i < argc; i++) {
441 if (c++ == (char *)0) return(MR_ARGS);
445 *(int *)&args[i] = *(int *)argv[i]; /* sigh */
447 return(MR_INGRES_ERR);
449 if (c = index(c, '%')) {
450 args[i] = args[i - 1];
459 sprintf(qual, fmt, args[0]);
463 sprintf(qual, fmt, args[0], args[1]);
467 sprintf(qual, fmt, args[0], args[1], args[2]);
471 sprintf(qual, fmt, args[0], args[1], args[2], args[3]);
475 com_err(whoami, MR_INTERNAL,
476 "Internal arg count error processing query");
484 register struct validate *v;
487 register struct valobj *vo;
496 if (vo->type == V_SORT) {
497 sprintf(elem, "%d", vo->index + 1); /* Result column number */
498 if (*sort) strcat(sort, ", ");
504 return ((*sort) ? sort : 0);
508 /* Build arguement vector, verify query and arguments */
510 mr_verify_query(cl, q, argc, argv_ro)
518 register struct validate *v = q->validate;
520 register int privileged = 0;
521 register char *to,*fr,*stop;
523 /* copy the arguments into a local argv that we can modify */
524 if (argc >= QMAXARGS)
526 for (i = 0; i < argc; i++) {
527 /* Single quotes must be doubled for SQL */
528 for (to=Argv[i], fr=argv_ro[i], stop=to+ARGLEN; (*fr) && (to<stop);) {
534 return(MR_ARG_TOO_LONG);
541 /* check initial query access */
542 status = check_query_access(q, Argv, cl);
543 if (status != MR_SUCCESS && status != MR_PERM)
545 if (status == MR_SUCCESS)
548 /* check argument count */
550 if (q->type == UPDATE || q->type == APPEND) argreq += q->vcnt;
551 if (argc != argreq) return(MR_ARGS);
553 /* validate arguments */
554 if (v && v->valobj) {
555 status = validate_fields(q, Argv, v->valobj, v->objcnt);
556 if (status != MR_SUCCESS) return(status);
559 /* perform special query access check */
560 if (!privileged && v && v->acs_rtn) {
561 status = (*v->acs_rtn)(q, Argv, cl);
562 if (status != MR_SUCCESS && status != MR_PERM)
564 if (status == MR_SUCCESS)
568 return(privileged ? MR_SUCCESS : MR_PERM);
572 /* This routine caches info from the database. Each query acl is stored
573 * in the query structure, and whether that acl contains everybody.
576 check_query_access(q, argv, cl)
581 EXEC SQL BEGIN DECLARE SECTION;
587 EXEC SQL END DECLARE SECTION;
592 /* initialize default uid */
594 EXEC SQL SELECT users_id INTO :def_uid FROM users WHERE login='default';
597 /* get query access control list */
602 EXEC SQL SELECT list_id INTO :acl_id FROM capacls WHERE tag = :name;
603 if (sqlca.sqlcode < 0) return(MR_INGRES_ERR);
604 if (sqlca.sqlcode == 100) return(MR_PERM);
607 /* check for default access */
608 EXEC SQL SELECT member_id INTO :acl_id FROM imembers
609 WHERE list_id = :acl_id AND member_type = 'USER'
610 AND member_id = :def_uid;
611 if (sqlca.sqlerrd[2] == 0)
620 if (get_client(cl, &client_type, &client_id) != MR_SUCCESS)
622 if (find_member("LIST", acl_id, client_type, client_id, 0))
629 get_client(cl, client_type, client_id)
634 if (cl->users_id > 0) {
635 *client_id = cl->users_id;
636 *client_type = "USER";
640 if (cl->client_id < 0) {
641 *client_id = -cl->users_id;
642 *client_type = "KERBEROS";
649 find_member(list_type, list_id, member_type, member_id)
651 EXEC SQL BEGIN DECLARE SECTION;
655 EXEC SQL END DECLARE SECTION;
657 EXEC SQL BEGIN DECLARE SECTION;
659 EXEC SQL END DECLARE SECTION;
661 if (!strcmp(strtrim(list_type), strtrim(member_type)) &&
662 list_id == member_id)
665 /* see if client is a direct member of list */
667 EXEC SQL SELECT member_id INTO :flag FROM imembers
668 WHERE list_id = :list_id AND member_type = :member_type
669 AND member_id = :member_id;
670 if(flag!=0) flag=1; /** Not strictly necessary */
671 if (sqlca.sqlcode == 0)
677 do_retrieve(q, pqual, psort, action, actarg)
678 register struct query *q;
679 EXEC SQL BEGIN DECLARE SECTION;
682 EXEC SQL END DECLARE SECTION;
686 static char **vaddrs = (char **)NULL;
692 if ((vaddrs = (char **)malloc(sizeof(char *) * QMAXARGS)) == NULL) {
693 com_err(whoami, MR_NO_MEM, "setting up static argv");
696 for (i = 0; i < QMAXARGS; i++) {
697 vaddrs[i]=SQLDA->sqlvar[i].sqldata;
701 build_sql_stmt(stmt_buf,"SELECT",q->tlist,vaddrs,pqual);
702 if(psort) { strcat(stmt_buf," ORDER BY "); strcat(stmt_buf,psort); }
703 EXEC SQL PREPARE stmt INTO :SQLDA USING NAMES FROM :stmt_buf;
706 EXEC SQL DECLARE csr001 CURSOR FOR stmt;
707 EXEC SQL OPEN csr001;
710 EXEC SQL FETCH csr001 USING DESCRIPTOR :SQLDA;
711 if(sqlca.sqlcode != 0) break;
712 (*action)(q->vcnt, vaddrs, actarg);
715 EXEC SQL CLOSE csr001;
717 if (mr_errcode) return(mr_errcode);
718 return ((rowcount == 0) ? MR_NO_MATCH : MR_SUCCESS);
721 char *sqlstrstr(str,pat)
725 register char *p=pat;
728 if(*str=='\'') { /* Skip over single-quote delimited substrings */
729 while(*++str && (*str!='\''))
736 while(*++p && (*++s==*p))
738 if(*p) p=pat; /* failed */
740 } while(*p && *++str);
746 void optimize_sql_stmt(buf)
749 char *point=buf, *pat, *eopat, *esc1, *esc2, *csr;
751 for(point=buf; point=sqlstrstr(point,"LIKE"); point++) {
752 /* Now pointing to string "LIKE" */
754 /* Look at next word */
755 for(pat=point+4; *pat==' '; pat++) ;
757 /* Is it a single-quote delimited string? */
758 if(*pat!='\'') continue;
760 /* look for "escape" clause - save escape character */
761 /* 1. Find end of pattern */
762 for(eopat=pat+1; 1; eopat++) {
764 if(eopat[1]=='\'') /* single-quote is self-escaping */
771 /* 2. Look at next word */
772 for(esc1=eopat; *++esc1==' ';) ;
774 /* 3. esc1=0 if not "ESCAPE '?'", where the ? may be any character. */
775 if(strncmp(esc1,"ESCAPE",6)) esc1=NULL;
778 for(esc2=esc1+6; *esc2==' '; esc2++) ;
780 if(*esc2++!='\'') continue; /* Bad SQL syntax. Skip. */
781 /* esc2 now points at the escape character itself */
782 if(esc2[1]!='\'') continue; /* Weird escape string. Skip. */
787 /* Is pattern free from special characters? */
788 for(csr=pat; csr<eopat; csr++)
789 if((*csr=='%') || (*csr=='_') || (*csr==*esc2)) break;
790 if(csr!=eopat) continue; /* Uses pattern matching. Skip. */
792 /* Optimize the query statement */
793 /* 1. Change "LIKE" to " = " */
794 memcpy(point," = ",4);
796 /* 2. Change "ESCAPE" to " " */
799 /* 3. Change "'*'" to " " */
800 /* (Changes '''' to " ") */
801 if(esc2) memset(esc2-1,' ',(*esc2=='\'')?4:3);
806 build_sql_stmt(result_buf,cmd,targetlist,argv,qual)
813 char fmt_buf[MR_STMTBUF_LEN];
814 register char *res, *fmt;
817 sprintf(fmt_buf,"%s %s WHERE %s",cmd,targetlist,qual);
819 sprintf(fmt_buf,"%s %s",cmd,targetlist);
821 for(res=result_buf, fmt=fmt_buf; *fmt; fmt++) {
825 case '%': /* %% -> % */
837 sprintf(res,"%d",*(int *)*argv++); /* print to result buffer */
840 default: /* Swallow other %? pairs */
844 } else *res++ = *fmt; /* text -> result buffer */
848 optimize_sql_stmt(result_buf);
851 do_update(q, argv, qual, action, actarg)
852 register struct query *q;
858 build_sql_stmt(stmt_buf,"UPDATE",q->tlist,argv,qual);
859 EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
860 if (mr_errcode) return(mr_errcode);
864 do_append(q, argv, pqual, action, actarg)
865 register struct query *q;
871 build_sql_stmt(stmt_buf,"INSERT",q->tlist,argv,pqual);
872 EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
873 if (mr_errcode) return(mr_errcode);
877 do_delete(q, qual, action, actarg)
878 register struct query *q;
883 sprintf(stmt_buf,"DELETE FROM %s WHERE %s",q->rtable,qual);
884 EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
885 if (mr_errcode) return(mr_errcode);
891 ** set_next_object_id - set next object id in values table
893 ** Inputs: object - object name in values table and in objects
894 ** table - name of table objects are found in
895 ** limit - should the ID be range limited
897 ** - called before an APPEND operation to set the next object id to
898 ** be used for the new record to the next free value
902 set_next_object_id(object, table_name, limit)
903 EXEC SQL BEGIN DECLARE SECTION;
907 EXEC SQL END DECLARE SECTION;
909 EXEC SQL BEGIN DECLARE SECTION;
911 EXEC SQL END DECLARE SECTION;
914 EXEC SQL SELECT value INTO :value FROM numvalues WHERE name = :object;
915 if (sqlca.sqlerrd[2] != 1)
918 starting_value=value;
920 if (limit && value > MAX_ID_VALUE)
921 value = MIN_ID_VALUE;
923 sprintf(stmt_buf,"SELECT %s FROM %s WHERE %s=%d",object,table_name,object,value);
924 EXEC SQL PREPARE stmt INTO :SQLDA USING NAMES FROM :stmt_buf;
927 EXEC SQL DECLARE csr002 CURSOR FOR stmt;
928 EXEC SQL OPEN csr002;
929 EXEC SQL FETCH csr002 USING DESCRIPTOR :SQLDA;
930 if (sqlca.sqlcode < 0) return(mr_errcode);
931 if (sqlca.sqlcode == 100) break;
933 EXEC SQL CLOSE csr002;
935 if (limit && value == starting_value) {
936 com_err(whoami,0,"All id values have been used");
940 EXEC SQL CLOSE csr002;
943 com_err(whoami, 0, "setting ID %s to %d", object, value);
944 EXEC SQL UPDATE numvalues SET value = :value WHERE name = :object;
949 /* Turn a kerberos name into the user's ID of the account that principal
950 * owns. Sets the kerberos ID and user ID.
953 int set_krb_mapping(name, login, ok, kid, uid)
960 EXEC SQL BEGIN DECLARE SECTION;
963 EXEC SQL END DECLARE SECTION;
969 EXEC SQL SELECT km.users_id, km.string_id INTO :u_id, :k_id
970 FROM krbmap km, strings str
971 WHERE km.string_id = str.string_id AND str.string = :krbname;
973 if (ingres_errno) return(mr_errcode);
975 if (sqlca.sqlerrd[2] == 1) { /* rowcount */
981 if (name_to_id(name, "STRINGS", &k_id) == MR_SUCCESS)
989 if (name_to_id(login, "USERS", uid) != MR_SUCCESS)
994 if (ingres_errno) return(mr_errcode);
999 /* For now this just checks the argc's. It should also see that there
1000 * are no duplicate names.
1003 sanity_check_queries()
1006 int maxv = 0, maxa = 0;
1007 #ifdef MULTIPROTOCOLS
1008 extern int QueryCount1, QueryCount2;
1009 extern struct query Queries1[], Queries2[];
1011 extern int QueryCount2;
1012 extern struct query Queries2[];
1013 #endif MULTIPROTOCOLS
1015 #define MAX(x,y) ((x) > (y) ? (x) : (y))
1017 #ifdef MULTIPROTOCOLS
1018 for (i = 0; i < QueryCount1; i++) {
1019 maxv = MAX(maxv, Queries1[i].vcnt);
1020 maxa = MAX(maxa, Queries1[i].argc);
1022 #endif MULTIPROTOCOLS
1023 for (i = 0; i < QueryCount2; i++) {
1024 maxv = MAX(maxv, Queries2[i].vcnt);
1025 maxa = MAX(maxa, Queries2[i].argc);
1027 if (MAX(maxv, maxa) > QMAXARGS) {
1028 com_err(whoami, 0, "A query has more args than QMAXARGS");