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 */
516 mr_verify_query(cl, q, argc, argv_ro)
524 register struct validate *v = q->validate;
526 register char *to,*fr,*stop;
530 /* copy the arguments into a local argv that we can modify */
531 if (argc >= QMAXARGS)
533 for (i = 0; i < argc; i++) {
534 /* Single quotes must be doubled for SQL */
535 for (to=Argv[i], fr=argv_ro[i], stop=to+ARGLEN; (*fr) && (to<stop);) {
541 return(MR_ARG_TOO_LONG);
548 /* check initial query access */
549 status = check_query_access(q, Argv, cl);
550 if (status != MR_SUCCESS && status != MR_PERM)
552 if (status == MR_SUCCESS)
555 /* check argument count */
557 if (q->type == UPDATE || q->type == APPEND) argreq += q->vcnt;
558 if (argc != argreq) return(MR_ARGS);
560 /* validate arguments */
561 if (v && v->valobj) {
562 status = validate_fields(q, Argv, v->valobj, v->objcnt);
563 if (status != MR_SUCCESS) return(status);
566 /* perform special query access check */
567 if (!privileged && v && v->acs_rtn) {
568 status = (*v->acs_rtn)(q, Argv, cl);
569 if (status != MR_SUCCESS && status != MR_PERM)
571 if (status == MR_SUCCESS)
575 return(privileged ? MR_SUCCESS : MR_PERM);
579 /* This routine caches info from the database. Each query acl is stored
580 * in the query structure, and whether that acl contains everybody.
583 check_query_access(q, argv, cl)
588 EXEC SQL BEGIN DECLARE SECTION;
594 EXEC SQL END DECLARE SECTION;
599 /* initialize default uid */
601 EXEC SQL SELECT users_id INTO :def_uid FROM users WHERE login='default';
604 /* get query access control list */
609 EXEC SQL SELECT list_id INTO :acl_id FROM capacls WHERE tag = :name;
610 if (sqlca.sqlcode < 0) return(MR_INGRES_ERR);
611 if (sqlca.sqlcode == 100) return(MR_PERM);
614 /* check for default access */
615 EXEC SQL SELECT member_id INTO :acl_id FROM imembers
616 WHERE list_id = :acl_id AND member_type = 'USER'
617 AND member_id = :def_uid;
618 if (sqlca.sqlerrd[2] == 0)
627 if (get_client(cl, &client_type, &client_id) != MR_SUCCESS)
629 if (find_member("LIST", acl_id, client_type, client_id, 0))
636 get_client(cl, client_type, client_id)
641 if (cl->users_id > 0) {
642 *client_id = cl->users_id;
643 *client_type = "USER";
647 if (cl->client_id < 0) {
648 *client_id = -cl->users_id;
649 *client_type = "KERBEROS";
656 find_member(list_type, list_id, member_type, member_id)
658 EXEC SQL BEGIN DECLARE SECTION;
662 EXEC SQL END DECLARE SECTION;
664 EXEC SQL BEGIN DECLARE SECTION;
666 EXEC SQL END DECLARE SECTION;
668 if (!strcmp(strtrim(list_type), strtrim(member_type)) &&
669 list_id == member_id)
672 /* see if client is a direct member of list */
674 EXEC SQL SELECT member_id INTO :flag FROM imembers
675 WHERE list_id = :list_id AND member_type = :member_type
676 AND member_id = :member_id;
677 if(flag!=0) flag=1; /** Not strictly necessary */
678 if (sqlca.sqlcode == 0)
684 do_retrieve(q, pqual, psort, action, actarg)
685 register struct query *q;
686 EXEC SQL BEGIN DECLARE SECTION;
689 EXEC SQL END DECLARE SECTION;
693 static char **vaddrs = (char **)NULL;
699 if ((vaddrs = (char **)malloc(sizeof(char *) * QMAXARGS)) == NULL) {
700 com_err(whoami, MR_NO_MEM, "setting up static argv");
703 for (i = 0; i < QMAXARGS; i++) {
704 vaddrs[i]=SQLDA->sqlvar[i].sqldata;
708 build_sql_stmt(stmt_buf,"SELECT",q->tlist,vaddrs,pqual);
709 if(psort) { strcat(stmt_buf," ORDER BY "); strcat(stmt_buf,psort); }
710 EXEC SQL PREPARE stmt INTO :SQLDA USING NAMES FROM :stmt_buf;
713 EXEC SQL DECLARE csr001 CURSOR FOR stmt;
714 EXEC SQL OPEN csr001;
717 EXEC SQL FETCH csr001 USING DESCRIPTOR :SQLDA;
718 if(sqlca.sqlcode != 0) break;
719 (*action)(q->vcnt, vaddrs, actarg);
722 EXEC SQL CLOSE csr001;
724 if (mr_errcode) return(mr_errcode);
725 return ((rowcount == 0) ? MR_NO_MATCH : MR_SUCCESS);
728 char *sqlstrstr(str,pat)
732 register char *p=pat;
735 if(*str=='\'') { /* Skip over single-quote delimited substrings */
736 while(*++str && (*str!='\''))
743 while(*++p && (*++s==*p))
745 if(*p) p=pat; /* failed */
747 } while(*p && *++str);
753 void optimize_sql_stmt(buf)
756 char *point=buf, *pat, *eopat, *esc1, *esc2, *csr;
758 for(point=buf; point=sqlstrstr(point,"LIKE"); point++) {
759 /* Now pointing to string "LIKE" */
761 /* Look at next word */
762 for(pat=point+4; *pat==' '; pat++) ;
764 /* Is it a single-quote delimited string? */
765 if(*pat!='\'') continue;
767 /* look for "escape" clause - save escape character */
768 /* 1. Find end of pattern */
769 for(eopat=pat+1; 1; eopat++) {
771 if(eopat[1]=='\'') /* single-quote is self-escaping */
778 /* 2. Look at next word */
779 for(esc1=eopat; *++esc1==' ';) ;
781 /* 3. esc1=0 if not "ESCAPE '?'", where the ? may be any character. */
782 if(strncmp(esc1,"ESCAPE",6)) esc1=NULL;
785 for(esc2=esc1+6; *esc2==' '; esc2++) ;
787 if(*esc2++!='\'') continue; /* Bad SQL syntax. Skip. */
788 /* esc2 now points at the escape character itself */
789 if(esc2[1]!='\'') continue; /* Weird escape string. Skip. */
794 /* Is pattern free from special characters? */
795 for(csr=pat; csr<eopat; csr++)
796 if((*csr=='%') || (*csr=='_') || (*csr==*esc2)) break;
797 if(csr!=eopat) continue; /* Uses pattern matching. Skip. */
799 /* Optimize the query statement */
800 /* 1. Change "LIKE" to " = " */
801 memcpy(point," = ",4);
803 /* 2. Change "ESCAPE" to " " */
806 /* 3. Change "'*'" to " " */
807 /* (Changes '''' to " ") */
808 if(esc2) memset(esc2-1,' ',(*esc2=='\'')?4:3);
813 build_sql_stmt(result_buf,cmd,targetlist,argv,qual)
820 char fmt_buf[MR_STMTBUF_LEN];
821 register char *res, *fmt;
824 sprintf(fmt_buf,"%s %s WHERE %s",cmd,targetlist,qual);
826 sprintf(fmt_buf,"%s %s",cmd,targetlist);
828 for(res=result_buf, fmt=fmt_buf; *fmt; fmt++) {
832 case '%': /* %% -> % */
844 sprintf(res,"%d",*(int *)*argv++); /* print to result buffer */
847 default: /* Swallow other %? pairs */
851 } else *res++ = *fmt; /* text -> result buffer */
855 optimize_sql_stmt(result_buf);
858 do_update(q, argv, qual, action, actarg)
859 register struct query *q;
865 build_sql_stmt(stmt_buf,"UPDATE",q->tlist,argv,qual);
866 EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
867 if (mr_errcode) return(mr_errcode);
871 do_append(q, argv, pqual, action, actarg)
872 register struct query *q;
878 build_sql_stmt(stmt_buf,"INSERT",q->tlist,argv,pqual);
879 EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
880 if (mr_errcode) return(mr_errcode);
884 do_delete(q, qual, action, actarg)
885 register struct query *q;
890 sprintf(stmt_buf,"DELETE FROM %s WHERE %s",q->rtable,qual);
891 EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
892 if (mr_errcode) return(mr_errcode);
898 ** set_next_object_id - set next object id in values table
900 ** Inputs: object - object name in values table and in objects
901 ** table - name of table objects are found in
902 ** limit - should the ID be range limited
904 ** - called before an APPEND operation to set the next object id to
905 ** be used for the new record to the next free value
909 set_next_object_id(object, table_name, limit)
910 EXEC SQL BEGIN DECLARE SECTION;
914 EXEC SQL END DECLARE SECTION;
916 EXEC SQL BEGIN DECLARE SECTION;
918 EXEC SQL END DECLARE SECTION;
921 EXEC SQL SELECT value INTO :value FROM numvalues WHERE name = :object;
922 if (sqlca.sqlerrd[2] != 1)
925 starting_value=value;
927 if (limit && value > MAX_ID_VALUE)
928 value = MIN_ID_VALUE;
930 sprintf(stmt_buf,"SELECT %s FROM %s WHERE %s=%d",object,table_name,object,value);
931 EXEC SQL PREPARE stmt INTO :SQLDA USING NAMES FROM :stmt_buf;
934 EXEC SQL DECLARE csr002 CURSOR FOR stmt;
935 EXEC SQL OPEN csr002;
936 EXEC SQL FETCH csr002 USING DESCRIPTOR :SQLDA;
937 if (sqlca.sqlcode < 0) return(mr_errcode);
938 if (sqlca.sqlcode == 100) break;
940 EXEC SQL CLOSE csr002;
942 if (limit && value == starting_value) {
943 com_err(whoami,0,"All id values have been used");
947 EXEC SQL CLOSE csr002;
950 com_err(whoami, 0, "setting ID %s to %d", object, value);
951 EXEC SQL UPDATE numvalues SET value = :value WHERE name = :object;
956 /* Turn a kerberos name into the user's ID of the account that principal
957 * owns. Sets the kerberos ID and user ID.
960 int set_krb_mapping(name, login, ok, kid, uid)
967 EXEC SQL BEGIN DECLARE SECTION;
970 EXEC SQL END DECLARE SECTION;
976 EXEC SQL SELECT km.users_id, km.string_id INTO :u_id, :k_id
977 FROM krbmap km, strings str
978 WHERE km.string_id = str.string_id AND str.string = :krbname;
979 EXEC SQL COMMIT WORK;
981 if (ingres_errno) return(mr_errcode);
983 if (sqlca.sqlerrd[2] == 1) { /* rowcount */
989 if (name_to_id(name, "STRINGS", &k_id) == MR_SUCCESS)
997 if (name_to_id(login, "USERS", uid) != MR_SUCCESS)
1002 if (ingres_errno) return(mr_errcode);
1007 /* For now this just checks the argc's. It should also see that there
1008 * are no duplicate names.
1011 sanity_check_queries()
1014 int maxv = 0, maxa = 0;
1015 #ifdef MULTIPROTOCOLS
1016 extern int QueryCount1, QueryCount2;
1017 extern struct query Queries1[], Queries2[];
1019 extern int QueryCount2;
1020 extern struct query Queries2[];
1021 #endif MULTIPROTOCOLS
1023 #define MAX(x,y) ((x) > (y) ? (x) : (y))
1025 #ifdef MULTIPROTOCOLS
1026 for (i = 0; i < QueryCount1; i++) {
1027 maxv = MAX(maxv, Queries1[i].vcnt);
1028 maxa = MAX(maxa, Queries1[i].argc);
1030 #endif MULTIPROTOCOLS
1031 for (i = 0; i < QueryCount2; i++) {
1032 maxv = MAX(maxv, Queries2[i].vcnt);
1033 maxa = MAX(maxa, Queries2[i].argc);
1035 if (MAX(maxv, maxa) > QMAXARGS) {
1036 com_err(whoami, 0, "A query has more args than QMAXARGS");