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 */
147 EXEC SQL COMMIT WORK;
154 int mr_close_database()
162 mr_check_access(cl, name, argc, argv_ro)
169 struct query *get_query_by_name();
174 q = get_query_by_name(name, cl->args->mr_version_no);
175 if (q == (struct query *)0)
176 return(MR_NO_HANDLE);
178 return(mr_verify_query(cl, q, argc, argv_ro));
181 mr_process_query(cl, name, argc, argv_ro, action, actarg)
189 register struct query *q;
191 register struct validate *v;
196 EXEC SQL BEGIN DECLARE SECTION;
198 EXEC SQL END DECLARE SECTION;
199 struct save_queue *sq;
200 struct query *get_query_by_name();
202 struct save_queue *sq_create();
208 /* list queries command */
209 if (!strcmp(name, "_list_queries")) {
210 list_queries(cl->args->mr_version_no, action, actarg);
214 /* help query command */
215 if (!strcmp(name, "_help")) {
218 q = get_query_by_name(argv_ro[0], cl->args->mr_version_no);
219 if (q == (struct query *)0) return(MR_NO_HANDLE);
220 help_query(q, action, actarg);
224 /* get query structure, return error if named query does not exist */
225 q = get_query_by_name(name, cl->args->mr_version_no);
226 if (q == (struct query *)0) return(MR_NO_HANDLE);
229 /* setup argument vector, verify access and arguments */
230 if ((status = mr_verify_query(cl, q, argc, argv_ro)) != MR_SUCCESS)
233 /* perform any special query pre-processing */
234 if (v && v->pre_rtn) {
235 status = (*v->pre_rtn)(q, Argv, cl, 0);
236 if (status != MR_SUCCESS)
242 /* for queries that do not permit wildcarding, check if row
245 status = validate_row(q, Argv, v);
246 if (status != MR_EXISTS) break;
249 /* build "where" clause if needed */
251 build_qual(q->qual, q->argc, Argv, qual);
257 /* build "sort" clause if needed */
258 if (v && v->valobj) {
259 psort = build_sort(v, sort);
264 /* if there is a followup routine, then we must save the results */
265 /* of the first query for use by the followup routine */
266 /* if q->rvar = NULL, perform post_rtn only */
268 if (v && v->post_rtn) {
270 status = do_retrieve(q, pqual, psort, sq_save_args, sq);
271 if (status != MR_SUCCESS) {
275 status = (*v->post_rtn)(q, sq, v, action, actarg, cl);
277 /* normal retrieve */
278 status = do_retrieve(q, pqual, psort, action, actarg);
280 if (status != MR_SUCCESS) break;
282 status = (*v->post_rtn)(q, Argv, cl, action, actarg);
288 /* see if row already exists */
290 status = validate_row(q, Argv, v);
291 if (status != MR_EXISTS) break;
294 /* build "where" clause and perform update */
295 /* if q->rvar = NULL, perform post_rtn only */
297 build_qual(q->qual, q->argc, Argv, qual);
298 incremental_before(q->rtable, qual, argv_ro);
299 status = do_update(q, &Argv[q->argc], qual, action, actarg);
300 incremental_after(q->rtable, qual, argv_ro);
301 if (status != MR_SUCCESS) break;
302 flush_name(argv_ro[0], q->rtable);
303 table_name = q->rtable;
304 if (strcmp(q->shortname, "sshi") && strcmp(q->shortname, "ssif")) {
305 EXEC SQL UPDATE tblstats
306 SET updates = updates + 1, modtime = 'now'
307 WHERE table_name = :table_name;
311 /* execute followup routine (if any) */
312 if (v->post_rtn) status = (*v->post_rtn)(q, Argv, cl);
317 /* see if row already exists */
319 status = validate_row(q, Argv, v);
320 if (status != MR_NO_MATCH) break;
323 /* build "where" clause if needed */
325 build_qual(q->qual, q->argc, Argv, qual);
331 /* perform the append */
332 /* if q->rvar = NULL, perform post_rtn only */
334 incremental_clear_before();
335 status = do_append(q, &Argv[q->argc], pqual, action, actarg);
336 if (status != MR_SUCCESS) break;
337 if (v && v->object_id) {
338 sprintf(qual, "%s.%s = %s",q->rvar, v->object_id,
339 Argv[q->argc+q->vcnt]);
340 incremental_after(q->rtable, qual, argv_ro);
342 incremental_after(q->rtable, pqual, argv_ro);
344 table_name = q->rtable;
345 EXEC SQL UPDATE tblstats
346 SET appends = appends + 1, modtime = 'now'
347 WHERE table_name = :table_name;
350 /* execute followup routine */
351 if (v->post_rtn) status = (*v->post_rtn)(q, Argv, cl);
355 /* see if row already exists */
357 status = validate_row(q, Argv, v);
358 if (status != MR_EXISTS) break;
361 /* build "where" clause and perform delete */
362 /* if q->rvar = NULL, perform post_rtn only */
364 build_qual(q->qual, q->argc, Argv, qual);
365 table_name = q->rtable;
366 incremental_before(q->rtable, qual, argv_ro);
367 status = do_delete(q, qual, action, actarg);
368 incremental_clear_after();
369 if (status != MR_SUCCESS) break;
370 flush_name(argv_ro[0], q->rtable);
371 EXEC SQL UPDATE tblstats
372 SET deletes = deletes + 1, modtime = 'now'
373 WHERE table_name = :table_name;
376 /* execute followup routine */
377 if (v->post_rtn) status = (*v->post_rtn)(q, Argv, cl);
383 if (status == MR_SUCCESS && ingres_errno != 0) {
384 com_err(whoami, MR_INTERNAL, "Server didn't notice INGRES ERROR %d",
389 if (q->type == RETRIEVE) {
390 EXEC SQL COMMIT WORK;
392 if (status == MR_SUCCESS) {
393 EXEC SQL COMMIT WORK;
399 fprintf(journal, "%% %s %s %s",
400 cl->clname, cl->entity, ctime(&now));
401 fprintf(journal, "%s[%d] ", q->name, cl->args->mr_version_no);
402 for (i = 0; i < argc; i++) {
406 requote(buf, argv_ro[i], sizeof(buf));
412 incremental_update();
415 if (ingres_errno != INGRES_DEADLOCK) {
416 EXEC SQL ROLLBACK WORK;
421 cache_commit(); /* commit following abort is safe */
423 if (status != MR_SUCCESS && log_flags & LOG_RES)
424 com_err(whoami, status, " (Query failed)");
428 build_qual(fmt, argc, argv, qual)
440 for (i = 0; i < argc; i++) {
442 if (c++ == (char *)0) return(MR_ARGS);
446 *(int *)&args[i] = *(int *)argv[i]; /* sigh */
448 return(MR_INGRES_ERR);
450 if (c = index(c, '%')) {
451 args[i] = args[i - 1];
460 sprintf(qual, fmt, args[0]);
464 sprintf(qual, fmt, args[0], args[1]);
468 sprintf(qual, fmt, args[0], args[1], args[2]);
472 sprintf(qual, fmt, args[0], args[1], args[2], args[3]);
476 com_err(whoami, MR_INTERNAL,
477 "Internal arg count error processing query");
485 register struct validate *v;
488 register struct valobj *vo;
497 if (vo->type == V_SORT) {
498 sprintf(elem, "%d", vo->index + 1); /* Result column number */
499 if (*sort) strcat(sort, ", ");
505 return ((*sort) ? sort : 0);
509 /* Build arguement vector, verify query and arguments */
511 mr_verify_query(cl, q, argc, argv_ro)
519 register struct validate *v = q->validate;
521 register int privileged = 0;
522 register char *to,*fr,*stop;
524 /* copy the arguments into a local argv that we can modify */
525 if (argc >= QMAXARGS)
527 for (i = 0; i < argc; i++) {
528 /* Single quotes must be doubled for SQL */
529 for (to=Argv[i], fr=argv_ro[i], stop=to+ARGLEN; (*fr) && (to<stop);) {
535 return(MR_ARG_TOO_LONG);
542 /* check initial query access */
543 status = check_query_access(q, Argv, cl);
544 if (status != MR_SUCCESS && status != MR_PERM)
546 if (status == MR_SUCCESS)
549 /* check argument count */
551 if (q->type == UPDATE || q->type == APPEND) argreq += q->vcnt;
552 if (argc != argreq) return(MR_ARGS);
554 /* validate arguments */
555 if (v && v->valobj) {
556 status = validate_fields(q, Argv, v->valobj, v->objcnt);
557 if (status != MR_SUCCESS) return(status);
560 /* perform special query access check */
561 if (!privileged && v && v->acs_rtn) {
562 status = (*v->acs_rtn)(q, Argv, cl);
563 if (status != MR_SUCCESS && status != MR_PERM)
565 if (status == MR_SUCCESS)
569 return(privileged ? MR_SUCCESS : MR_PERM);
573 /* This routine caches info from the database. Each query acl is stored
574 * in the query structure, and whether that acl contains everybody.
577 check_query_access(q, argv, cl)
582 EXEC SQL BEGIN DECLARE SECTION;
588 EXEC SQL END DECLARE SECTION;
593 /* initialize default uid */
595 EXEC SQL SELECT users_id INTO :def_uid FROM users WHERE login='default';
598 /* get query access control list */
603 EXEC SQL SELECT list_id INTO :acl_id FROM capacls WHERE tag = :name;
604 if (sqlca.sqlcode < 0) return(MR_INGRES_ERR);
605 if (sqlca.sqlcode == 100) return(MR_PERM);
608 /* check for default access */
609 EXEC SQL SELECT member_id INTO :acl_id FROM imembers
610 WHERE list_id = :acl_id AND member_type = 'USER'
611 AND member_id = :def_uid;
612 if (sqlca.sqlerrd[2] == 0)
621 if (get_client(cl, &client_type, &client_id) != MR_SUCCESS)
623 if (find_member("LIST", acl_id, client_type, client_id, 0))
630 get_client(cl, client_type, client_id)
635 if (cl->users_id > 0) {
636 *client_id = cl->users_id;
637 *client_type = "USER";
641 if (cl->client_id < 0) {
642 *client_id = -cl->users_id;
643 *client_type = "KERBEROS";
650 find_member(list_type, list_id, member_type, member_id)
652 EXEC SQL BEGIN DECLARE SECTION;
656 EXEC SQL END DECLARE SECTION;
658 EXEC SQL BEGIN DECLARE SECTION;
660 EXEC SQL END DECLARE SECTION;
662 if (!strcmp(strtrim(list_type), strtrim(member_type)) &&
663 list_id == member_id)
666 /* see if client is a direct member of list */
668 EXEC SQL SELECT member_id INTO :flag FROM imembers
669 WHERE list_id = :list_id AND member_type = :member_type
670 AND member_id = :member_id;
671 if(flag!=0) flag=1; /** Not strictly necessary */
672 if (sqlca.sqlcode == 0)
678 do_retrieve(q, pqual, psort, action, actarg)
679 register struct query *q;
680 EXEC SQL BEGIN DECLARE SECTION;
683 EXEC SQL END DECLARE SECTION;
687 static char **vaddrs = (char **)NULL;
693 if ((vaddrs = (char **)malloc(sizeof(char *) * QMAXARGS)) == NULL) {
694 com_err(whoami, MR_NO_MEM, "setting up static argv");
697 for (i = 0; i < QMAXARGS; i++) {
698 vaddrs[i]=SQLDA->sqlvar[i].sqldata;
702 build_sql_stmt(stmt_buf,"SELECT",q->tlist,vaddrs,pqual);
703 if(psort) { strcat(stmt_buf," ORDER BY "); strcat(stmt_buf,psort); }
704 EXEC SQL PREPARE stmt INTO :SQLDA USING NAMES FROM :stmt_buf;
707 EXEC SQL DECLARE csr001 CURSOR FOR stmt;
708 EXEC SQL OPEN csr001;
711 EXEC SQL FETCH csr001 USING DESCRIPTOR :SQLDA;
712 if(sqlca.sqlcode != 0) break;
713 (*action)(q->vcnt, vaddrs, actarg);
716 EXEC SQL CLOSE csr001;
718 if (mr_errcode) return(mr_errcode);
719 return ((rowcount == 0) ? MR_NO_MATCH : MR_SUCCESS);
722 char *sqlstrstr(str,pat)
726 register char *p=pat;
729 if(*str=='\'') { /* Skip over single-quote delimited substrings */
730 while(*++str && (*str!='\''))
737 while(*++p && (*++s==*p))
739 if(*p) p=pat; /* failed */
741 } while(*p && *++str);
747 void optimize_sql_stmt(buf)
750 char *point=buf, *pat, *eopat, *esc1, *esc2, *csr;
752 for(point=buf; point=sqlstrstr(point,"LIKE"); point++) {
753 /* Now pointing to string "LIKE" */
755 /* Look at next word */
756 for(pat=point+4; *pat==' '; pat++) ;
758 /* Is it a single-quote delimited string? */
759 if(*pat!='\'') continue;
761 /* look for "escape" clause - save escape character */
762 /* 1. Find end of pattern */
763 for(eopat=pat+1; 1; eopat++) {
765 if(eopat[1]=='\'') /* single-quote is self-escaping */
772 /* 2. Look at next word */
773 for(esc1=eopat; *++esc1==' ';) ;
775 /* 3. esc1=0 if not "ESCAPE '?'", where the ? may be any character. */
776 if(strncmp(esc1,"ESCAPE",6)) esc1=NULL;
779 for(esc2=esc1+6; *esc2==' '; esc2++) ;
781 if(*esc2++!='\'') continue; /* Bad SQL syntax. Skip. */
782 /* esc2 now points at the escape character itself */
783 if(esc2[1]!='\'') continue; /* Weird escape string. Skip. */
788 /* Is pattern free from special characters? */
789 for(csr=pat; csr<eopat; csr++)
790 if((*csr=='%') || (*csr=='_') || (*csr==*esc2)) break;
791 if(csr!=eopat) continue; /* Uses pattern matching. Skip. */
793 /* Optimize the query statement */
794 /* 1. Change "LIKE" to " = " */
795 memcpy(point," = ",4);
797 /* 2. Change "ESCAPE" to " " */
800 /* 3. Change "'*'" to " " */
801 /* (Changes '''' to " ") */
802 if(esc2) memset(esc2-1,' ',(*esc2=='\'')?4:3);
807 build_sql_stmt(result_buf,cmd,targetlist,argv,qual)
814 char fmt_buf[MR_STMTBUF_LEN];
815 register char *res, *fmt;
818 sprintf(fmt_buf,"%s %s WHERE %s",cmd,targetlist,qual);
820 sprintf(fmt_buf,"%s %s",cmd,targetlist);
822 for(res=result_buf, fmt=fmt_buf; *fmt; fmt++) {
826 case '%': /* %% -> % */
838 sprintf(res,"%d",*(int *)*argv++); /* print to result buffer */
841 default: /* Swallow other %? pairs */
845 } else *res++ = *fmt; /* text -> result buffer */
849 optimize_sql_stmt(result_buf);
852 do_update(q, argv, qual, action, actarg)
853 register struct query *q;
859 build_sql_stmt(stmt_buf,"UPDATE",q->tlist,argv,qual);
860 EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
861 if (mr_errcode) return(mr_errcode);
865 do_append(q, argv, pqual, action, actarg)
866 register struct query *q;
872 build_sql_stmt(stmt_buf,"INSERT",q->tlist,argv,pqual);
873 EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
874 if (mr_errcode) return(mr_errcode);
878 do_delete(q, qual, action, actarg)
879 register struct query *q;
884 sprintf(stmt_buf,"DELETE FROM %s WHERE %s",q->rtable,qual);
885 EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
886 if (mr_errcode) return(mr_errcode);
892 ** set_next_object_id - set next object id in values table
894 ** Inputs: object - object name in values table and in objects
895 ** table - name of table objects are found in
896 ** limit - should the ID be range limited
898 ** - called before an APPEND operation to set the next object id to
899 ** be used for the new record to the next free value
903 set_next_object_id(object, table_name, limit)
904 EXEC SQL BEGIN DECLARE SECTION;
908 EXEC SQL END DECLARE SECTION;
910 EXEC SQL BEGIN DECLARE SECTION;
912 EXEC SQL END DECLARE SECTION;
915 EXEC SQL SELECT value INTO :value FROM numvalues WHERE name = :object;
916 if (sqlca.sqlerrd[2] != 1)
919 starting_value=value;
921 if (limit && value > MAX_ID_VALUE)
922 value = MIN_ID_VALUE;
924 sprintf(stmt_buf,"SELECT %s FROM %s WHERE %s=%d",object,table_name,object,value);
925 EXEC SQL PREPARE stmt INTO :SQLDA USING NAMES FROM :stmt_buf;
928 EXEC SQL DECLARE csr002 CURSOR FOR stmt;
929 EXEC SQL OPEN csr002;
930 EXEC SQL FETCH csr002 USING DESCRIPTOR :SQLDA;
931 if (sqlca.sqlcode < 0) return(mr_errcode);
932 if (sqlca.sqlcode == 100) break;
934 EXEC SQL CLOSE csr002;
936 if (limit && value == starting_value) {
937 com_err(whoami,0,"All id values have been used");
941 EXEC SQL CLOSE csr002;
944 com_err(whoami, 0, "setting ID %s to %d", object, value);
945 EXEC SQL UPDATE numvalues SET value = :value WHERE name = :object;
950 /* Turn a kerberos name into the user's ID of the account that principal
951 * owns. Sets the kerberos ID and user ID.
954 int set_krb_mapping(name, login, ok, kid, uid)
961 EXEC SQL BEGIN DECLARE SECTION;
964 EXEC SQL END DECLARE SECTION;
970 EXEC SQL SELECT km.users_id, km.string_id INTO :u_id, :k_id
971 FROM krbmap km, strings str
972 WHERE km.string_id = str.string_id AND str.string = :krbname;
973 EXEC SQL COMMIT WORK;
975 if (ingres_errno) return(mr_errcode);
977 if (sqlca.sqlerrd[2] == 1) { /* rowcount */
983 if (name_to_id(name, "STRINGS", &k_id) == MR_SUCCESS)
991 if (name_to_id(login, "USERS", uid) != MR_SUCCESS)
996 if (ingres_errno) return(mr_errcode);
1001 /* For now this just checks the argc's. It should also see that there
1002 * are no duplicate names.
1005 sanity_check_queries()
1008 int maxv = 0, maxa = 0;
1009 #ifdef MULTIPROTOCOLS
1010 extern int QueryCount1, QueryCount2;
1011 extern struct query Queries1[], Queries2[];
1013 extern int QueryCount2;
1014 extern struct query Queries2[];
1015 #endif MULTIPROTOCOLS
1017 #define MAX(x,y) ((x) > (y) ? (x) : (y))
1019 #ifdef MULTIPROTOCOLS
1020 for (i = 0; i < QueryCount1; i++) {
1021 maxv = MAX(maxv, Queries1[i].vcnt);
1022 maxa = MAX(maxa, Queries1[i].argc);
1024 #endif MULTIPROTOCOLS
1025 for (i = 0; i < QueryCount2; i++) {
1026 maxv = MAX(maxv, Queries2[i].vcnt);
1027 maxa = MAX(maxa, Queries2[i].argc);
1029 if (MAX(maxv, maxa) > QMAXARGS) {
1030 com_err(whoami, 0, "A query has more args than QMAXARGS");