コード例 #1
0
ファイル: server.c プロジェクト: jsankararaman/p2p
int main()
{
    int listenfd = create_server(2000), connfd, i, pid, ret;
    char line[1000];
    pthread_t tid;
    struct request *r; 

    for (; ;) {
        if ((connfd = accept(listenfd, (struct sockaddr *)NULL, NULL))<0) {
            perror("accept error : ");
            return -1;
        }
        getline(line, connfd);
        if ((ret = validate_request(line, connfd))>0) {
	    r = (struct request *)malloc(sizeof(struct request));
            r->request_t = ret;
            strcpy(r->req, line);
	    r->connfd = connfd;
	    printf("creating thread\n");
            ret = pthread_create(&tid, NULL, handle_request, (void *)r);
	}
        else {
	    close(connfd);
	}
    }
    close(listenfd);
    return 0;
}
コード例 #2
0
static int __handle_jool_message(struct genl_info *info)
{
	struct xlator translator;
	bool client_is_jool;
	int error;

	log_debug("===============================================");
	log_debug("Received a request from userspace.");

	error = validate_request(nla_data(info->attrs[ATTR_DATA]),
			nla_len(info->attrs[ATTR_DATA]),
			"userspace client",
			"kernel module",
			&client_is_jool);
	if (error)
		return client_is_jool ? nlcore_respond(info, error) : error;

	if (be16_to_cpu(get_jool_hdr(info)->mode) == MODE_INSTANCE)
		return handle_instance_request(info);

	error = xlator_find_current(&translator);
	if (error == -ESRCH) {
		log_err("This namespace lacks a Jool instance.");
		return nlcore_respond(info, -ESRCH);
	}
	if (error) {
		log_err("Unknown error %d; Jool instance not found.", error);
		return nlcore_respond(info, error);
	}

	error = multiplex_request(&translator, info);
	xlator_put(&translator);
	return error;
}
コード例 #3
0
ファイル: HttpHandler.cpp プロジェクト: debdipta/tista
const char* HttpHandler::get_response(const char* request)
{
    char* response = new char[2048];

    time_t t = time(NULL);
    struct tm tm = *localtime(&t);
    if(validate_request(request))   {
        strcat(response, default_response_header_OK);
        strcat(response, default_new_line);
        sprintf(test_html, "<html><body><h1>It works!now: %d-%d-%d %d:%d:%d\n</h1></body></html>", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
        strcat(response, test_html);
    }
    printf("Responding: %s\n", response);
    return response;
}
コード例 #4
0
map_handler::map_handler(request &req) : bounds(validate_request(req)) {}
コード例 #5
0
ファイル: protocol.c プロジェクト: libguestfs/nbdkit
int
protocol_recv_request_send_reply (struct connection *conn)
{
  int r;
  struct request request;
  uint16_t cmd, flags;
  uint32_t magic, count, error = 0;
  uint64_t offset;
  char *buf = NULL;
  CLEANUP_EXTENTS_FREE struct nbdkit_extents *extents = NULL;

  /* Read the request packet. */
  {
    ACQUIRE_LOCK_FOR_CURRENT_SCOPE (&conn->read_lock);
    r = connection_get_status (conn);
    if (r <= 0)
      return r;
    r = conn->recv (conn, &request, sizeof request);
    if (r == -1) {
      nbdkit_error ("read request: %m");
      return connection_set_status (conn, -1);
    }
    if (r == 0) {
      debug ("client closed input socket, closing connection");
      return connection_set_status (conn, 0); /* disconnect */
    }

    magic = be32toh (request.magic);
    if (magic != NBD_REQUEST_MAGIC) {
      nbdkit_error ("invalid request: 'magic' field is incorrect (0x%x)",
                    magic);
      return connection_set_status (conn, -1);
    }

    flags = be16toh (request.flags);
    cmd = be16toh (request.type);

    offset = be64toh (request.offset);
    count = be32toh (request.count);

    if (cmd == NBD_CMD_DISC) {
      debug ("client sent %s, closing connection", name_of_nbd_cmd (cmd));
      return connection_set_status (conn, 0); /* disconnect */
    }

    /* Validate the request. */
    if (!validate_request (conn, cmd, flags, offset, count, &error)) {
      if (cmd == NBD_CMD_WRITE &&
          skip_over_write_buffer (conn->sockin, count) < 0)
        return connection_set_status (conn, -1);
      goto send_reply;
    }

    /* Get the data buffer used for either read or write requests.
     * This is a common per-thread data buffer, it must not be freed.
     */
    if (cmd == NBD_CMD_READ || cmd == NBD_CMD_WRITE) {
      buf = threadlocal_buffer ((size_t) count);
      if (buf == NULL) {
        error = ENOMEM;
        if (cmd == NBD_CMD_WRITE &&
            skip_over_write_buffer (conn->sockin, count) < 0)
          return connection_set_status (conn, -1);
        goto send_reply;
      }
    }

    /* Allocate the extents list for block status only. */
    if (cmd == NBD_CMD_BLOCK_STATUS) {
      extents = nbdkit_extents_new (offset, conn->exportsize);
      if (extents == NULL) {
        error = ENOMEM;
        goto send_reply;
      }
    }

    /* Receive the write data buffer. */
    if (cmd == NBD_CMD_WRITE) {
      r = conn->recv (conn, buf, count);
      if (r == 0) {
        errno = EBADMSG;
        r = -1;
      }
      if (r == -1) {
        nbdkit_error ("read data: %s: %m", name_of_nbd_cmd (cmd));
        return connection_set_status (conn, -1);
      }
    }
  }

  /* Perform the request.  Only this part happens inside the request lock. */
  if (quit || !connection_get_status (conn)) {
    error = ESHUTDOWN;
  }
  else {
    lock_request (conn);
    error = handle_request (conn, cmd, flags, offset, count, buf, extents);
    assert ((int) error >= 0);
    unlock_request (conn);
  }

  /* Send the reply packet. */
 send_reply:
  if (connection_get_status (conn) < 0)
    return -1;

  if (error != 0) {
    /* Since we're about to send only the limited NBD_E* errno to the
     * client, don't lose the information about what really happened
     * on the server side.  Make sure there is a way for the operator
     * to retrieve the real error.
     */
    debug ("sending error reply: %s", strerror (error));
  }

  /* Currently we prefer to send simple replies for everything except
   * where we have to (ie. NBD_CMD_READ and NBD_CMD_BLOCK_STATUS when
   * structured_replies have been negotiated).  However this prevents
   * us from sending human-readable error messages to the client, so
   * we should reconsider this in future.
   */
  if (conn->structured_replies &&
      (cmd == NBD_CMD_READ || cmd == NBD_CMD_BLOCK_STATUS)) {
    if (!error) {
      if (cmd == NBD_CMD_READ)
        return send_structured_reply_read (conn, request.handle, cmd,
                                           buf, count, offset);
      else /* NBD_CMD_BLOCK_STATUS */
        return send_structured_reply_block_status (conn, request.handle,
                                                   cmd, flags,
                                                   count, offset,
                                                   extents);
    }
    else
      return send_structured_reply_error (conn, request.handle, cmd, flags,
                                          error);
  }
  else
    return send_simple_reply (conn, request.handle, cmd, buf, count, error);
}
コード例 #6
0
ファイル: disp1.c プロジェクト: AlainODea/illumos-gate
static int
mv_file(RSTATUS *rp, char *dest)
{
	int	stat;
	char	*olddest;
	EXEC	*oldexec;
	SECURE * securep;
	RSTATUS * prs;
	char *reqno;

	oldexec = rp->printer->exec;
	olddest = rp->request->destination;
	rp->request->destination = Strdup(dest);
	if ((stat = validate_request(rp, (char **)0, 1)) == MOK) {
		Free(olddest);

		if (rp->request->outcome & RS_FILTERED) {
			int cnt = 0;
			char *reqno;
			char **listp;
			char tmp_nam[MAXPATHLEN];

			reqno = getreqno(rp->secure->req_id);
			for (listp = rp->request->file_list; *listp; listp++) {
				cnt++;
				snprintf(tmp_nam, sizeof (tmp_nam),
				    "%s/F%s-%d", Lp_Temp, reqno, cnt);
				unlink(tmp_nam);

			}
			rp->request->outcome &= ~RS_FILTERED;
		}

		/* update /var/spool/lp/tmp/<host>/nnn-0 */
		if (putrequest(rp->req_file, rp->request) < 0) {
			note("putrequest failed\n");
			return (MNOMEM);
		}

		/* update /var/spool/lp/requests/<host>/nnn-0 */
		if ((securep = Getsecure(rp->req_file))) {
			reqno = strdup(getreqno(securep->req_id));
			(void) free(securep->req_id);
			if ((securep->req_id = calloc(strlen(dest) + 1 +
			    strlen(reqno) +1, sizeof (char))) == NULL)
				return (MNOMEM);
			(void) sprintf(securep->req_id, "%s-%s", dest, reqno);
			/* remove the old request file; save new one */
			(void) rmsecure(rp->secure->req_id);
			if (Putsecure(rp->req_file, securep) < 0) {
				/* Putsecure includes note/errmessage */
				return (MNOMEM);
			}
		} else {
			note("Getsecure failed\n");
			return (MNOMEM);
		}

		/* update internal jobs list: Request_list */
		if (prs = request_by_id(rp->secure->req_id)) {
			free(prs->secure->req_id);
			prs->secure->req_id = strdup(securep->req_id);

			/*
			 * We calloc'd securep->reqid earlier, now we free it
			 * here because we no longer call 'freesecure' from
			 * Putsecure() if we use a static structure
			 */

			free(securep->req_id);
		} else {
			note("request_by_id failed\n");
			return (MUNKNOWN);
		}

		/*
		 * If the request was being filtered or was printing,
		 * it would have been stopped in "validate_request()",
		 * but only if it has to be refiltered. Thus, the
		 * filtering has been stopped if it has to be stopped,
		 * but the printing may still be going.
		 */
		if (rp->request->outcome & RS_PRINTING &&
		    !(rp->request->outcome & RS_STOPPED)) {
			rp->request->outcome |= RS_STOPPED;
			terminate(oldexec);
		}

		maybe_schedule(rp);
		return (MOK);
	}

	Free(rp->request->destination);
	rp->request->destination = olddest;
	return (stat);
}
コード例 #7
0
ファイル: disp1.c プロジェクト: AlainODea/illumos-gate
void
s_print_request(char *m, MESG *md)
{
	extern char		*Local_System;
	char			*file;
	char			*idno;
	char			*path;
	char			*req_file;
	char			*req_id	= 0;
	RSTATUS			*rp;
	REQUEST			*r;
	SECURE			*s;
	struct passwd		*pw;
	short			err;
	short			status;
	off_t			size;
	uid_t			org_uid;
	gid_t			org_gid;
#ifdef LP_USE_PAPI_ATTR
	struct stat		tmpBuf;
	char 			tmpName[BUFSIZ];
#endif


	(void) getmessage(m, S_PRINT_REQUEST, &file);
	syslog(LOG_DEBUG, "s_print_request(%s)", (file ? file : "NULL"));

	/*
	 * "NewRequest" points to a request that's not yet in the
	 * request list but is to be considered with the rest of the
	 * requests (e.g. calculating # of requests awaiting a form).
	 */
	if ((rp = NewRequest = new_rstatus(NULL, NULL)) == NULL)
		status = MNOMEM;

	else
	{
		req_file = reqpath(file, &idno);
		path = makepath(Lp_Tmp, req_file, (char *)0);
		(void) chownmod(path, Lp_Uid, Lp_Gid, 0644);
		Free(path);

		if (!(r = Getrequest(req_file)))
			status = MNOOPEN;

		else
		{
			rp->req_file = Strdup(req_file);

			freerequest(rp->request);
			rp->request = r;

			rp->request->outcome = 0;
			rp->secure->uid = md->uid;
			rp->secure->gid = md->gid;
			if (md->slabel != NULL)
				rp->secure->slabel = Strdup(md->slabel);

			pw = getpwuid(md->uid);
			endpwent();
			if (pw && pw->pw_name && *pw->pw_name)
				rp->secure->user = Strdup(pw->pw_name);
			else {
				rp->secure->user = Strdup(BIGGEST_NUMBER_S);
				(void) sprintf(rp->secure->user, "%u",
				    md->uid);
			}

			if ((rp->request->actions & ACT_SPECIAL) == ACT_HOLD)
				rp->request->outcome |= RS_HELD;
			if ((rp->request->actions & ACT_SPECIAL) == ACT_RESUME)
				rp->request->outcome &= ~RS_HELD;
			if ((rp->request->actions & ACT_SPECIAL) ==
			    ACT_IMMEDIATE) {
				if (!md->admin) {
					status = MNOPERM;
					goto Return;
				}
				rp->request->outcome |= RS_IMMEDIATE;
			}

			size = chfiles(rp->request->file_list, Lp_Uid, Lp_Gid);

			if (size < 0) {
				/*
				 * at this point, chfiles() may have
				 * failed because the file may live on
				 * an NFS mounted filesystem, under
				 * a directory of mode 700. such a
				 * directory isn't accessible even by
				 * root, according to the NFS protocol
				 * (i.e. the Stat() in chfiles() failed).
				 * this most commonly happens via the
				 * automounter, and rlogin. thus we
				 * change our euid/egid to that of the
				 * user, and try again. if *this* fails,
				 * then the file must really be
				 * inaccessible.
				 */
				org_uid = geteuid();
				org_gid = getegid();

				if (setegid(md->gid) != 0) {
					status = MUNKNOWN;
					goto Return;
				}

				if (seteuid(md->uid) != 0) {
					setgid(org_gid);
					status = MUNKNOWN;
					goto Return;
				}

				size = chfiles(rp->request->file_list,
				    Lp_Uid, Lp_Gid);

				if (seteuid(org_uid) != 0) {
					/* should never happen */
					note("s_print_request(): ");
					note("seteuid back to uid=%d "
					    "failed!!\n", org_uid);
					size = -1;
				}

				if (setegid(org_gid) != 0) {
					/* should never happen */
					note("s_print_request(): ");
					note("setegid back to uid=%d "
					    "failed!!\n", org_uid);
					size = -1;
				}

				if (size < 0) {
					status = MUNKNOWN;
					goto Return;
				}
			}
			if (!(rp->request->outcome & RS_HELD) && size == 0) {
				status = MNOPERM;
				goto Return;
			}
			rp->secure->size = size;

			(void) time(&rp->secure->date);
			rp->secure->req_id = NULL;

			if (!rp->request->title) {
				if (strlen(*rp->request->file_list) <
				    (size_t)24)
					rp->request->title =
					    Strdup(*rp->request->file_list);
				else {
					char *r;
					if (r = strrchr(
					    *rp->request->file_list, '/'))
						r++;
					else
						r = *rp->request->file_list;

					rp->request->title = malloc(25);
					sprintf(rp->request->title,
					    "%-.24s", r);
				}
			}

			if ((err = validate_request(rp, &req_id, 0)) != MOK)
				status = err;
			else {
				/*
				 * "req_id" will be supplied if this is from a
				 * remote system.
				 */
				if (rp->secure->req_id == NULL) {
					req_id = makestr(req_id, "-",
					    idno, (char *)0);
					rp->secure->req_id = req_id;
				} else
					req_id = rp->secure->req_id;

#ifdef LP_USE_PAPI_ATTR
				/*
				 * Check if the PAPI job attribute file
				 * exists, if it does change the
				 * permissions and ownership of the file.
				 * This file is created when print jobs
				 * are submitted via the PAPI interface,
				 * the file pathname of this file is
				 * passed to the slow-filters and printer
				 * interface script as an environment
				 * variable when they are executed
				 */
				snprintf(tmpName, sizeof (tmpName),
				    "%s-%s", idno, LP_PAPIATTRNAME);
				path = makepath(Lp_Temp, tmpName, (char *)0);

				if (stat(path, &tmpBuf) == 0) {
					syslog(LOG_DEBUG,
					    "s_print_request: "\
					    "attribute file ='%s'", path);

					/*
					 * IPP job attribute file exists
					 * for this job so change
					 * permissions and ownership of
					 * the file
					 */
					(void) chownmod(path, Lp_Uid,
					    Lp_Gid, 0644);
					Free(path);
				}
				else
				{
					syslog(LOG_DEBUG,
					    "s_print_request: "\
					    "no attribute file");
				}
#endif

				/*
				 * fix for bugid 1103890.
				 * use Putsecure instead.
				 */
				if ((Putsecure(req_file, rp->secure) == -1) ||
				    (putrequest(req_file, rp->request) == -1))
					status = MNOMEM;
				else
				{
					status = MOK;

					insertr(rp);
					NewRequest = 0;

					if (rp->slow)
						schedule(EV_SLOWF, rp);
					else
						schedule(EV_INTERF,
						    rp->printer);

					del_flt_act(md, FLT_FILES);
				}
			}
		}
	}

Return:
	NewRequest = 0;
	Free(req_file);
	Free(idno);
	if (status != MOK && rp) {
		rmfiles(rp, 0);
		free_rstatus(rp);
	}
	mputm(md, R_PRINT_REQUEST, status, NB(req_id), chkprinter_result);
}
コード例 #8
0
ファイル: disp1.c プロジェクト: AlainODea/illumos-gate
void
s_end_change_request(char *m, MESG *md)
{
	char		*req_id;
	RSTATUS		*rp;
	off_t		size;
	off_t		osize;
	short		err;
	short		status;
	REQUEST		*r = 0;
	REQUEST		oldr;
	int		call_schedule = 0;
	int		move_ok	= 0;
	char		*path;
	char		tmpName[BUFSIZ];
	struct stat	tmpBuf;

	(void) getmessage(m, S_END_CHANGE_REQUEST, &req_id);
	syslog(LOG_DEBUG, "s_end_change_request(%s)",
	    (req_id ? req_id : "NULL"));

	if (!(rp = request_by_id(req_id)))
		status = MUNKNOWN;
	else if ((md->admin == 0) && (is_system_labeled()) &&
	    (md->slabel != NULL) && (rp->secure->slabel != NULL) &&
	    (!STREQU(md->slabel, rp->secure->slabel)))
		status = MUNKNOWN;
	else if (!(rp->request->outcome & RS_CHANGING))
		status = MNOSTART;
	else {
		path = makepath(Lp_Tmp, rp->req_file, (char *)0);
		(void) chownmod(path, Lp_Uid, Lp_Gid, 0644);
		Free(path);

#ifdef LP_USE_PAPI_ATTR

		/*
		 * Check if the PAPI job attribute file exists,
		 * if it does change the permission and the ownership
		 * of the file to be "Lp_Uid".
		 */

		snprintf(tmpName, sizeof (tmpName),
		    "%s-%s", strtok(strdup(rp->req_file), "-"),
		    LP_PAPIATTRNAME);

		path = makepath(Lp_Tmp, tmpName, (char *)0);

		if (stat(path, &tmpBuf) == 0) {
			syslog(LOG_DEBUG,
			    "s_end_change_request: attribute file ='%s'",
			    path);

			/*
			 * IPP job attribute file exists for this job so
			 * change permissions and ownership of the file
			 */
			(void) chownmod(path, Lp_Uid, Lp_Gid, 0644);
			Free(path);
		}
		else
		{
			syslog(LOG_DEBUG,
			    "s_end_change_request: no attribute file");
		}
#endif
		rp->request->outcome &= ~(RS_CHANGING);
		del_flt_act(md, FLT_CHANGE);
		/*
		 * The RS_CHANGING bit may have been the only thing
		 * preventing this request from filtering or printing,
		 * so regardless of what happens below,
		 * we must check to see if the request can proceed.
		 */
		call_schedule = 1;

		if (!(r = Getrequest(rp->req_file)))
			status = MNOOPEN;
		else {
			oldr = *(rp->request);
			*(rp->request) = *r;

			move_ok =
			    STREQU(oldr.destination, r->destination);

			/*
			 * Preserve the current request status!
			 */
			rp->request->outcome = oldr.outcome;

			/*
			 * Here's an example of the dangers one meets
			 * when public flags are used for private
			 * purposes. ".actions" (indeed, anything in the
			 * REQUEST structure) is set by the person
			 * changing the job. However, lpsched uses
			 * ".actions" as place to indicate that a job
			 * came from a remote system and we must send
			 * back job completion--this is a strictly
			 * private flag that we must preserve.
			 */
			rp->request->actions |=
			    (oldr.actions & ACT_NOTIFY);

			if ((rp->request->actions & ACT_SPECIAL) ==
			    ACT_HOLD) {
				rp->request->outcome |= RS_HELD;
				/*
				 * To be here means either the user owns
				 * the request or he or she is the
				 * administrator. Since we don't want to
				 * set the RS_ADMINHELD flag if the user
				 * is the administrator, the following
				 * compare will work.
				 */
				if (md->uid != rp->secure->uid)
					rp->request->outcome |=
					    RS_ADMINHELD;
			}

			if ((rp->request->actions & ACT_SPECIAL) ==
			    ACT_RESUME) {
				if ((rp->request->outcome & RS_ADMINHELD) &&
				    !md->admin) {
					status = MNOPERM;
					goto Return;
				}
				rp->request->outcome &=
				    ~(RS_ADMINHELD|RS_HELD);
			}

			if ((rp->request->actions & ACT_SPECIAL)
			    == ACT_IMMEDIATE) {
				if (!md->admin) {
					status = MNOPERM;
					goto Return;
				}
				rp->request->outcome |= RS_IMMEDIATE;
			}

			size = chfiles(rp->request->file_list, Lp_Uid,
			    Lp_Gid);
			if (size < 0) {
				status = MUNKNOWN;
				goto Return;
			}
			if (!(rp->request->outcome & RS_HELD) &&
			    size == 0) {
				status = MNOPERM;
				goto Return;
			}

			osize = rp->secure->size;
			rp->secure->size = size;

			if (move_ok == 0) {
				char *dest = strdup(r->destination);
				if ((status = mv_file(rp, dest)) == MOK)
					rp->secure->size = osize;
				free(dest);
			} else if ((err = validate_request(rp, (char **)0,
			    move_ok)) != MOK) {
				status = err;
				rp->secure->size = osize;
			} else {
				status = MOK;

				if ((rp->request->outcome & RS_IMMEDIATE) ||
				    (rp->request->priority != oldr.priority)) {
					remover(rp);
					insertr(rp);
				}

				freerequest(&oldr);
				(void) putrequest(rp->req_file, rp->request);
				/*
				 * fix for bugid 1103890.
				 * use Putsecure instead.
				 */
				(void) Putsecure(rp->req_file, rp->secure);
			}
		}
	}

Return:
	if (status != MOK && rp) {
		if (r) {
			freerequest(r);
			*(rp->request) = oldr;
		}
		if (status != MNOSTART)
			(void) putrequest(rp->req_file, rp->request);
	}

	if (call_schedule)
		maybe_schedule(rp);

	mputm(md, R_END_CHANGE_REQUEST, status, chkprinter_result);
}
コード例 #9
0
ファイル: nrpe.c プロジェクト: Honwhy/icinga-nrpe-ipv6
/* handles a client connection */
void handle_connection(int sock){
        u_int32_t calculated_crc32;
	command *temp_command;
	packet receive_packet;
	packet send_packet;
	int bytes_to_send;
	int bytes_to_recv;
	char buffer[MAX_INPUT_BUFFER];
	char raw_command[MAX_INPUT_BUFFER];
	char processed_command[MAX_INPUT_BUFFER];
	int result=STATE_OK;
	int early_timeout=FALSE;
	int rc;
	int x;
#ifdef DEBUG
	FILE *errfp;
#endif
#ifdef HAVE_SSL
	SSL *ssl=NULL;
#endif


	/* log info to syslog facility */
	if(debug==TRUE)
		syslog(LOG_DEBUG,"Handling the connection...");

#ifdef OLDSTUFF
	/* socket should be non-blocking */
	fcntl(sock,F_SETFL,O_NONBLOCK);
#endif

	/* set connection handler */
	signal(SIGALRM,my_connection_sighandler);
	alarm(connection_timeout);

#ifdef HAVE_SSL
	/* do SSL handshake */
	if(result==STATE_OK && use_ssl==TRUE){
		if((ssl=SSL_new(ctx))!=NULL){
			SSL_set_fd(ssl,sock);

			/* keep attempting the request if needed */
                        while(((rc=SSL_accept(ssl))!=1) && (SSL_get_error(ssl,rc)==SSL_ERROR_WANT_READ));

			if(rc!=1){
				syslog(LOG_ERR,"Error: Could not complete SSL handshake. %d\n",SSL_get_error(ssl,rc));
#ifdef DEBUG
				errfp=fopen("/tmp/err.log","w");
				ERR_print_errors_fp(errfp);
				fclose(errfp);
#endif
				return;
			        }
		        }
		else{
			syslog(LOG_ERR,"Error: Could not create SSL connection structure.\n");
#ifdef DEBUG
			errfp=fopen("/tmp/err.log","w");
			ERR_print_errors_fp(errfp);
			fclose(errfp);
#endif
			return;
		        }
	        }
#endif

	bytes_to_recv=sizeof(receive_packet);
	if(use_ssl==FALSE)
		rc=recvall(sock,(char *)&receive_packet,&bytes_to_recv,socket_timeout);
#ifdef HAVE_SSL
	else{
                while(((rc=SSL_read(ssl,&receive_packet,bytes_to_recv))<=0) && (SSL_get_error(ssl,rc)==SSL_ERROR_WANT_READ));
		}
#endif

	/* recv() error or client disconnect */
	if(rc<=0){

		/* log error to syslog facility */
		syslog(LOG_ERR,"Could not read request from client, bailing out...");

#ifdef HAVE_SSL
		if(ssl){
			SSL_shutdown(ssl);
			SSL_free(ssl);
			syslog(LOG_INFO,"INFO: SSL Socket Shutdown.\n");
			}
#endif

		return;
                }

	/* we couldn't read the correct amount of data, so bail out */
	else if(bytes_to_recv!=sizeof(receive_packet)){

		/* log error to syslog facility */
		syslog(LOG_ERR,"Data packet from client was too short, bailing out...");

#ifdef HAVE_SSL
		if(ssl){
			SSL_shutdown(ssl);
			SSL_free(ssl);
			}
#endif

		return;
	        }

#ifdef DEBUG
	fp=fopen("/tmp/packet","w");
	if(fp){
		fwrite(&receive_packet,1,sizeof(receive_packet),fp);
		fclose(fp);
	        }
#endif

	/* make sure the request is valid */
	if(validate_request(&receive_packet)==ERROR){

		/* log an error */
		syslog(LOG_ERR,"Client request was invalid, bailing out...");

		/* free memory */
		free(command_name);
		command_name=NULL;
		for(x=0;x<MAX_COMMAND_ARGUMENTS;x++){
			free(macro_argv[x]);
			macro_argv[x]=NULL;
	                }

#ifdef HAVE_SSL
		if(ssl){
			SSL_shutdown(ssl);
			SSL_free(ssl);
			}
#endif

		return;
	        }

	/* log info to syslog facility */
	if(debug==TRUE)
		syslog(LOG_DEBUG,"Host is asking for command '%s' to be run...",receive_packet.buffer);

	/* disable connection alarm - a new alarm will be setup during my_system */
	alarm(0);

	/* if this is the version check command, just spew it out */
	if(!strcmp(command_name,NRPE_HELLO_COMMAND)){

		snprintf(buffer,sizeof(buffer),"NRPE v%s",PROGRAM_VERSION);
		buffer[sizeof(buffer)-1]='\x0';

		/* log info to syslog facility */
		if(debug==TRUE)
			syslog(LOG_DEBUG,"Response: %s",buffer);

		result=STATE_OK;
	        }

	/* find the command we're supposed to run */
	else{
		temp_command=find_command(command_name);
		if(temp_command==NULL){

			snprintf(buffer,sizeof(buffer),"NRPE: Command '%s' not defined",command_name);
			buffer[sizeof(buffer)-1]='\x0';

			/* log error to syslog facility */
			if(debug==TRUE)
				syslog(LOG_DEBUG,"%s",buffer);

			result=STATE_CRITICAL;
	                }

		else{

			/* process command line */
			if(command_prefix==NULL)
				strncpy(raw_command,temp_command->command_line,sizeof(raw_command)-1);
			else
				snprintf(raw_command,sizeof(raw_command)-1,"%s %s",command_prefix,temp_command->command_line);
			raw_command[sizeof(raw_command)-1]='\x0';
			process_macros(raw_command,processed_command,sizeof(processed_command));

			/* log info to syslog facility */
			if(debug==TRUE)
				syslog(LOG_DEBUG,"Running command: %s",processed_command);

			/* run the command */
			strcpy(buffer,"");
			result=my_system(processed_command,command_timeout,&early_timeout,buffer,sizeof(buffer));

			/* log debug info */
			if(debug==TRUE)
				syslog(LOG_DEBUG,"Command completed with return code %d and output: %s",result,buffer);

			/* see if the command timed out */
			if(early_timeout==TRUE)
				snprintf(buffer,sizeof(buffer)-1,"NRPE: Command timed out after %d seconds\n",command_timeout);
			else if(!strcmp(buffer,""))
				snprintf(buffer,sizeof(buffer)-1,"NRPE: Unable to read output\n");

			buffer[sizeof(buffer)-1]='\x0';

			/* check return code bounds */
			if((result<0) || (result>3)){

				/* log error to syslog facility */
				syslog(LOG_ERR,"Bad return code for [%s]: %d", buffer,result);

				result=STATE_UNKNOWN;
			        }
		        }
	        }

	/* free memory */
	free(command_name);
	command_name=NULL;
	for(x=0;x<MAX_COMMAND_ARGUMENTS;x++){
		free(macro_argv[x]);
		macro_argv[x]=NULL;
	        }

	/* strip newline character from end of output buffer */
	if(buffer[strlen(buffer)-1]=='\n')
		buffer[strlen(buffer)-1]='\x0';

	/* clear the response packet buffer */
	bzero(&send_packet,sizeof(send_packet));

	/* fill the packet with semi-random data */
	randomize_buffer((char *)&send_packet,sizeof(send_packet));

	/* initialize response packet data */
	send_packet.packet_version=(int16_t)htons(NRPE_PACKET_VERSION_2);
	send_packet.packet_type=(int16_t)htons(RESPONSE_PACKET);
	send_packet.result_code=(int16_t)htons(result);
	strncpy(&send_packet.buffer[0],buffer,MAX_PACKETBUFFER_LENGTH);
	send_packet.buffer[MAX_PACKETBUFFER_LENGTH-1]='\x0';
	
	/* calculate the crc 32 value of the packet */
	send_packet.crc32_value=(u_int32_t)0L;
	calculated_crc32=calculate_crc32((char *)&send_packet,sizeof(send_packet));
	send_packet.crc32_value=(u_int32_t)htonl(calculated_crc32);


	/***** ENCRYPT RESPONSE *****/


	/* send the response back to the client */
	bytes_to_send=sizeof(send_packet);
	if(use_ssl==FALSE)
		sendall(sock,(char *)&send_packet,&bytes_to_send);
#ifdef HAVE_SSL
	else
		SSL_write(ssl,&send_packet,bytes_to_send);
#endif

#ifdef HAVE_SSL
	if(ssl){
		SSL_shutdown(ssl);
		SSL_free(ssl);
		}
#endif

	/* log info to syslog facility */
	if(debug==TRUE)
		syslog(LOG_DEBUG,"Return Code: %d, Output: %s",result,buffer);

	return;
        }
コード例 #10
0
int autofs4_wait(struct autofs_sb_info *sbi, struct dentry *dentry,
		enum autofs_notify notify)
{
	struct autofs_wait_queue *wq;
	struct qstr qstr;
	char *name;
	int status, ret, type;

	/* In catatonic mode, we don't wait for nobody */
	if (sbi->catatonic)
		return -ENOENT;

	if (!dentry->d_inode) {
		/*
		 * A wait for a negative dentry is invalid for certain
		 * cases. A direct or offset mount "always" has its mount
		 * point directory created and so the request dentry must
		 * be positive or the map key doesn't exist. The situation
		 * is very similar for indirect mounts except only dentrys
		 * in the root of the autofs file system may be negative.
		 */
		if (autofs_type_trigger(sbi->type))
			return -ENOENT;
		else if (!IS_ROOT(dentry->d_parent))
			return -ENOENT;
	}

	name = kmalloc(NAME_MAX + 1, GFP_KERNEL);
	if (!name)
		return -ENOMEM;

	/* If this is a direct mount request create a dummy name */
	if (IS_ROOT(dentry) && autofs_type_trigger(sbi->type))
		qstr.len = sprintf(name, "%p", dentry);
	else {
		qstr.len = autofs4_getpath(sbi, dentry, &name);
		if (!qstr.len) {
			kfree(name);
			return -ENOENT;
		}
	}
	qstr.name = name;
	qstr.hash = full_name_hash(name, qstr.len);

	if (mutex_lock_interruptible(&sbi->wq_mutex)) {
		kfree(qstr.name);
		return -EINTR;
	}

	ret = validate_request(&wq, sbi, &qstr, dentry, notify);
	if (ret <= 0) {
		if (ret == 0)
			mutex_unlock(&sbi->wq_mutex);
		kfree(qstr.name);
		return ret;
	}

	if (!wq) {
		/* Create a new wait queue */
		wq = kmalloc(sizeof(struct autofs_wait_queue),GFP_KERNEL);
		if (!wq) {
			kfree(qstr.name);
			mutex_unlock(&sbi->wq_mutex);
			return -ENOMEM;
		}

		wq->wait_queue_token = autofs4_next_wait_queue;
		if (++autofs4_next_wait_queue == 0)
			autofs4_next_wait_queue = 1;
		wq->next = sbi->queues;
		sbi->queues = wq;
		init_waitqueue_head(&wq->queue);
		memcpy(&wq->name, &qstr, sizeof(struct qstr));
		wq->dev = autofs4_get_dev(sbi);
		wq->ino = autofs4_get_ino(sbi);
		wq->uid = current_uid();
		wq->gid = current_gid();
		wq->pid = current->pid;
		wq->tgid = current->tgid;
		wq->status = -EINTR; /* Status return if interrupted */
		wq->wait_ctr = 2;
		mutex_unlock(&sbi->wq_mutex);

		if (sbi->version < 5) {
			if (notify == NFY_MOUNT)
				type = autofs_ptype_missing;
			else
				type = autofs_ptype_expire_multi;
		} else {
			if (notify == NFY_MOUNT)
				type = autofs_type_trigger(sbi->type) ?
					autofs_ptype_missing_direct :
					 autofs_ptype_missing_indirect;
			else
				type = autofs_type_trigger(sbi->type) ?
					autofs_ptype_expire_direct :
					autofs_ptype_expire_indirect;
		}

		DPRINTK("new wait id = 0x%08lx, name = %.*s, nfy=%d\n",
			(unsigned long) wq->wait_queue_token, wq->name.len,
			wq->name.name, notify);

		/* autofs4_notify_daemon() may block */
		autofs4_notify_daemon(sbi, wq, type);
	} else {
		wq->wait_ctr++;
		mutex_unlock(&sbi->wq_mutex);
		kfree(qstr.name);
		DPRINTK("existing wait id = 0x%08lx, name = %.*s, nfy=%d",
			(unsigned long) wq->wait_queue_token, wq->name.len,
			wq->name.name, notify);
	}

	/*
	 * wq->name.name is NULL iff the lock is already released
	 * or the mount has been made catatonic.
	 */
	if (wq->name.name) {
		/* Block all but "shutdown" signals while waiting */
		sigset_t oldset;
		unsigned long irqflags;

		spin_lock_irqsave(&current->sighand->siglock, irqflags);
		oldset = current->blocked;
		siginitsetinv(&current->blocked, SHUTDOWN_SIGS & ~oldset.sig[0]);
		recalc_sigpending();
		spin_unlock_irqrestore(&current->sighand->siglock, irqflags);

		wait_event_interruptible(wq->queue, wq->name.name == NULL);

		spin_lock_irqsave(&current->sighand->siglock, irqflags);
		current->blocked = oldset;
		recalc_sigpending();
		spin_unlock_irqrestore(&current->sighand->siglock, irqflags);
	} else {
		DPRINTK("skipped sleeping");
	}

	status = wq->status;

	/*
	 * For direct and offset mounts we need to track the requester's
	 * uid and gid in the dentry info struct. This is so it can be
	 * supplied, on request, by the misc device ioctl interface.
	 * This is needed during daemon resatart when reconnecting
	 * to existing, active, autofs mounts. The uid and gid (and
	 * related string values) may be used for macro substitution
	 * in autofs mount maps.
	 */
	if (!status) {
		struct autofs_info *ino;
		struct dentry *de = NULL;

		/* direct mount or browsable map */
		ino = autofs4_dentry_ino(dentry);
		if (!ino) {
			/* If not lookup actual dentry used */
			de = d_lookup(dentry->d_parent, &dentry->d_name);
			if (de)
				ino = autofs4_dentry_ino(de);
		}

		/* Set mount requester */
		if (ino) {
			spin_lock(&sbi->fs_lock);
			ino->uid = wq->uid;
			ino->gid = wq->gid;
			spin_unlock(&sbi->fs_lock);
		}

		if (de)
			dput(de);
	}

	/* Are we the last process to need status? */
	mutex_lock(&sbi->wq_mutex);
	if (!--wq->wait_ctr)
		kfree(wq);
	mutex_unlock(&sbi->wq_mutex);

	return status;
}
コード例 #11
0
map_handler::map_handler(FCGX_Request &request) 
  : bounds(validate_request(request)) {
}
コード例 #12
0
int ModbusSlave232::update(int *regs,
unsigned int regs_size) 
{
        unsigned char query[MAX_MESSAGE_LENGTH];
        unsigned char errpacket[EXCEPTION_SIZE + CHECKSUM_SIZE];
        unsigned int start_addr;
        int exception;
        int length = W232.available();
        unsigned long now = millis();
        
		//USB.print("\n");
		//USB.print("Datos recibidos : ");
		//USB.println(length);
		

        if (length == 0) {
                lastBytesReceived = 0;
                return 0;
        }

        if (lastBytesReceived != length) {
                lastBytesReceived = length;
                Nowdt = now + T35;
                return 0;
        }
        if (now < Nowdt) 
                return 0;

        lastBytesReceived = 0;

        length = modbus_request(query);
        if (length < 1) 
                return length;
         
                exception = validate_request(query, length, regs_size);
                if (exception) {
                        build_error_packet( query[FUNC], exception,
                        errpacket);
                        send_reply(errpacket, EXCEPTION_SIZE);
                        return (exception);
                } 

                        start_addr =
                                ((int) query[START_H] << 8) +
                                (int) query[START_L];

        switch (query[FUNC]) {
                case FC_READ_REGS:
                        return read_holding_registers(
                        start_addr,
                        query[REGS_L],
                        regs);
                break;
                case FC_WRITE_REGS:
                        return preset_multiple_registers(
                        start_addr,
                        query[REGS_L],
                        query,
                        regs);
                break;
                case FC_WRITE_REG:
                        write_single_register(
                        start_addr,
                        query,
                        regs);
                break;                                
        }      
        
}