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>
18 #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;
33 extern char *table_name[];
34 extern char *sqlbuffer[QMAXARGS];
38 EXEC SQL BEGIN DECLARE SECTION;
39 int query_timeout = 30;
40 char *database = "moira";
41 EXEC SQL END DECLARE SECTION;
45 int mr_verify_query(client *cl, struct query *q, int argc, char *argv_ro[]);
46 int do_retrieve(struct query *q, char *pqual, int (*action)(), char *actarg);
47 int do_update(struct query *q, char *argv[], char *qual,
48 int (*action)(), char *actarg);
49 int do_append(struct query *q, char *argv[], char *pqual,
50 int (*action)(), char *actarg);
51 int do_delete(struct query *q, char *qual,
52 int (*action)(), char *actarg);
53 char *build_sql_stmt(char *cmd, char *targetlist, char *argv[],
54 int argc, char *qual, char *sort);
56 /* from qvalidate.dc */
57 int validate_fields(struct query *q, char *argv[], struct valobj *vo, int n);
58 int validate_row(struct query *q, char *argv[], struct validate *v);
62 * dbmserr: Called when the DBMS indicates an error.
67 EXEC SQL BEGIN DECLARE SECTION;
69 EXEC SQL END DECLARE SECTION;
70 int bufsize=256, msglength=0;
72 dbms_errno = -sqlca.sqlcode;
73 mr_errcode = MR_DBMS_ERR;
74 com_err(whoami, MR_DBMS_ERR, " code %d\n", dbms_errno);
75 sqlglm(err_msg, &bufsize, &msglength);
77 com_err(whoami, 0, "SQL error text = %s", err_msg);
78 critical_alert("MOIRA", "Moira server encountered DBMS ERROR %d\n%s",
82 /* This is declarative, not executed. Applies from here on, in this file. */
83 EXEC SQL WHENEVER SQLERROR DO dbmserr();
85 int mr_open_database(void)
88 SQLDA *mr_alloc_sqlda();
89 static first_open = 1;
94 /* initialize local argv */
95 for (i = 0; i < 16; i++)
96 Argv[i] = malloc(ARGLEN);
98 mr_sqlda = mr_alloc_sqlda();
107 /* open the database */
108 EXEC SQL CONNECT :database IDENTIFIED BY :database;
113 EXEC SQL SELECT data_length INTO :mr_sig_length FROM user_tab_columns WHERE table_name='USERS' and column_name='SIGNATURE';
114 EXEC SQL COMMIT WORK;
121 void mr_close_database(void)
124 EXEC SQL COMMIT RELEASE;
127 int mr_check_access(cl, name, argc, argv_ro)
129 char *name, *argv_ro[];
137 q = get_query_by_name(name, cl->args->mr_version_no);
138 if (q == (struct query *)0)
139 return(MR_NO_HANDLE);
141 return(mr_verify_query(cl, q, argc, argv_ro));
144 int mr_process_query(cl, name, argc, argv_ro, action, actarg)
146 char *name, *argv_ro[], *actarg;
147 int argc, (*action)();
149 register struct query *q;
151 register struct validate *v;
153 EXEC SQL BEGIN DECLARE SECTION;
155 EXEC SQL END DECLARE SECTION;
156 struct save_queue *sq;
161 /* list queries command */
162 if (!strcmp(name, "_list_queries")) {
163 list_queries(cl->args->mr_version_no, action, actarg);
167 /* help query command */
168 if (!strcmp(name, "_help")) {
171 q = get_query_by_name(argv_ro[0], cl->args->mr_version_no);
172 if (q == (struct query *)0) return(MR_NO_HANDLE);
173 help_query(q, action, actarg);
177 /* get query structure, return error if named query does not exist */
178 q = get_query_by_name(name, cl->args->mr_version_no);
179 if (q == (struct query *)0) return(MR_NO_HANDLE);
182 /* setup argument vector, verify access and arguments */
183 if ((status = mr_verify_query(cl, q, argc, argv_ro)) != MR_SUCCESS)
186 /* perform any special query pre-processing */
187 if (v && v->pre_rtn) {
188 status = (*v->pre_rtn)(q, Argv, cl, 0);
189 if (status != MR_SUCCESS)
195 /* for queries that do not permit wildcarding, check if row
198 status = validate_row(q, Argv, v);
199 if (status != MR_EXISTS) break;
202 /* if there is a followup routine, then we must save the results */
203 /* of the first query for use by the followup routine */
204 /* if q->rvar = NULL, perform post_rtn only */
206 if (q->qual) qual = build_qual(q->qual, q->argc, Argv);
207 if (v && v->post_rtn) {
209 status = do_retrieve(q, qual, sq_save_args, (char *)sq);
210 if (status != MR_SUCCESS) {
214 status = (*v->post_rtn)(q, sq, v, action, actarg, cl);
216 /* normal retrieve */
217 status = do_retrieve(q, qual, action, actarg);
219 if (status != MR_SUCCESS) break;
221 status = (*v->post_rtn)(q, Argv, cl, action, actarg);
227 /* see if row already exists */
229 status = validate_row(q, Argv, v);
230 if (status != MR_EXISTS) break;
233 /* build "where" clause and perform update */
234 /* if q->rvar = NULL, perform post_rtn only */
236 qual = build_qual(q->qual, q->argc, Argv);
237 incremental_before(q->rtable, qual, argv_ro);
238 status = do_update(q, &Argv[q->argc], qual, action, actarg);
239 incremental_after(q->rtable, qual, argv_ro);
240 if (status != MR_SUCCESS) break;
241 flush_name(argv_ro[0], q->rtable);
242 table = table_name[q->rtable];
243 if (strcmp(q->shortname, "sshi") && strcmp(q->shortname, "ssif")) {
244 EXEC SQL UPDATE tblstats
245 SET updates = updates + 1, modtime = SYSDATE
246 WHERE table_name = :table;
250 /* execute followup routine (if any) */
251 if (v->post_rtn) status = (*v->post_rtn)(q, Argv, cl);
256 /* see if row already exists */
258 status = validate_row(q, Argv, v);
259 if (status != MR_NO_MATCH) break;
262 /* perform the append */
263 /* if q->rvar = NULL, perform post_rtn only */
265 if (q->qual) qual = build_qual(q->qual, q->argc, Argv);
266 incremental_clear_before();
267 status = do_append(q, &Argv[q->argc], qual, action, actarg);
268 if (status != MR_SUCCESS) break;
269 if (v && v->object_id) {
270 qual = realloc(qual, 128);
271 sprintf(qual, "%s.%s = %s",q->rvar, v->object_id,
272 Argv[q->argc+q->vcnt]);
273 incremental_after(q->rtable, qual, argv_ro);
275 incremental_after(q->rtable, qual, argv_ro);
277 table = table_name[q->rtable];
278 EXEC SQL UPDATE tblstats
279 SET appends = appends + 1, modtime = SYSDATE
280 WHERE table_name = :table;
283 /* execute followup routine */
284 if (v->post_rtn) status = (*v->post_rtn)(q, Argv, cl);
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 delete */
295 /* if q->rvar = NULL, perform post_rtn only */
297 qual = build_qual(q->qual, q->argc, Argv);
298 table = table_name[q->rtable];
299 incremental_before(q->rtable, qual, argv_ro);
300 status = do_delete(q, qual, action, actarg);
301 incremental_clear_after();
302 if (status != MR_SUCCESS) break;
303 flush_name(argv_ro[0], q->rtable);
304 EXEC SQL UPDATE tblstats
305 SET deletes = deletes + 1, modtime = SYSDATE
306 WHERE table_name = :table;
309 /* execute followup routine */
310 if (v->post_rtn) status = (*v->post_rtn)(q, Argv, cl);
316 if (status == MR_SUCCESS && dbms_errno != 0) {
317 com_err(whoami, MR_INTERNAL, "Server didn't notice DBMS ERROR %d",
322 if (q->type == RETRIEVE) {
323 EXEC SQL COMMIT WORK;
325 if (status == MR_SUCCESS) {
326 EXEC SQL COMMIT WORK;
332 fprintf(journal, "%% %s %s %s",
333 cl->clname, cl->entity, ctime(&now));
334 fprintf(journal, "%s[%d] ", q->name, cl->args->mr_version_no);
335 for (i = 0; i < argc; i++) {
339 requote(buf, argv_ro[i], sizeof(buf));
345 incremental_update();
348 EXEC SQL ROLLBACK WORK;
352 cache_commit(); /* commit following abort is safe */
353 if (qual) free(qual);
355 if (status != MR_SUCCESS && log_flags & LOG_RES)
356 com_err(whoami, status, " (Query failed)");
360 char *build_qual(fmt_buf, argc, argv)
361 char *fmt_buf, *argv[];
364 char *res, *result_buf, *fmt, *arg, *like;
366 result_buf = malloc(2*(strlen(fmt_buf) + argc*ARGLEN));
371 /* Look through the format for LIKE expressions and arguments.
372 Substitute in the arguments, and simplify the `LIKE's to `='s
376 like = strstr(fmt, "LIKE");
377 arg = strchr(fmt, '%');
380 /* only plain text remains */
383 } else if (!like || arg < like) {
384 /* copy to arg, then substitute */
385 strncpy(res, fmt, arg - fmt - 1);
396 if(*p == '\'') *res++ = '\'';
403 res += sprintf(res, "%d", *(int *)*argv++);
408 arg = strchr(fmt, '%');
410 /* copy over up to the arg, then copy and convert the arg */
414 strncpy(res, fmt, arg - fmt - 1);
416 for (p = *argv++; *p; p++) {
418 case '\'': *res++ = '\''; *res++ = '\''; break;
419 case '*': *res++ = '%'; break;
420 case '?': *res++ = '_'; break;
422 case '_': *res++ = '*'; *res++ = *p; escape = 1; break;
423 default: *res++ = *p;
426 if (escape) res += sprintf(res, " ESCAPE '*'");
429 arg = strchr(fmt, '%');
430 like = strstr(fmt, "LIKE");
434 result_buf = realloc(result_buf, strlen(result_buf) + 1);
438 /* Build argument vector, verify query and arguments */
442 int mr_verify_query(cl, q, argc, argv_ro)
450 register struct validate *v = q->validate;
452 register char *to,*fr,*stop;
456 /* check argument count */
458 if (q->type == UPDATE || q->type == APPEND) argreq += q->vcnt;
459 if (argc != argreq) return(MR_ARGS);
461 /* copy the arguments into a local argv that we can modify */
462 for (i = 0; i < argc; i++) {
463 for (to=Argv[i], fr=argv_ro[i], stop=to+ARGLEN; (*fr) && (to<stop);)
467 return(MR_ARG_TOO_LONG);
474 /* check initial query access */
475 status = check_query_access(q, Argv, cl);
476 if (status != MR_SUCCESS && status != MR_PERM)
478 if (status == MR_SUCCESS)
481 /* validate arguments */
482 if (v && v->valobj) {
483 status = validate_fields(q, Argv, v->valobj, v->objcnt);
484 if (status != MR_SUCCESS) return(status);
487 /* perform special query access check */
488 if (!privileged && v && v->acs_rtn) {
489 status = (*v->acs_rtn)(q, Argv, cl);
490 if (status != MR_SUCCESS && status != MR_PERM)
492 if (status == MR_SUCCESS)
496 return(privileged ? MR_SUCCESS : MR_PERM);
500 /* This routine caches info from the database. Each query acl is stored
501 * in the query structure, and whether that acl contains everybody.
504 int check_query_access(q, argv, cl)
509 EXEC SQL BEGIN DECLARE SECTION;
513 EXEC SQL END DECLARE SECTION;
515 /* initialize default uid */
517 EXEC SQL SELECT users_id INTO :def_uid FROM users WHERE login='default';
520 /* get query access control list */
525 EXEC SQL SELECT list_id INTO :acl_id FROM capacls WHERE tag = :name;
526 if (sqlca.sqlcode < 0) return(MR_DBMS_ERR);
527 if (sqlca.sqlcode == SQL_NO_MATCH) return(MR_PERM);
530 /* check for default access */
531 EXEC SQL SELECT member_id INTO :acl_id FROM imembers
532 WHERE list_id = :acl_id AND member_type = 'USER'
533 AND member_id = :def_uid;
534 if (sqlca.sqlerrd[2] == 0)
543 if (find_member("LIST", acl_id, cl))
550 int find_member(list_type, list_id, cl)
555 EXEC SQL BEGIN DECLARE SECTION;
556 int flag, users_id, client_id;
557 EXEC SQL END DECLARE SECTION;
559 if (!strcmp(strtrim(list_type), "USER") &&
560 list_id == cl->users_id)
563 if (!strcmp(strtrim(list_type), "KERBEROS") &&
564 list_id == -cl->client_id)
567 /* see if client is a member of list */
569 users_id = cl->users_id;
570 client_id = -cl->client_id;
571 EXEC SQL SELECT COUNT(member_id) INTO :flag FROM imembers
572 WHERE list_id = :list_id
573 AND ( ( member_type = 'USER' AND member_id = :users_id )
574 OR (member_type = 'KERBEROS' AND member_id = :client_id ) );
575 if (sqlca.sqlcode == 0)
581 int do_retrieve(q, pqual, action, actarg)
583 char *pqual, *actarg;
589 stmt = build_sql_stmt("SELECT",q->tlist,NULL,0,pqual,q->sort);
590 status = do_for_all_rows(stmt_buf, q->vcnt, action, (int)actarg);
595 char *build_sql_stmt(cmd, targetlist, argv, argc, qual, sort)
596 char *cmd, *targetlist, *argv[], *qual, *sort;
601 register char *res, *fmt;
603 len = strlen(cmd) + strlen(targetlist) + argc*ARGLEN + 3;
604 if (qual) len += strlen(qual) + 6;
605 if (sort) len += strlen(sort) + 10;
606 result_buf = malloc(len);
608 sprintf(result_buf, "%s ", cmd);
610 for(res=strchr(result_buf, '\0'), fmt=targetlist; *fmt; fmt++) {
621 if(*p=='\'') *res++='\'';
628 res+=sprintf(res,"%d",*(int *)*argv++);
634 } else *res++ = *fmt;
639 res += sprintf(res, " WHERE %s", qual);
642 res += sprintf(res, " ORDER BY %s", sort);
644 result_buf = realloc(result_buf, strlen(result_buf));
649 int do_update(q, argv, qual, action, actarg)
651 char *argv[], *qual, *actarg;
654 EXEC SQL BEGIN DECLARE SECTION;
656 EXEC SQL END DECLARE SECTION;
658 stmt = build_sql_stmt("UPDATE",q->tlist,argv,q->vcnt,qual,NULL);
659 EXEC SQL EXECUTE IMMEDIATE :stmt;
661 if (mr_errcode) return(mr_errcode);
665 int do_append(q, argv, pqual, action, actarg)
667 char *argv[], *pqual, *actarg;
670 EXEC SQL BEGIN DECLARE SECTION;
672 EXEC SQL END DECLARE SECTION;
674 stmt = build_sql_stmt("INSERT",q->tlist,argv,q->vcnt,pqual,NULL);
675 EXEC SQL EXECUTE IMMEDIATE :stmt;
677 if (mr_errcode) return(mr_errcode);
681 int do_delete(q, qual, action, actarg)
686 sprintf(stmt_buf,"DELETE FROM %s WHERE %s",table_name[q->rtable],qual);
687 EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
688 if (mr_errcode) return(mr_errcode);
694 ** set_next_object_id - set next object id in values table
696 ** Inputs: object - object name in values table and in objects
697 ** table - name of table objects are found in
698 ** limit - should the ID be range limited
700 ** - called before an APPEND operation to set the next object id to
701 ** be used for the new record to the next free value
705 int set_next_object_id(object, table, limit)
706 EXEC SQL BEGIN DECLARE SECTION;
708 EXEC SQL END DECLARE SECTION;
712 EXEC SQL BEGIN DECLARE SECTION;
714 EXEC SQL END DECLARE SECTION;
717 EXEC SQL SELECT value INTO :value FROM numvalues WHERE name = :object;
718 if (sqlca.sqlerrd[2] != 1)
721 starting_value=value;
723 if (limit && value > MAX_ID_VALUE)
724 value = MIN_ID_VALUE;
726 sprintf(stmt_buf,"SELECT %s FROM %s WHERE %s=%d",
727 object,table_name[table],object,value);
729 if (sqlca.sqlcode < 0) return(mr_errcode);
730 if (sqlca.sqlcode == SQL_NO_MATCH) break;
733 if (limit && value == starting_value) {
734 com_err(whoami,0,"All id values have been used");
740 com_err(whoami, 0, "setting ID %s to %d", object, value);
741 EXEC SQL UPDATE numvalues SET value = :value WHERE name = :object;
746 /* Turn a kerberos name into the user's ID of the account that principal
747 * owns. Sets the kerberos ID and user ID.
750 int set_krb_mapping(name, login, ok, kid, uid)
754 EXEC SQL BEGIN DECLARE SECTION;
757 EXEC SQL END DECLARE SECTION;
763 EXEC SQL SELECT km.users_id, km.string_id INTO :u_id, :k_id
764 FROM krbmap km, strings str
765 WHERE km.string_id = str.string_id AND str.string = :krbname;
766 EXEC SQL COMMIT WORK;
768 if (dbms_errno) return(mr_errcode);
770 if (sqlca.sqlerrd[2] == 1) { /* rowcount */
776 if (name_to_id(name, STRINGS_TABLE, &k_id) == MR_SUCCESS)
784 if (name_to_id(login, USERS_TABLE, uid) != MR_SUCCESS)
789 if (dbms_errno) return(mr_errcode);
794 /* For now this just checks the argc's. It should also see that there
795 * are no duplicate names.
798 void sanity_check_queries(void)
801 int maxv = 0, maxa = 0;
802 extern int QueryCount2;
803 extern struct query Queries2[];
805 #define MAX(x,y) ((x) > (y) ? (x) : (y))
807 for (i = 0; i < QueryCount2; i++) {
808 maxv = MAX(maxv, Queries2[i].vcnt);
809 maxa = MAX(maxa, Queries2[i].argc);
811 if (MAX(maxv, maxa) > QMAXARGS) {
812 com_err(whoami, 0, "A query has more args than QMAXARGS");
818 /* Generically do a SELECT, storing the results in the provided buffers */
823 int i, errcode=0, errlen;
825 EXEC SQL PREPARE inc_stmt FROM :stmt_buf;
826 if(sqlca.sqlcode) return;
827 EXEC SQL DECLARE inc_crs CURSOR FOR inc_stmt;
828 EXEC SQL OPEN inc_crs;
829 mr_sqlda->N = QMAXARGS;
830 EXEC SQL DESCRIBE SELECT LIST FOR inc_stmt INTO mr_sqlda;
831 mr_sqlda->N = mr_sqlda->F;
832 for(i=0; i<mr_sqlda->N; i++) {
833 mr_sqlda->V[i]=buffers[i];
835 mr_sqlda->L[i]=ARGLEN;
837 EXEC SQL FETCH inc_crs USING DESCRIPTOR mr_sqlda;
839 /* if we got an error from the FETCH, we have to preserve it or the
840 close will reset it and the caller will think nothing happened */
842 errcode=sqlca.sqlcode;
843 errlen=sqlca.sqlerrm.sqlerrml;
846 EXEC SQL CLOSE inc_crs;
848 sqlca.sqlcode=errcode;
849 sqlca.sqlerrm.sqlerrml=errlen;
853 int do_for_all_rows(query, count, action, actarg)
854 EXEC SQL BEGIN DECLARE SECTION;
856 EXEC SQL END DECLARE SECTION;
857 int count, (*action)(), actarg;
861 EXEC SQL PREPARE stmt FROM :query;
862 if(sqlca.sqlcode) return;
863 EXEC SQL DECLARE curs CURSOR FOR stmt;
866 EXEC SQL DESCRIBE SELECT LIST FOR stmt INTO mr_sqlda;
867 mr_sqlda->N = mr_sqlda->F;
868 for(i=0; i<mr_sqlda->N; i++) {
869 mr_sqlda->V[i]=sqlbuffer[i];
871 mr_sqlda->L[i]=ARGLEN;
875 EXEC SQL FETCH curs USING DESCRIPTOR mr_sqlda;
876 if(sqlca.sqlcode != 0) break;
877 (*action)(count, sqlbuffer, actarg);
882 if (mr_errcode) return(mr_errcode);
883 return ((rowcount == 0) ? MR_NO_MATCH : MR_SUCCESS);