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 mr_errcode = MR_INTERNAL;
81 com_err(whoami, 0, "Cursor not opened");
84 mr_errcode = MR_INTERNAL;
85 com_err(whoami, 0, "Statement not declared");
87 case INGRES_BAD_COLUMN:
88 mr_errcode = MR_INTERNAL;
89 com_err(whoami, 0, "Bad column name in query table");
92 mr_errcode = MR_INTERNAL;
93 com_err(whoami, 0, "Error in SQL assignment statement");
97 mr_errcode = MR_INGRES_ERR;
98 com_err(whoami, MR_INGRES_ERR, " code %d\n", ingres_errno);
99 EXEC SQL INQUIRE_SQL(:err_msg = errortext);
100 com_err(whoami, 0, "SQL error text = %s", err_msg);
101 critical_alert("MOIRA", "Moira server encountered INGRES ERROR %d", ingres_errno);
105 /* This is declarative, not executed. Applies from here on, in this file. */
106 EXEC SQL WHENEVER SQLERROR CALL ingerr;
108 int mr_open_database()
112 MR_SQLDA_T *mr_alloc_SQLDA();
113 static first_open = 1;
118 /* initialize local argv */
119 for (i = 0; i < 16; i++)
120 Argv[i] = malloc(ARGLEN);
122 SQLDA = mr_alloc_SQLDA();
131 /* open the database */
133 EXEC SQL CONNECT :database;
135 return (ingres_errno);
136 EXEC SQL set lockmode session where level = table, timeout = :query_timeout;
137 EXEC SQL set lockmode on capacls where readlock = shared;
138 EXEC SQL set lockmode on alias where readlock = shared;
141 EXEC SQL DATABASE moira
147 EXEC SQL SELECT SIZE(signature) INTO :mr_sig_length FROM users WHERE users_id=0; /* Harmless on second open */
148 EXEC SQL COMMIT WORK;
155 int mr_close_database()
163 mr_check_access(cl, name, argc, argv_ro)
170 struct query *get_query_by_name();
175 q = get_query_by_name(name, cl->args->mr_version_no);
176 if (q == (struct query *)0)
177 return(MR_NO_HANDLE);
179 return(mr_verify_query(cl, q, argc, argv_ro));
182 mr_process_query(cl, name, argc, argv_ro, action, actarg)
190 register struct query *q;
192 register struct validate *v;
197 EXEC SQL BEGIN DECLARE SECTION;
199 EXEC SQL END DECLARE SECTION;
200 struct save_queue *sq;
201 struct query *get_query_by_name();
203 struct save_queue *sq_create();
209 /* list queries command */
210 if (!strcmp(name, "_list_queries")) {
211 list_queries(cl->args->mr_version_no, action, actarg);
215 /* help query command */
216 if (!strcmp(name, "_help")) {
219 q = get_query_by_name(argv_ro[0], cl->args->mr_version_no);
220 if (q == (struct query *)0) return(MR_NO_HANDLE);
221 help_query(q, action, actarg);
225 /* get query structure, return error if named query does not exist */
226 q = get_query_by_name(name, cl->args->mr_version_no);
227 if (q == (struct query *)0) return(MR_NO_HANDLE);
230 /* setup argument vector, verify access and arguments */
231 if ((status = mr_verify_query(cl, q, argc, argv_ro)) != MR_SUCCESS)
234 /* perform any special query pre-processing */
235 if (v && v->pre_rtn) {
236 status = (*v->pre_rtn)(q, Argv, cl, 0);
237 if (status != MR_SUCCESS)
243 /* for queries that do not permit wildcarding, check if row
246 status = validate_row(q, Argv, v);
247 if (status != MR_EXISTS) break;
250 /* build "where" clause if needed */
252 build_qual(q->qual, q->argc, Argv, qual);
258 /* build "sort" clause if needed */
259 if (v && v->valobj) {
260 psort = build_sort(v, sort);
265 /* if there is a followup routine, then we must save the results */
266 /* of the first query for use by the followup routine */
267 /* if q->rvar = NULL, perform post_rtn only */
269 if (v && v->post_rtn) {
271 status = do_retrieve(q, pqual, psort, sq_save_args, sq);
272 if (status != MR_SUCCESS) {
276 status = (*v->post_rtn)(q, sq, v, action, actarg, cl);
278 /* normal retrieve */
279 status = do_retrieve(q, pqual, psort, action, actarg);
281 if (status != MR_SUCCESS) break;
283 status = (*v->post_rtn)(q, Argv, cl, action, actarg);
289 /* see if row already exists */
291 status = validate_row(q, Argv, v);
292 if (status != MR_EXISTS) break;
295 /* build "where" clause and perform update */
296 /* if q->rvar = NULL, perform post_rtn only */
298 build_qual(q->qual, q->argc, Argv, qual);
299 incremental_before(q->rtable, qual, argv_ro);
300 status = do_update(q, &Argv[q->argc], qual, action, actarg);
301 incremental_after(q->rtable, qual, argv_ro);
302 if (status != MR_SUCCESS) break;
303 flush_name(argv_ro[0], q->rtable);
304 table_name = q->rtable;
305 if (strcmp(q->shortname, "sshi") && strcmp(q->shortname, "ssif")) {
306 EXEC SQL UPDATE tblstats
307 SET updates = updates + 1, modtime = 'now'
308 WHERE table_name = :table_name;
312 /* execute followup routine (if any) */
313 if (v->post_rtn) status = (*v->post_rtn)(q, Argv, cl);
318 /* see if row already exists */
320 status = validate_row(q, Argv, v);
321 if (status != MR_NO_MATCH) break;
324 /* build "where" clause if needed */
326 build_qual(q->qual, q->argc, Argv, qual);
332 /* perform the append */
333 /* if q->rvar = NULL, perform post_rtn only */
335 incremental_clear_before();
336 status = do_append(q, &Argv[q->argc], pqual, action, actarg);
337 if (status != MR_SUCCESS) break;
338 if (v && v->object_id) {
339 sprintf(qual, "%s.%s = %s",q->rvar, v->object_id,
340 Argv[q->argc+q->vcnt]);
341 incremental_after(q->rtable, qual, argv_ro);
343 incremental_after(q->rtable, pqual, argv_ro);
345 table_name = q->rtable;
346 EXEC SQL UPDATE tblstats
347 SET appends = appends + 1, modtime = 'now'
348 WHERE table_name = :table_name;
351 /* execute followup routine */
352 if (v->post_rtn) status = (*v->post_rtn)(q, Argv, cl);
356 /* see if row already exists */
358 status = validate_row(q, Argv, v);
359 if (status != MR_EXISTS) break;
362 /* build "where" clause and perform delete */
363 /* if q->rvar = NULL, perform post_rtn only */
365 build_qual(q->qual, q->argc, Argv, qual);
366 table_name = q->rtable;
367 incremental_before(q->rtable, qual, argv_ro);
368 status = do_delete(q, qual, action, actarg);
369 incremental_clear_after();
370 if (status != MR_SUCCESS) break;
371 flush_name(argv_ro[0], q->rtable);
372 EXEC SQL UPDATE tblstats
373 SET deletes = deletes + 1, modtime = 'now'
374 WHERE table_name = :table_name;
377 /* execute followup routine */
378 if (v->post_rtn) status = (*v->post_rtn)(q, Argv, cl);
384 if (status == MR_SUCCESS && ingres_errno != 0) {
385 com_err(whoami, MR_INTERNAL, "Server didn't notice INGRES ERROR %d",
390 if (q->type == RETRIEVE) {
391 EXEC SQL COMMIT WORK;
393 if (status == MR_SUCCESS) {
394 EXEC SQL COMMIT WORK;
400 fprintf(journal, "%% %s %s %s",
401 cl->clname, cl->entity, ctime(&now));
402 fprintf(journal, "%s[%d] ", q->name, cl->args->mr_version_no);
403 for (i = 0; i < argc; i++) {
407 requote(buf, argv_ro[i], sizeof(buf));
413 incremental_update();
416 if (ingres_errno != INGRES_DEADLOCK) {
417 EXEC SQL ROLLBACK WORK;
422 cache_commit(); /* commit following abort is safe */
424 if (status != MR_SUCCESS && log_flags & LOG_RES)
425 com_err(whoami, status, " (Query failed)");
429 build_qual(fmt, argc, argv, qual)
441 for (i = 0; i < argc; i++) {
443 if (c++ == (char *)0) return(MR_ARGS);
447 *(int *)&args[i] = *(int *)argv[i]; /* sigh */
449 return(MR_INGRES_ERR);
451 if (c = index(c, '%')) {
452 args[i] = args[i - 1];
461 sprintf(qual, fmt, args[0]);
465 sprintf(qual, fmt, args[0], args[1]);
469 sprintf(qual, fmt, args[0], args[1], args[2]);
473 sprintf(qual, fmt, args[0], args[1], args[2], args[3]);
477 com_err(whoami, MR_INTERNAL,
478 "Internal arg count error processing query");
486 register struct validate *v;
489 register struct valobj *vo;
498 if (vo->type == V_SORT) {
499 sprintf(elem, "%d", vo->index + 1); /* Result column number */
500 if (*sort) strcat(sort, ", ");
506 return ((*sort) ? sort : 0);
510 /* Build arguement vector, verify query and arguments */
512 mr_verify_query(cl, q, argc, argv_ro)
520 register struct validate *v = q->validate;
522 register int privileged = 0;
523 register char *to,*fr,*stop;
525 /* copy the arguments into a local argv that we can modify */
526 if (argc >= QMAXARGS)
528 for (i = 0; i < argc; i++) {
529 /* Single quotes must be doubled for SQL */
530 for (to=Argv[i], fr=argv_ro[i], stop=to+ARGLEN; (*fr) && (to<stop);) {
536 return(MR_ARG_TOO_LONG);
543 /* check initial query access */
544 status = check_query_access(q, Argv, cl);
545 if (status != MR_SUCCESS && status != MR_PERM)
547 if (status == MR_SUCCESS)
550 /* check argument count */
552 if (q->type == UPDATE || q->type == APPEND) argreq += q->vcnt;
553 if (argc != argreq) return(MR_ARGS);
555 /* validate arguments */
556 if (v && v->valobj) {
557 status = validate_fields(q, Argv, v->valobj, v->objcnt);
558 if (status != MR_SUCCESS) return(status);
561 /* perform special query access check */
562 if (!privileged && v && v->acs_rtn) {
563 status = (*v->acs_rtn)(q, Argv, cl);
564 if (status != MR_SUCCESS && status != MR_PERM)
566 if (status == MR_SUCCESS)
570 return(privileged ? MR_SUCCESS : MR_PERM);
574 /* This routine caches info from the database. Each query acl is stored
575 * in the query structure, and whether that acl contains everybody.
578 check_query_access(q, argv, cl)
583 EXEC SQL BEGIN DECLARE SECTION;
589 EXEC SQL END DECLARE SECTION;
594 /* initialize default uid */
596 EXEC SQL SELECT users_id INTO :def_uid FROM users WHERE login='default';
599 /* get query access control list */
604 EXEC SQL SELECT list_id INTO :acl_id FROM capacls WHERE tag = :name;
605 if (sqlca.sqlcode < 0) return(MR_INGRES_ERR);
606 if (sqlca.sqlcode == 100) return(MR_PERM);
609 /* check for default access */
610 EXEC SQL SELECT member_id INTO :acl_id FROM imembers
611 WHERE list_id = :acl_id AND member_type = 'USER'
612 AND member_id = :def_uid;
613 if (sqlca.sqlerrd[2] == 0)
622 if (get_client(cl, &client_type, &client_id) != MR_SUCCESS)
624 if (find_member("LIST", acl_id, client_type, client_id, 0))
631 get_client(cl, client_type, client_id)
636 if (cl->users_id > 0) {
637 *client_id = cl->users_id;
638 *client_type = "USER";
642 if (cl->client_id < 0) {
643 *client_id = -cl->users_id;
644 *client_type = "KERBEROS";
651 find_member(list_type, list_id, member_type, member_id)
653 EXEC SQL BEGIN DECLARE SECTION;
657 EXEC SQL END DECLARE SECTION;
659 EXEC SQL BEGIN DECLARE SECTION;
661 EXEC SQL END DECLARE SECTION;
663 if (!strcmp(strtrim(list_type), strtrim(member_type)) &&
664 list_id == member_id)
667 /* see if client is a direct member of list */
669 EXEC SQL SELECT member_id INTO :flag FROM imembers
670 WHERE list_id = :list_id AND member_type = :member_type
671 AND member_id = :member_id;
672 if(flag!=0) flag=1; /** Not strictly necessary */
673 if (sqlca.sqlcode == 0)
679 do_retrieve(q, pqual, psort, action, actarg)
680 register struct query *q;
681 EXEC SQL BEGIN DECLARE SECTION;
684 EXEC SQL END DECLARE SECTION;
688 static char **vaddrs = (char **)NULL;
694 if ((vaddrs = (char **)malloc(sizeof(char *) * QMAXARGS)) == NULL) {
695 com_err(whoami, MR_NO_MEM, "setting up static argv");
698 for (i = 0; i < QMAXARGS; i++) {
699 vaddrs[i]=SQLDA->sqlvar[i].sqldata;
703 build_sql_stmt(stmt_buf,"SELECT",q->tlist,vaddrs,pqual);
704 if(psort) { strcat(stmt_buf," ORDER BY "); strcat(stmt_buf,psort); }
705 EXEC SQL PREPARE stmt INTO :SQLDA USING NAMES FROM :stmt_buf;
708 EXEC SQL DECLARE csr001 CURSOR FOR stmt;
709 EXEC SQL OPEN csr001;
712 EXEC SQL FETCH csr001 USING DESCRIPTOR :SQLDA;
713 if(sqlca.sqlcode != 0) break;
714 (*action)(q->vcnt, vaddrs, actarg);
717 EXEC SQL CLOSE csr001;
719 if (mr_errcode) return(mr_errcode);
720 return ((rowcount == 0) ? MR_NO_MATCH : MR_SUCCESS);
723 char *sqlstrstr(str,pat)
727 register char *p=pat;
730 if(*str=='\'') { /* Skip over single-quote delimited substrings */
731 while(*++str && (*str!='\''))
738 while(*++p && (*++s==*p))
740 if(*p) p=pat; /* failed */
742 } while(*p && *++str);
748 void optimize_sql_stmt(buf)
751 char *point=buf, *pat, *eopat, *esc1, *esc2, *csr;
753 for(point=buf; point=sqlstrstr(point,"LIKE"); point++) {
754 /* Now pointing to string "LIKE" */
756 /* Look at next word */
757 for(pat=point+4; *pat==' '; pat++) ;
759 /* Is it a single-quote delimited string? */
760 if(*pat!='\'') continue;
762 /* look for "escape" clause - save escape character */
763 /* 1. Find end of pattern */
764 for(eopat=pat+1; 1; eopat++) {
766 if(eopat[1]=='\'') /* single-quote is self-escaping */
773 /* 2. Look at next word */
774 for(esc1=eopat; *++esc1==' ';) ;
776 /* 3. esc1=0 if not "ESCAPE '?'", where the ? may be any character. */
777 if(strncmp(esc1,"ESCAPE",6)) esc1=NULL;
780 for(esc2=esc1+6; *esc2==' '; esc2++) ;
782 if(*esc2++!='\'') continue; /* Bad SQL syntax. Skip. */
783 /* esc2 now points at the escape character itself */
784 if(esc2[1]!='\'') continue; /* Weird escape string. Skip. */
789 /* Is pattern free from special characters? */
790 for(csr=pat; csr<eopat; csr++)
791 if((*csr=='%') || (*csr=='_') || (*csr==*esc2)) break;
792 if(csr!=eopat) continue; /* Uses pattern matching. Skip. */
794 /* Optimize the query statement */
795 /* 1. Change "LIKE" to " = " */
796 memcpy(point," = ",4);
798 /* 2. Change "ESCAPE" to " " */
801 /* 3. Change "'*'" to " " */
802 /* (Changes '''' to " ") */
803 if(esc2) memset(esc2-1,' ',(*esc2=='\'')?4:3);
808 build_sql_stmt(result_buf,cmd,targetlist,argv,qual)
815 char fmt_buf[MR_STMTBUF_LEN];
816 register char *res, *fmt;
819 sprintf(fmt_buf,"%s %s WHERE %s",cmd,targetlist,qual);
821 sprintf(fmt_buf,"%s %s",cmd,targetlist);
823 for(res=result_buf, fmt=fmt_buf; *fmt; fmt++) {
827 case '%': /* %% -> % */
839 sprintf(res,"%d",*(int *)*argv++); /* print to result buffer */
842 default: /* Swallow other %? pairs */
846 } else *res++ = *fmt; /* text -> result buffer */
850 optimize_sql_stmt(result_buf);
853 do_update(q, argv, qual, action, actarg)
854 register struct query *q;
860 build_sql_stmt(stmt_buf,"UPDATE",q->tlist,argv,qual);
861 EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
862 if (mr_errcode) return(mr_errcode);
866 do_append(q, argv, pqual, action, actarg)
867 register struct query *q;
873 build_sql_stmt(stmt_buf,"INSERT",q->tlist,argv,pqual);
874 EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
875 if (mr_errcode) return(mr_errcode);
879 do_delete(q, qual, action, actarg)
880 register struct query *q;
885 sprintf(stmt_buf,"DELETE FROM %s WHERE %s",q->rtable,qual);
886 EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
887 if (mr_errcode) return(mr_errcode);
893 ** set_next_object_id - set next object id in values table
895 ** Inputs: object - object name in values table and in objects
896 ** table - name of table objects are found in
897 ** limit - should the ID be range limited
899 ** - called before an APPEND operation to set the next object id to
900 ** be used for the new record to the next free value
904 set_next_object_id(object, table_name, limit)
905 EXEC SQL BEGIN DECLARE SECTION;
909 EXEC SQL END DECLARE SECTION;
911 EXEC SQL BEGIN DECLARE SECTION;
913 EXEC SQL END DECLARE SECTION;
916 EXEC SQL SELECT value INTO :value FROM numvalues WHERE name = :object;
917 if (sqlca.sqlerrd[2] != 1)
920 starting_value=value;
922 if (limit && value > MAX_ID_VALUE)
923 value = MIN_ID_VALUE;
925 sprintf(stmt_buf,"SELECT %s FROM %s WHERE %s=%d",object,table_name,object,value);
926 EXEC SQL PREPARE stmt INTO :SQLDA USING NAMES FROM :stmt_buf;
929 EXEC SQL DECLARE csr002 CURSOR FOR stmt;
930 EXEC SQL OPEN csr002;
931 EXEC SQL FETCH csr002 USING DESCRIPTOR :SQLDA;
932 if (sqlca.sqlcode < 0) return(mr_errcode);
933 if (sqlca.sqlcode == 100) break;
935 EXEC SQL CLOSE csr002;
937 if (limit && value == starting_value) {
938 com_err(whoami,0,"All id values have been used");
942 EXEC SQL CLOSE csr002;
945 com_err(whoami, 0, "setting ID %s to %d", object, value);
946 EXEC SQL UPDATE numvalues SET value = :value WHERE name = :object;
951 /* Turn a kerberos name into the user's ID of the account that principal
952 * owns. Sets the kerberos ID and user ID.
955 int set_krb_mapping(name, login, ok, kid, uid)
962 EXEC SQL BEGIN DECLARE SECTION;
965 EXEC SQL END DECLARE SECTION;
971 EXEC SQL SELECT km.users_id, km.string_id INTO :u_id, :k_id
972 FROM krbmap km, strings str
973 WHERE km.string_id = str.string_id AND str.string = :krbname;
974 EXEC SQL COMMIT WORK;
976 if (ingres_errno) return(mr_errcode);
978 if (sqlca.sqlerrd[2] == 1) { /* rowcount */
984 if (name_to_id(name, "STRINGS", &k_id) == MR_SUCCESS)
992 if (name_to_id(login, "USERS", uid) != MR_SUCCESS)
997 if (ingres_errno) return(mr_errcode);
1002 /* For now this just checks the argc's. It should also see that there
1003 * are no duplicate names.
1006 sanity_check_queries()
1009 int maxv = 0, maxa = 0;
1010 #ifdef MULTIPROTOCOLS
1011 extern int QueryCount1, QueryCount2;
1012 extern struct query Queries1[], Queries2[];
1014 extern int QueryCount2;
1015 extern struct query Queries2[];
1016 #endif MULTIPROTOCOLS
1018 #define MAX(x,y) ((x) > (y) ? (x) : (y))
1020 #ifdef MULTIPROTOCOLS
1021 for (i = 0; i < QueryCount1; i++) {
1022 maxv = MAX(maxv, Queries1[i].vcnt);
1023 maxa = MAX(maxa, Queries1[i].argc);
1025 #endif MULTIPROTOCOLS
1026 for (i = 0; i < QueryCount2; i++) {
1027 maxv = MAX(maxv, Queries2[i].vcnt);
1028 maxa = MAX(maxa, Queries2[i].argc);
1030 if (MAX(maxv, maxa) > QMAXARGS) {
1031 com_err(whoami, 0, "A query has more args than QMAXARGS");