Exemplo n.º 1
0
void
ia32_step(void)
{
	int rv;

	rv = sigsetjmp(exec_1step_jmpbuf, 1);
	switch (rv) {
	case 0:
		break;

	case 1:
		VERBOSE(("ia32_step: return from exception"));
		break;

	case 2:
		VERBOSE(("ia32_step: return from panic"));
		return;

	default:
		VERBOSE(("ia32_step: return from unknown cause"));
		break;
	}

	do {
		exec_1step();
#if !defined(IA32_SUPPORT_DEBUG_REGISTER)
		if (CPU_TRAP) {
			CPU_DR6 |= CPU_DR6_BS;
			INTERRUPT(1, TRUE, FALSE, 0);
		}
#endif
		if (dmac.working) {
			dmax86();
		}
	} while (CPU_REMCLOCK > 0);
}
Exemplo n.º 2
0
/*
 * check_functionality() - make sure the memory is detached correctly
 */
void check_functionality(void)
{
	/* stat the shared memory segment */
	if (shmctl(shm_id_1, IPC_STAT, &buf) == -1)
		tst_brkm(TBROK | TERRNO, cleanup,
			 "could not stat in signal handler");

	if (buf.shm_nattch != 0) {
		tst_resm(TFAIL, "# of attaches is incorrect");
		return;
	}

	/*
	 * Try writing to the shared memory.  This should generate a
	 * SIGSEGV which will be caught below.
	 *
	 * This is wrapped by the sigsetjmp() call that will take care of
	 * restoring the program's context in an elegant way in conjunction
	 * with the call to siglongjmp() in the signal handler.
	 *
	 * An attempt to do the assignment without using the sigsetjmp()
	 * and siglongjmp() calls will result in an infinite loop.  Program
	 * control is returned to the assignment statement after the execution
	 * of the signal handler and another SIGSEGV will be generated.
	 */

	if (sigsetjmp(env, 1) == 0) {
		*shared = 2;
	}

	if (pass) {
		tst_resm(TPASS, "shared memory detached correctly");
	} else {
		tst_resm(TFAIL, "shared memory was not detached correctly");
	}
}
Exemplo n.º 3
0
void OPENSSL_cpuid_setup(void)
	{
	sigset_t oset;
	struct sigaction ill_act,oact;

	if (OPENSSL_s390xcap_P) return;

	TINYCLR_SSL_MEMSET(&ill_act,0,sizeof(ill_act));
	ill_act.sa_handler = ill_handler;
	sigfillset(&ill_act.sa_mask);
	sigdelset(&ill_act.sa_mask,SIGILL);
	sigdelset(&ill_act.sa_mask,SIGTRAP);
	sigprocmask(SIG_SETMASK,&ill_act.sa_mask,&oset);
	sigaction (SIGILL,&ill_act,&oact);

	/* protection against missing store-facility-list-extended */
	if (sigsetjmp(ill_jmp,0) == 0)
		OPENSSL_s390xcap_P = OPENSSL_s390x_facilities();
	else
		OPENSSL_s390xcap_P = 1UL<<63;

	sigaction (SIGILL,&oact,NULL);
	sigprocmask(SIG_SETMASK,&oset,NULL);
	}
Exemplo n.º 4
0
static char * get_stack_bottom(void) {
    /*
     * for autovar, must be volatile
     */
    volatile char *c;

    seg_handler = Signal( SIGSEGV, segfault);
    bus_handler = Signal( SIGBUS, segfault);
    c = (char *) &c;
    if ( sigsetjmp( jmpbuf, 1 ) != 0) {
        Signal( SIGSEGV, seg_handler);
        Signal( SIGBUS, bus_handler);
        return ((char *) c);
    }
    /*
     * now sigsetjump() is OK
     */
    canjump = 1;
    while (1) {
        *c = *c;
        c++;
    }
    return ( NULL);
} /* end of get_stack_bottom */
Exemplo n.º 5
0
/* ----------------------------------------------------------------
 * 功    能:从消息队列中读取消息,消息最大为MSGSIZE
 * 输入参数:
 *           iMsgid    消息队列的标识符
 *           lMsgType  消息的类型
 *           iTimeOut  超时时间(0:无限等待接收消息,>0:超时时间)
 * 输出参数:szRcvBuf  收到的数据
 * 返 回 值: 0   成功/-1  失败
 * 作    者:
 * 日    期:2012/12/27
 * 调用说明:
 * 修改日志:修改日期    修改者      修改内容简述
 * ----------------------------------------------------------------
 */
int RcvMsgFromMQ(int iMsgid, long lMsgType, int iTimeOut, char *szRcvBuf)
{
    int rcvlen;
    struct MsgBuf mb;

    if (iMsgid <= 0 || lMsgType <= 0 || iTimeOut < 0 || szRcvBuf == NULL)
    {
        return FAIL;
    }

    if (iTimeOut > 0)
    {
        signal(SIGALRM, RcvMsgTimeOutProc);
        if (sigsetjmp(RcvMsgTimeOut, 1) != 0)
        {
            PRINT_LOG(ERROR_LVL, "RcvMsgFromMQ(msgid=%d) Timeout", 
                      iMsgid);
            return SUCC;
        }
        alarm(iTimeOut);
    }

    memset(&mb, 0, sizeof(mb));
    rcvlen = msgrcv(iMsgid, &mb, MSGSIZE, lMsgType, 0);
    if (rcvlen == -1)
    {
        PRINT_LOG(ERROR_LVL, "call msgrcv(msgid=%d) fail[%d-%s]", 
                  iMsgid, errno, strerror(errno));
        return FAIL;
    }
    alarm(0);

    memcpy(szRcvBuf, mb.mbuf, rcvlen);

    return (rcvlen);
}
Exemplo n.º 6
0
/*
 * context - returned from image_begin_load
 *
 * free context, unref gdk_pixbuf
 */
static gboolean
gdk_pixbuf__jpeg_image_stop_load (gpointer data, GError **error)
{
	JpegProgContext *context = (JpegProgContext *) data;
        gboolean retval;

	g_return_val_if_fail (context != NULL, TRUE);
	
        /* FIXME this thing needs to report errors if
         * we have unused image data
         */
        
	if (context->pixbuf)
		g_object_unref (context->pixbuf);
	
	/* if we have an error? */
	context->jerr.error = error;
	if (sigsetjmp (context->jerr.setjmp_buffer, 1)) {
                retval = FALSE;
	} else {
		jpeg_finish_decompress (&context->cinfo);
                retval = TRUE;
	}

        jpeg_destroy_decompress (&context->cinfo);

	if (context->cinfo.src) {
		my_src_ptr src = (my_src_ptr) context->cinfo.src;
		
		g_free (src);
	}

	g_free (context);

        return retval;
}
Exemplo n.º 7
0
void _runtest(const char* filename, int linenum, const char* testname, void (*f)())
{
  TRACE_ENTER;
  static sigjmp_buf sigjmpbuf;
  static jmp_buf jmpbuf;
  int rc = 0;
  int code = sigsetjmp(sigjmpbuf, 1);
  if (code == 0) {
    code = setjmp(jmpbuf);
    if (code == 0) {
      _catch_signals(filename, linenum, testname, &rc, &sigjmpbuf, &jmpbuf);
      (*f)();
      _release_signals();
    } else {
      TRACE_CATCH;
      rc = code;
      _release_signals();
    }
  } else {
    //printf("after siglongjmp\n");
    TRACE_CATCH;
    //printf("after trace_catch\n");
    rc = code;
    _release_signals();
    //printf("after release_signals\n");
  }

  if (rc == 0 && __verbose) {
    printf("Passed %s\n\n", testname);
  }
  else if (rc != 0) {
    __tests_failed++;
    printf("%s:%d: Failed %s\n\n", filename, linenum, testname);
  }
  TRACE_EXIT;
}
Exemplo n.º 8
0
int execLibNrpc(char *C)
{
int i;
    if (sigsetjmp(ENV_INT,1)) {
       return 0;
    }
    if (IF_execFct(C)) return 1;
    for (i=0;i<NBFonc;i++) {
        if (strcmp(C,Fonctions[i].nam) == 0) {
           switch (Fonctions[i].typ) {
            case 1:
            case 3: /* usr fct */
              return 0;
              break;
            default: /* typ = 0 et 2 */
              Fonctions[i].fct();
              break;
           }
           return 1;
        }
    }
    if (IF_execVar(C)) return 1; /* VARS DOWN */
    return 0;
}
Exemplo n.º 9
0
int
g_print_stats (char *file, uint32_t flags, size_t block_sz)
{
  g_setjmp (0, "g_print_stats", NULL, NULL);

  if (block_sz)
    {
      g_act_1.block_sz = block_sz;
    }

  if (g_fopen (file, "r", F_DL_FOPEN_BUFFER | flags, &g_act_1))
    {
      return 2;
    }

  if (gfl & F_OPT_LOADQ)
    {
      goto rc_end;
    }

  void *buffer = calloc (1, g_act_1.block_sz);

  pt_g_bmatch proc_match = g_bmatch;

  int r = 0;

  if (gfl & F_OPT_SORT)
    {
      if (gfl & F_OPT_NOBUFFER)
	{
	  print_str ("ERROR: %s: unable to sort with buffering disabled\n",
		     g_act_1.file);
	  goto r_end;
	}

      void *s_exec = (void*) g_act_1.exec_args.exc;

      if (l_sfo == L_STFO_SORT)
	{
	  if (g_print_do_filter (&g_act_1, s_exec))
	    {
	      goto r_end;
	    }
	}

      if (gfl & F_OPT_KILL_GLOBAL)
	{
	  goto r_end;
	}

      if (do_sort (&g_act_1, g_sort_field, g_sort_flags))
	{
	  goto r_end;
	}

      if (l_sfo == L_STFO_FILTER)
	{
	  if (g_print_do_filter (&g_act_1, s_exec))
	    {
	      goto r_end;
	    }
	}

      if (gfl & F_OPT_KILL_GLOBAL)
	{
	  goto r_end;
	}

      g_act_1.max_hits = 0;
      g_act_1.max_results = 0;

      if (g_act_1.j_offset == 2)
	{
	  g_act_1.buffer.r_pos = md_last (&g_act_1.buffer);
	}
      else
	{
	  g_act_1.buffer.r_pos = md_first (&g_act_1.buffer);
	}

      //proc_match = g_bmatch_dummy;

      md_g_free_cb (&g_act_1._match_rr, g_cl_mrr);
    }

  __d_is_wb w_d_s = g_act_1.w_d;

  g_act_1.w_d = g_act_1.w_d_pr;

  g_do_ppprint (&g_act_1, F_GH_PRE_PRINT, &g_act_1.pre_print_mech,
		g_act_1.g_proc4_pr);

  if (gfl0 & F_OPT_LOADQA)
    {
      goto r_end;
    }

  g_act_1.w_d = w_d_s;

  void *ptr;

  size_t c = 0;

  g_setjmp (F_SIGERR_CONTINUE, "g_print_stats(loop)", NULL, NULL);

  g_act_1.buffer.offset = 0;

  if (!sigsetjmp(g_sigjmp.env, 1))
    {
      while ((ptr = g_read (buffer, &g_act_1, g_act_1.block_sz)))
	{
	  if ((gfl & F_OPT_KILL_GLOBAL))
	    {
	      break;
	    }

	  if ((r = proc_match (ptr, &g_act_1, &g_act_1.buffer)))
	    {
	      if (r == -1)
		{
		  print_str ("ERROR: %s: [%d] matching record failed\n",
			     g_act_1.file, r);
		  break;
		}

	      continue;
	    }

	  c++;
	  g_act_1.g_proc4 ((void*) &g_act_1, ptr, NULL);

	}

    }
  else
    {
      print_str (
	  "ERROR: %s: an exception has occured, terminating enumeration and attempt cleanup..\n",
	  g_act_1.file);
      EXITVAL = 2;
      goto r_end;
    }

  g_act_1.w_d = g_act_1.w_d_po;

  g_do_ppprint (&g_act_1, F_GH_POST_PRINT, &g_act_1.post_print_mech,
		g_act_1.g_proc4_po);

  if (gfl & F_OPT_MODE_RAWDUMP)
    {
#ifdef HAVE_ZLIB_H
      if ((g_act_1.flags & F_GH_IO_GZIP) && g_act_1.gz_fh1)
	{
	  gzflush(g_act_1.gz_fh1, Z_FINISH);
	}
#endif
      fflush (stdout);
    }

  // g_setjmp(0, "dirlog_print_stats(2)", NULL, NULL);

  if (!(g_act_1.flags & F_GH_ISONLINE) && (gfl0 & F_OPT_STATS))
    {
      fprintf (
	  stderr,
	  "STATS: %s: processed %llu/%llu records\n",
	  file,
	  (unsigned long long int) c,
	  !g_act_1.buffer.count ?
	      (unsigned long long int) c : g_act_1.buffer.count);
    }

  if (0 == c && 0 == EXITVAL)
    {
      EXITVAL = 2;
    }

  r_end:

  free (buffer);

  rc_end:

  g_close (&g_act_1);

  return EXITVAL;
}
Exemplo n.º 10
0
int main(int argc, char ** argv)
{

	if (signal(SIGPIPE,sig_pipe)==SIG_ERR)
		perror("signal_SIGPIPE");
	if (signal(SIGALRM,sig_alrm)==SIG_ERR)
		perror("signal_SIGALRM");

	int i;
	for (i=1;i<8;i++)
	{
		if (!strncmp(argv[i],"-n",2))
			nsublist=atoi(argv[i+1]);
		else if (!strncmp(argv[i],"-p",2))
			nchild=atoi(argv[i+1]);
		else if (!strncmp(argv[i],"-e",2))
			strcpy(sortpath,argv[i+1]);
		else if (!strncmp(argv[i],"-k",2))
			ansk=atoi(argv[i+1]);
	}	

	read(0,&ndata,4);
	int unsortData=ndata;
	int sortData=0;

	// printf("n:%d,p:%d,k:%d,path:%s;data %d\n",nsublist,nchild,ansk,sortpath,ndata);
	fflush(stdout);

	int buf[trans_buf_size];
	int nByte,remainByte;

	char bufname[100];
	int unreadData=ndata;
	for (i=0;i<((ndata%nsublist)?nsublist+1:nsublist);i++)
	{
		tmpfp[i]=tmpfile();
		tmpfp2[i]=tmpfile();
			
		subread[i]=0;
	
		sublen[i]=ndata/nsublist;
		if (unreadData<sublen[i])
			sublen[i]=unreadData;

		remainByte=sublen[i]*4;
		while (remainByte>=4*trans_buf_size)
		{
			memset(buf,0,trans_buf_size*4);
			nByte=read(0,buf,4*trans_buf_size);
			
			fwrite(buf,4,nByte/4,tmpfp2[i]);
			remainByte-=nByte;
		};
		while (remainByte!=0)
		{
			memset(buf,0,trans_buf_size*4);
			nByte=read(0,buf,remainByte);
			fwrite(buf,4,nByte/4,tmpfp2[i]);
			remainByte-=nByte;
		};
		unreadData-=sublen[i];
	};

	// printf("read data finish!\n");
	fflush(stdout);


	for (i=0;i<nchild;i++)
		make_child(i);

	// printf("make child finish!\n");
	fflush(stdout);
	
	fd_set rfd,wfd;
	struct timeval tv;
	tv.tv_sec=100;
	tv.tv_usec=0;
	int retval,maxfd;

	for (i=0;i<nchild;i++)
		childsub[i]=-1;

	while (!(sortData==ndata))
	{
		if (sigsetjmp(jmpbuf,1)==1)
		{
			// fprintf(stderr,"jumped\n");
			unsortData=ndata-sortData;
		}
		  /* Parent reads from pipe 1, writes to pipe 0*/
		FD_ZERO(&rfd);
		FD_ZERO(&wfd);
		maxfd=-1;
		// fprintf(stderr,"data unsorted: %d\n",unsortData);
		if (unsortData>0)
			for (i=0;i<nchild;i++)
			{
				FD_SET(pipefd[i][0][1],&wfd);
				if (pipefd[i][0][1]>maxfd)
					maxfd=pipefd[i][0][1];
			};
		for (i=0;i<nchild;i++)
		{
			FD_SET(pipefd[i][1][0],&rfd);
			if (pipefd[i][1][0]>maxfd)
				maxfd=pipefd[i][1][0];
		};

		alarm(15);
		retval=select(maxfd+1,&rfd,&wfd,NULL,&tv);
		if (retval==-1)
		{
			if (errno==EINTR)
				continue;
		}
		else if (retval==0)
			continue;
		else 
		{
			if (unsortData>0)
			{
				for (i=0;i<nchild;i++)
					if (childsub[i]==-1 && FD_ISSET(pipefd[i][0][1],&wfd))
					{
						// if (sigsetjmp(jmpbuf,1)==1)
						// {
						// 	fprintf(stderr,"jumped\n");
						// 	continue;
						// }

						alarm(15);


						int k;
						for (k=0;k<((ndata%nsublist)?nsublist+1:nsublist);k++)
							if (!subread[k])
								break;

						// printf("send sublist %d to %d, pid %d \n",k,i,cpid[i]);
						fflush(stdout);

						fseek(tmpfp2[k],0,SEEK_SET);
						int tp=sublen[k];
						if (write(pipefd[i][0][1],&tp,4)!=4)
							if (errno==EPIPE)
							{
								//perror("sigpipe");
								kill(cpid[i],SIGINT);
								make_child(i);
								continue;
							}
						
						remainByte=sublen[k]*4;
						while (remainByte>=4*trans_buf_size)
						{
							memset(buf,0,trans_buf_size*4);
							nByte=fread(buf,4,trans_buf_size,tmpfp2[k])*4;
							
							if (write(pipefd[i][0][1],buf,nByte)!=nByte)
								if (errno==EPIPE)
								{
									kill(cpid[i],SIGINT);
									make_child(i);
									continue;
								}
							remainByte-=nByte;
						};
						while (remainByte!=0)
						{
							memset(buf,0,trans_buf_size*4);
							nByte=fread(buf,4,remainByte/4,tmpfp2[k])*4;

							if (write(pipefd[i][0][1],buf,nByte)!=nByte)
								if (errno==EPIPE)
								{
									kill(cpid[i],SIGINT);
									make_child(i);
									continue;
								}

							remainByte-=nByte;
						};
						// printf("send sublist %d to %d finish, send %d, remain %d\n",k,i,sublen[k],unsortData);
						fflush(stdout);
					
						unsortData-=sublen[k];
						subread[k]=1;
						childsub[i]=k;
						if (unsortData==0)
							break;

					};
			};
			for (i=0;i<nchild;i++)
				if (FD_ISSET(pipefd[i][1][0],&rfd))
				{
					alarm(15);
					fseek(tmpfp[childsub[i]],0,SEEK_SET);
					// if (sigsetjmp(jmpbuf,1)==1)
					// {
					// 	fprintf(stderr,"jumped\n");
					// 	continue;
					// }

					// printf("receive from %d begin\n",i);
					fflush(stdout);

					int remainByte=sublen[childsub[i]]*4;
					while (remainByte>=4*trans_buf_size)
					{
						memset(buf,0,trans_buf_size*4);
						nByte=read(pipefd[i][1][0],buf,4*trans_buf_size);
						fwrite(buf,4,nByte/4,tmpfp[childsub[i]]);
						remainByte-=nByte;
					};
					while (remainByte!=0)
					{
						memset(buf,0,trans_buf_size*4);
						nByte=read(pipefd[i][1][0],buf,remainByte);
						fwrite(buf,4,nByte/4,tmpfp[childsub[i]]);
						remainByte-=nByte;
					}
					
					// printf("receive sublist %d from %d end, data soted %d, total sorted %d\n",childsub[i],i,sublen[childsub[i]],sortData);
					fflush(stdout);
					
					sortData+=sublen[childsub[i]];
					childsub[i]=-1;
					
				}
		}
	};
	// printf("sort finish,begin to merge\n");
	fflush(stdout);

	printf("%d",findAns(ansk));

	for (i=0;i<nchild;i++)
		kill(cpid[i],SIGINT);

	return 1;
}
Exemplo n.º 11
0
void
recvrequest(const char *cmd, 
	    char *volatile local, char *remote, 
	    const char *lmode, int printnames)
{
	FILE *volatile fout, *volatile din = 0;
	int (*volatile closefunc)(FILE *);
	void (*volatile oldintp)(int);
	void (*volatile oldintr)(int);
	volatile int is_retr, tcrflag, bare_lfs = 0;
	static unsigned bufsize;
	static char *buf;
	volatile long bytes = 0, hashbytes = HASHBYTES;
	register int c, d;
	struct timeval start, stop;
	struct stat st;

#if 0
	printf("%s(%d): recvrequest(cmd=%s,local=%s,remote=%s)\n", __FILE__, __LINE__, cmd, local, remote);
#endif
	is_retr = strcmp(cmd, "RETR") == 0;
	if (is_retr && ftpverbose && printnames) {
		if (local && *local != '-')
			printf("local: %s ", local);
		if (remote)
			printf("remote: %s\n", remote);
	}
#if 0
	if (proxy && is_retr) {
		proxtrans(cmd, local, remote);
		return;
	}
#endif
	closefunc = NULL;
	oldintr = NULL;
	oldintp = NULL;
	tcrflag = !crflag && is_retr;
	if (sigsetjmp(recvabort, 1)) {
		while (cpend) {
			(void) getreply(0);
		}
		if (data >= 0) {
			(void) close(data);
			data = -1;
		}
		if (oldintr)
			(void) signal(SIGINT, oldintr);
		code = -1;
		return;
	}
	oldintr = signal(SIGINT, abortrecv);
#if 0
	if (strcmp(local, "-") && *local != '|') {
		if (access(local, W_OK) < 0) {
			char *dir = rindex(local, '/');

			if (errno != ENOENT && errno != EACCES) {
				fprintf(stderr, "local: %s: %s\n", local,
					strerror(errno));
				(void) signal(SIGINT, oldintr);
				code = -1;
				return;
			}
			if (dir != NULL)
				*dir = 0;
			d = access(dir ? local : ".", W_OK);
			if (dir != NULL)
				*dir = '/';
			if (d < 0) {
				fprintf(stderr, "local: %s: %s\n", local,
					strerror(errno));
				(void) signal(SIGINT, oldintr);
				code = -1;
				return;
			}
			if (!runique && errno == EACCES &&
			    chmod(local, 0600) < 0) {
				fprintf(stderr, "local: %s: %s\n", local,
					strerror(errno));
				/*
				 * Believe it or not, this was actually
				 * repeated in the original source.
				 */
				(void) signal(SIGINT, oldintr);
				/*(void) signal(SIGINT, oldintr);*/
				code = -1;
				return;
			}
			if (runique && errno == EACCES &&
			   (local = gunique(local)) == NULL) {
				(void) signal(SIGINT, oldintr);
				code = -1;
				return;
			}
		}
		else if (runique && (local = gunique(local)) == NULL) {
			(void) signal(SIGINT, oldintr);
			code = -1;
			return;
		}
	}
#endif
	if (!is_retr) {
		if (curtype != TYPE_A)
			changetype(TYPE_A, 0);
	} 
	else if (curtype != type) {
		changetype(type, 0);
	}
	if (initconn()) {
		(void) signal(SIGINT, oldintr);
		code = -1;
		return;
	}
	if (sigsetjmp(recvabort, 1))
		goto abort;
	if (is_retr && restart_point &&
	    command("REST %ld", (long) restart_point) != CONTINUE)
		return;
	if (remote) {
		if (command("%s %s", cmd, remote) != PRELIM) {
			(void) signal(SIGINT, oldintr);
			return;
		}
	} 
	else {
		if (command("%s", cmd) != PRELIM) {
			(void) signal(SIGINT, oldintr);
			return;
		}
	}
	din = dataconn("r");
	if (din == NULL)
		goto abort;
	if (strcmp(local, "-") == 0)
		fout = stdout;
	else if (*local == '|') {
		oldintp = signal(SIGPIPE, SIG_IGN);
		fout = popen(local + 1, "w");
		if (fout == NULL) {
			perror(local+1);
			goto abort;
		}
		closefunc = pclose;
	} 
	else {
		extern int local_fclose();
		fout = local_fopen(local, lmode);
		if (fout == NULL) {
			fprintf(stderr, "local: %s: %s\n", local,
				strerror(errno));
			goto abort;
		}
		closefunc = local_fclose;
	}
	if (fstat(fileno(fout), &st) < 0 || st.st_blksize == 0)
		st.st_blksize = BUFSIZ;
	if (st.st_blksize > bufsize) {
		if (buf)
			(void) free(buf);
		buf = malloc((unsigned)st.st_blksize);
		if (buf == NULL) {
			perror("malloc");
			bufsize = 0;
			goto abort;
		}
		bufsize = st.st_blksize;
	}
	(void) gettimeofday(&start, (struct timezone *)0);
	switch (curtype) {

	case TYPE_I:
	case TYPE_L:
		if (restart_point &&
		    lseek(fileno(fout), (long) restart_point, L_SET) < 0) {
			fprintf(stderr, "local: %s: %s\n", local,
				strerror(errno));
			if (closefunc != NULL)
				(*closefunc)(fout);
			return;
		}
		errno = d = 0;
		while ((c = read(fileno(din), buf, bufsize)) > 0) {
			if ((d = local_write(fileno(fout), buf, c)) != c)
				break;
			bytes += c;
			if (hash && is_retr) {
				while (bytes >= hashbytes) {
					(void) putchar('#');
					hashbytes += HASHBYTES;
				}
				(void) fflush(stdout);
			}
			if (tick && (bytes >= hashbytes) && is_retr) {
				(void) printf("\rBytes transferred: %ld",
					bytes);
				(void) fflush(stdout);
				while (bytes >= hashbytes)
					hashbytes += TICKBYTES;
			}
		}
		if (hash && bytes > 0) {
			if (bytes < HASHBYTES)
				(void) putchar('#');
			(void) putchar('\n');
			(void) fflush(stdout);
		}
		if (tick && is_retr) {
			(void) printf("\rBytes transferred: %ld\n", bytes);
			(void) fflush(stdout);
		}
		if (c < 0) {
			if (errno != EPIPE)
				perror("netin");
			bytes = -1;
		}
		if (d < c) {
			if (d < 0)
				fprintf(stderr, "local: %s: %s\n", local,
					strerror(errno));
			else
				fprintf(stderr, "%s: short write\n", local);
		}
		break;

	case TYPE_A:
#if 0 /* ascii mode not supported for netflash */
		if (restart_point) {
			register int i, n, ch;

			if (fseek(fout, 0L, L_SET) < 0)
				goto done;
			n = restart_point;
			for (i = 0; i++ < n;) {
				if ((ch = getc(fout)) == EOF)
					goto done;
				if (ch == '\n')
					i++;
			}
			if (fseek(fout, 0L, L_INCR) < 0) {
done:
				fprintf(stderr, "local: %s: %s\n", local,
					strerror(errno));
				if (closefunc != NULL)
					(*closefunc)(fout);
				return;
			}
		}
		while ((c = getc(din)) != EOF) {
			if (c == '\n')
				bare_lfs++;
			while (c == '\r') {
				while (hash && (bytes >= hashbytes)
					&& is_retr) {
					(void) putchar('#');
					(void) fflush(stdout);
					hashbytes += HASHBYTES;
				}
				if (tick && (bytes >= hashbytes) && is_retr) {
					printf("\rBytes transferred: %ld",
						bytes);
					fflush(stdout);
					while (bytes >= hashbytes)
						hashbytes += TICKBYTES;
				}
				bytes++;
				if ((c = getc(din)) != '\n' || tcrflag) {
					if (ferror(fout))
						goto break2;
					(void) putc('\r', fout);
					if (c == '\0') {
						bytes++;
						goto contin2;
					}
					if (c == EOF)
						goto contin2;
				}
			}
			(void) putc(c, fout);
			bytes++;
	contin2:	;
		}
break2:
		if (hash && is_retr) {
			if (bytes < hashbytes)
				(void) putchar('#');
			(void) putchar('\n');
			(void) fflush(stdout);
		}
		if (tick && is_retr) {
			(void) printf("\rBytes transferred: %ld\n", bytes);
			(void) fflush(stdout);
		}
		if (bare_lfs) {
			printf("WARNING! %d bare linefeeds received in ASCII mode\n", bare_lfs);
			printf("File may not have transferred correctly.\n");
		}
		if (ferror(din)) {
			if (errno != EPIPE)
				perror("netin");
			bytes = -1;
		}
		if (ferror(fout))
			fprintf(stderr, "local: %s: %s\n", local,
				strerror(errno));
#else
		printf("Netflash does not support ASCII downloads!\n");
		bytes = -1;
#endif 0 /* ascii mode not supported for netflash */
		break;
	}
	if (closefunc != NULL)
		(*closefunc)(fout);
	(void) signal(SIGINT, oldintr);
	if (oldintp)
		(void) signal(SIGPIPE, oldintp);
	(void) gettimeofday(&stop, (struct timezone *)0);
	(void) fclose(din);
	/* closes data as well, so discard it */
	data = -1;
	(void) getreply(0);
	if (bytes > 0 && is_retr)
		ptransfer("received", bytes, &start, &stop);
	return;
abort:

/* abort using RFC959 recommended IP,SYNC sequence  */

	(void) gettimeofday(&stop, (struct timezone *)0);
	if (oldintp)
		(void) signal(SIGPIPE, oldintp);
	(void) signal(SIGINT, SIG_IGN);
	if (!cpend) {
		code = -1;
		(void) signal(SIGINT, oldintr);
		return;
	}

	abort_remote(din);
	code = -1;
	if (closefunc != NULL && fout != NULL)
		(*closefunc)(fout);
	if (din) {
		(void) fclose(din);
	}
	if (data >= 0) {
		/* if it just got closed with din, again won't hurt */
		(void) close(data);
		data = -1;
	}
	if (bytes > 0)
		ptransfer("received", bytes, &start, &stop);
	(void) signal(SIGINT, oldintr);
}
Exemplo n.º 12
0
/*
 * Periodically test network connection. On signals, determine what
 * happened or what to do with child. Return as necessary for exit 
 * or restart of child.
 */
int
ssh_watch(int sock)
{
	int	r;
	int	val;
	static	int	secs_left;
	int	my_poll_time = first_poll_time;
	time_t	now;
	double	secs_to_shutdown;

#if defined(HAVE_SETPROCTITLE)
	setproctitle("parent of %d (%d)", 
	    (int)cchild, start_count);
#endif

	for (;;) {
		if (restart_ssh) {
			errlog(LOG_INFO, "signalled to kill and restart ssh");
			ssh_kill();
			return P_RESTART;
		}
		if ((val = sigsetjmp(jumpbuf, 1)) == 0) {

			errlog(LOG_DEBUG, "check on child %d", cchild);

			/* poll for expired child */
			r = ssh_wait(WNOHANG);
			if (r != P_CONTINUE) {
				errlog(LOG_DEBUG, 
				    "expired child, returning %d", r);
				return r;
			}

			secs_left = alarm(0);
			if (secs_left == 0)
				secs_left = my_poll_time;

			my_poll_time = poll_time;

			if (max_lifetime != 0) {
				time(&now);
				secs_to_shutdown = max_lifetime - difftime(now,pid_start_time);
				if (secs_to_shutdown < poll_time)
					secs_left = secs_to_shutdown;
			}

			errlog(LOG_DEBUG, 
			    "set alarm for %d secs", secs_left);

			alarm(secs_left);
			dolongjmp = 1;
			pause();

		} else {

			switch(val) {
			case SIGINT:
			case SIGTERM:
			case SIGQUIT:
			case SIGABRT:
				errlog(LOG_INFO, 
				    "received signal to exit (%d)", val);
				ssh_kill();
				return P_EXIT;
				break;
			case SIGALRM:
				if (exceeded_lifetime()) {
					ssh_kill();
					return P_EXIT;
				}

				if (writep && sock != -1 &&
				    !conn_test(sock, mhost, writep)) {
					errlog(LOG_INFO, 
					    "port down, restarting ssh");
					ssh_kill();
					return P_RESTART;
				}
#ifdef TOUCH_PIDFILE
				/*
				 * utimes() with a NULL time argument sets
				 * file access and modification times to
				 * the current time
				 */
				if (pid_file_name && 
				    utimes(pid_file_name, NULL) != 0) {
					errlog(LOG_ERR,
					    "could not touch pid file: %s",
					    strerror(errno));
				}
#endif
				break;
			default:
				break;
			}
		}
	}
}
Exemplo n.º 13
0
int run_test( test_func test, const char* func_name )
{
  printf("Running %s ...\n", func_name );
  
#if MODE == EXCEPTION_MODE
  /* On Windows, run all tests in same process.
     Flag errors by throwing an exception.
   */
  try {
    (*test)();
    return 0;
  }
  catch (ErrorExcept) {
    printf( "  %s: FAILED\n", func_name );
    return 1;
  }
  catch (...) {
    printf( "  %s: UNCAUGHT EXCEPTION\n", func_name );
    return 1;
  }
    
#elif MODE == FORK_MODE
    /* For non-Windows OSs, fork() and run test in child process. */
  pid_t pid = fork();
  int status;
  
    /* Fork failed? */
  if (pid == -1) {  
    perror( "fork()" );
    abort(); /* abort all tests (can't fork child processes) */
  }
  
    /* If child process*/
  if (pid == 0) {
    (*test)();  /* call test function */
    exit(0);    /* if function returned, then it succeeded */
  }
  
    /* If here, then parent process */
    
    /* Wait until child process exits */
  waitpid( pid, &status, 0 );
  
    /* Check child exit status */
  if (WIFSIGNALED(status)) {
    if (WTERMSIG(status))
      printf("  %s: TERMINATED (signal %d)\n", func_name, (int)WTERMSIG(status) );
    if (WCOREDUMP(status))
      printf("  %s: CORE DUMP\n", func_name);
    return 1;
  }
  else if(WEXITSTATUS(status)) {
    printf( "  %s: FAILED\n", func_name );
    return 1;
  }
  else {
    return 0;
  }
  
#elif MODE == LONGJMP_MODE
    // Save stack state at this location.
  int rval = sigsetjmp( jmpenv, 1 );
    // If rval is zero, then we haven't run the test yet. 
    // If rval is non-zero then
    // a) we ran the test
    // b) the test failed
    // c) we did a longjmp back to the location where we called setsigjmp.
    
    // run test
  if (!rval) {
    (*test)();
    return 0;
  }
    // some check failed
  else if (rval == -1) {
    printf( "  %s: FAILED\n", func_name );
    return 1;
  }
    // a signal was raised (e.g. segfault)
  else {
    printf( "  %s: TERMINATED (signal %d)\n", func_name, rval );
    return 1;
  }
#else
  #error "MODE not set"
#endif // MODE
}
Exemplo n.º 14
0
/*
 *	Wall function.
 */
void wall(const char *text, int remote)
{
	FILE			*tp;
	struct sigaction	sa;
	struct utmp		*utmp;
	time_t			t;
	char			term[UT_LINESIZE+ strlen(_PATH_DEV) + 1];
	char			line[81];
	char			hostname[HOST_NAME_MAX+1];
	char			*date, *p;
	char			*user, *tty;
	int			fd, flags;

	/*
	 *	Make sure tp and fd aren't in a register. Some versions
	 *	of gcc clobber those after longjmp (or so I understand).
	 */
	(void) &tp;
	(void) &fd;

	getuidtty(&user, &tty);

	/* Get and report current hostname, to make it easier to find
	   out which machine is being shut down. */
	if (0 != gethostname(hostname, sizeof(hostname))) {
		strncpy(hostname, "[unknown]", sizeof(hostname)-1);
	}
	/* If hostname is truncated, it is unspecified if the string
	   is null terminated or not.  Make sure we know it is null
	   terminated. */
	hostname[sizeof(hostname)-1] = 0;

	/* Get the time */
	time(&t);
	date = ctime(&t);
	for(p = date; *p && *p != '\n'; p++)
		;
	*p = 0;
	
	if (remote) {
		snprintf(line, sizeof(line),
			"\007\r\nRemote broadcast message (%s):\r\n\r\n",
			date);
	} else {
		snprintf(line, sizeof(line),
			"\007\r\nBroadcast message from %s@%s %s(%s):\r\n\r\n",
			user, hostname, tty, date);
	}

	/*
	 *	Fork to avoid us hanging in a write()
	 */
	if (fork() != 0)
		return;
	
	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = handler;
	sa.sa_flags = 0;
	sigemptyset(&sa.sa_mask);
	sigaction(SIGALRM, &sa, NULL);

	setutent();

	while ((utmp = getutent()) != NULL) {
		if(utmp->ut_type != USER_PROCESS ||
		   utmp->ut_user[0] == 0) continue;
		if (strncmp(utmp->ut_line, _PATH_DEV, strlen(_PATH_DEV)) == 0) {
			term[0] = 0;
			strncat(term, utmp->ut_line, sizeof(term)-1);
		} else
			snprintf(term, sizeof(term), _PATH_DEV "%.*s",
				UT_LINESIZE, utmp->ut_line);
		if (strstr(term, "/../")) continue;

		fd = -1;
		tp = NULL;

		/*
		 *	Open it non-delay
		 */
		if (sigsetjmp(jbuf, 1) == 0) {
			alarm(2);
			flags = O_WRONLY|O_NDELAY|O_NOCTTY;
			if (file_isatty(term) &&
			    (fd = open(term, flags)) >= 0) {
				if (isatty(fd) &&
				    (tp = fdopen(fd, "w")) != NULL) {
					fputs(line, tp);
					feputs(text, tp);
					fflush(tp);
				}
			}
		}
		alarm(0);
		if (fd >= 0) close(fd);
		if (tp != NULL) fclose(tp);
	}
	endutent();

	exit(0);
}
Exemplo n.º 15
0
int
main(int argc, char *argv[])
{
	START(argc, argv, "blk_recovery");

	if (argc != 5)
		FATAL("usage: %s bsize file first_lba lba", argv[0]);

	Bsize = strtoul(argv[1], NULL, 0);
	const char *path = argv[2];

	PMEMblkpool *handle;
	if ((handle = pmemblk_create(path, Bsize, 0,
			S_IWUSR | S_IRUSR)) == NULL)
		FATAL("!%s: pmemblk_create", path);

	OUT("%s block size %zu usable blocks %zu",
			argv[1], Bsize, pmemblk_nblock(handle));

	/* write the first lba */
	off_t lba = strtoul(argv[3], NULL, 0);
	unsigned char buf[Bsize];

	construct(buf);
	if (pmemblk_write(handle, buf, lba) < 0)
		FATAL("!write     lba %zu", lba);

	OUT("write     lba %zu: %s", lba, ident(buf));

	/* reach into the layout and write-protect the map */
	struct btt_info *infop = (void *)handle +
		roundup(sizeof (struct pmemblk), BLK_FORMAT_DATA_ALIGN);

	void *mapaddr = (void *)infop + le32toh(infop->mapoff);
	void *flogaddr = (void *)infop + le32toh(infop->flogoff);

	OUT("write-protecting map, length %zu", (size_t)(flogaddr - mapaddr));
	MPROTECT(mapaddr, (size_t)(flogaddr - mapaddr), PROT_READ);

	/* arrange to catch SEGV */
	struct sigaction v;
	sigemptyset(&v.sa_mask);
	v.sa_flags = 0;
	v.sa_handler = signal_handler;
	SIGACTION(SIGSEGV, &v, NULL);

	/* map each file argument with the given map type */
	lba = strtoul(argv[4], NULL, 0);

	construct(buf);

	if (!sigsetjmp(Jmp, 1)) {
		if (pmemblk_write(handle, buf, lba) < 0)
			FATAL("!write     lba %zu", lba);
		else
			FATAL("write     lba %zu: %s", lba, ident(buf));
	}

	pmemblk_close(handle);

	int result = pmemblk_check(path);
	if (result < 0)
		OUT("!%s: pmemblk_check", path);
	else if (result == 0)
		OUT("%s: pmemblk_check: not consistent", path);
	else
		OUT("%s: consistent", path);

	DONE(NULL);
}
Exemplo n.º 16
0
/* the volatile qualifiers should be removed as well.                  */ 
int callmgr_main(int argc, char **argv, char **envp) {
  struct in_addr inetaddr;
  int inet_sock, unix_sock;
  fd_set call_set;
  PPTP_CONN * conn;
  VECTOR * call_list;
  int max_fd=0;
  volatile int first=1;
  int retval;
  int i;
  char * volatile phonenr;

  /* Step 0: Check arguments */
  if (argc < 2) 
    fatal("Usage: %s ip.add.ress.here [--phone <phone number>]", argv[0]);
  phonenr = argc==3 ? argv[2] : NULL;
  if (inet_aton(argv[1], &inetaddr)==0)
    fatal("Invalid IP address: %s", argv[1]);

  /* Step 1: Open sockets. */
  if ((inet_sock = open_inetsock(inetaddr)) < 0)
    fatal("Could not open control connection to %s", argv[1]);
  if ((unix_sock = open_unixsock(inetaddr)) < 0)
    fatal("Could not open unix socket for %s", argv[1]);

  /* Step 1b: FORK and return status to calling process. */
  switch (fork()) {
  case 0: /* child. stick around. */
    break;
  case -1: /* failure.  Fatal. */
    fatal("Could not fork.");
  default: /* Parent. Return status to caller. */
    exit(0);
  }

  /* re-open stderr as /dev/null to release it */
  file2fd("/dev/null", "wb", STDERR_FILENO);

  /* Step 1c: Clean up unix socket on TERM */
  if (sigsetjmp(callmgr_env, 1)!=0)
    goto cleanup;

  signal(SIGINT, callmgr_sighandler);
  signal(SIGTERM, callmgr_sighandler);

  signal(SIGPIPE, callmgr_do_nothing);
  signal(SIGUSR1, callmgr_do_nothing); /* signal state change; wake up accept */

  /* Step 2: Open control connection and register callback */
  if ((conn = pptp_conn_open(inet_sock, 1, NULL/* callback */)) == NULL) {
    close(unix_sock); close(inet_sock); fatal("Could not open connection.");
  }

  FD_ZERO(&call_set);
  max_fd = unix_sock;
  call_list = vector_create();
  { 
    struct local_conninfo *conninfo = malloc(sizeof(*conninfo));
    if (conninfo==NULL) {
      close(unix_sock); close(inet_sock); fatal("No memory.");
    }
    conninfo->call_list = call_list;
    conninfo->call_set  = &call_set;
    pptp_conn_closure_put(conn, conninfo);
  }

  if (sigsetjmp(callmgr_env, 1)!=0) goto shutdown;

  /* Step 3: Get FD_SETs */
  do {
    int rc;
    fd_set read_set = call_set, write_set;
    FD_ZERO (&write_set);
    FD_SET (unix_sock, &read_set);
    pptp_fd_set(conn, &read_set, &write_set, &max_fd);

    for (; max_fd > 0 ; max_fd--) {
      if (FD_ISSET (max_fd, &read_set) ||
          FD_ISSET (max_fd, &write_set))
        break;
    }

    /* Step 4: Wait on INET or UNIX event */

    if ((rc = select(max_fd+1, &read_set, &write_set, NULL, NULL)) <0)
      /* a signal or somesuch. */
      continue;

    /* Step 5a: Handle INET events */
    pptp_dispatch(conn, &read_set, &write_set);

    /* Step 5b: Handle new connection to UNIX socket */
    if (FD_ISSET(unix_sock, &read_set)) {
      /* New call! */
      struct sockaddr_un from;
      int len = sizeof(from);
      PPTP_CALL * call;
      struct local_callinfo *lci;
      int s;

      /* Accept the socket */
      FD_CLR (unix_sock, &read_set);
      if ((s = accept(unix_sock, (struct sockaddr *) &from, &len))<0) {
	warn("Socket not accepted: %s", strerror(errno));
	goto skip_accept;
      }
      /* Allocate memory for local call information structure. */
      if ((lci = malloc(sizeof(*lci))) == NULL) {
	warn("Out of memory."); close(s); goto skip_accept;
      }
      lci->unix_sock = s;

      /* Give the initiator time to write the PIDs while we open the call */
      call = pptp_call_open(conn, call_callback, phonenr);
      /* Read and store the associated pids */
      read(s, &lci->pid[0], sizeof(lci->pid[0]));
      read(s, &lci->pid[1], sizeof(lci->pid[1]));
      /* associate the local information with the call */
      pptp_call_closure_put(conn, call, (void *) lci);
      /* The rest is done on callback. */
      
      /* Keep alive; wait for close */
      retval = vector_insert(call_list, s, call); assert(retval);
      if (s > max_fd) max_fd = s;
      FD_SET(s, &call_set);
      first = 0;
    }
  skip_accept:
    /* Step 5c: Handle socket close */
    for (i=0; i<max_fd+1; i++)
      if (FD_ISSET(i, &read_set)) {
	/* close it */
	PPTP_CALL * call;
	retval = vector_search(call_list, i, &call);
	if (retval) {
	  struct local_callinfo *lci = pptp_call_closure_get(conn, call);
          log("Closing connection");
	  if(lci->pid[0]) kill(lci->pid[0], SIGTERM);
	  if(lci->pid[1]) kill(lci->pid[1], SIGTERM);
	  free(lci);
	  /* soft shutdown.  Callback will do hard shutdown later */
	  pptp_call_close(conn, call);
	  vector_remove(call_list, i);
	}
	FD_CLR(i, &call_set);
	close(i);
      }
  } while (vector_size(call_list)>0 || first);

shutdown:
  {
    fd_set read_set, write_set;

    /* warn("Shutdown"); */
    /* kill all open calls */
    for (i=0; i<vector_size(call_list); i++) {
      PPTP_CALL *call = vector_get_Nth(call_list, i);
      struct local_callinfo *lci = pptp_call_closure_get(conn, call);
      log("Closing connection");
      pptp_call_close(conn, call);
      if(lci->pid[0]) kill(lci->pid[0], SIGTERM);
      if(lci->pid[1]) kill(lci->pid[1], SIGTERM);
    }
    /* attempt to dispatch these messages */
    FD_ZERO(&read_set);
    FD_ZERO(&write_set);
    pptp_fd_set(conn, &read_set, &write_set, &max_fd);
    FD_ZERO(&read_set);
    pptp_dispatch(conn, &read_set, &write_set);
    if (i>0) sleep(2);
    /* no more open calls.  Close the connection. */
    pptp_conn_close(conn, PPTP_STOP_LOCAL_SHUTDOWN);
    FD_ZERO(&read_set);
    FD_ZERO(&write_set);
    pptp_fd_set(conn, &read_set, &write_set, &max_fd);
    FD_ZERO(&read_set);
    pptp_dispatch(conn, &read_set, &write_set);
    sleep(2);
    /* with extreme prejudice */
    pptp_conn_destroy(conn);
    vector_destroy(call_list);
  }
cleanup:
  close_inetsock(inet_sock, inetaddr);
  close_unixsock(unix_sock, inetaddr);
  return 0;
}
Exemplo n.º 17
0
void
FileRepSubProcess_Main()
{
	const char *statmsg;

	MemoryContext fileRepSubProcessMemoryContext;

	sigjmp_buf	local_sigjmp_buf;

	MyProcPid = getpid();

	MyStartTime = time(NULL);

	/*
	 * Create a PGPROC so we can use LWLocks in FileRep sub-processes.  The
	 * routine also register clean up at process exit
	 */
	InitAuxiliaryProcess();

	InitBufferPoolBackend();

	FileRepSubProcess_ConfigureSignals();

	/*
	 * If an exception is encountered, processing resumes here.
	 *
	 * See notes in postgres.c about the design of this coding.
	 */
	if (sigsetjmp(local_sigjmp_buf, 1) != 0)
	{
		/* Prevents interrupts while cleaning up */
		HOLD_INTERRUPTS();

		/* Report the error to the server log */
		EmitErrorReport();

		LWLockReleaseAll();

		if (FileRepPrimary_IsResyncManagerOrWorker())
		{
			LockReleaseAll(DEFAULT_LOCKMETHOD, false);
		}

		if (FileRepIsBackendSubProcess(fileRepProcessType))
		{
			AbortBufferIO();
			UnlockBuffers();

			/* buffer pins are released here: */
			ResourceOwnerRelease(CurrentResourceOwner,
								 RESOURCE_RELEASE_BEFORE_LOCKS,
								 false, true);
		}

		/*
		 * We can now go away.	Note that because we'll call InitProcess, a
		 * callback will be registered to do ProcKill, which will clean up
		 * necessary state.
		 */
		proc_exit(0);
	}

	/* We can now handle ereport(ERROR) */
	PG_exception_stack = &local_sigjmp_buf;

	PG_SETMASK(&UnBlockSig);

	/*
	 * Identify myself via ps
	 */

	statmsg = FileRepProcessTypeToString[fileRepProcessType];

	init_ps_display(statmsg, "", "", "");

	/* Create the memory context where cross-transaction state is stored */
	fileRepSubProcessMemoryContext = AllocSetContextCreate(TopMemoryContext,
														   "filerep subprocess memory context",
														   ALLOCSET_DEFAULT_MINSIZE,
														   ALLOCSET_DEFAULT_INITSIZE,
														   ALLOCSET_DEFAULT_MAXSIZE);

	MemoryContextSwitchTo(fileRepSubProcessMemoryContext);

	stateChangeRequestCounter++;

	FileRepSubProcess_ProcessSignals();

	switch (fileRepProcessType)
	{
		case FileRepProcessTypePrimarySender:
			FileRepPrimary_StartSender();
			break;

		case FileRepProcessTypeMirrorReceiver:
			FileRepMirror_StartReceiver();
			break;

		case FileRepProcessTypeMirrorConsumer:
		case FileRepProcessTypeMirrorConsumerWriter:
		case FileRepProcessTypeMirrorConsumerAppendOnly1:
			FileRepMirror_StartConsumer();
			break;

		case FileRepProcessTypeMirrorSenderAck:
			FileRepAckMirror_StartSender();
			break;

		case FileRepProcessTypePrimaryReceiverAck:
			FileRepAckPrimary_StartReceiver();
			break;

		case FileRepProcessTypePrimaryConsumerAck:
			FileRepAckPrimary_StartConsumer();
			break;

		case FileRepProcessTypePrimaryRecovery:
			FileRepSubProcess_InitProcess();

			/*
			 * At this point, database is starting up and xlog is not yet
			 * replayed.  Initializing relcache now is dangerous, a sequential
			 * scan of catalog tables may end up with incorrect hint bits.
			 * E.g. a committed transaction's dirty heap pages made it to disk
			 * but pg_clog update was still in memory and we crashed.  If a
			 * tuple inserted by this transaction is read during relcache
			 * initialization, status of the tuple's xmin will be incorrectly
			 * determined as "not commited" from pg_clog. And
			 * HEAP_XMIN_INVALID hint bit will be set, rendering the tuple
			 * perpetually invisible.  Relcache initialization must be
			 * deferred to only after all of xlog has been replayed.
			 */
			FileRepPrimary_StartRecovery();

			ResourceOwnerRelease(CurrentResourceOwner,
								 RESOURCE_RELEASE_BEFORE_LOCKS,
								 false, true);
			break;

		case FileRepProcessTypeResyncManager:
			FileRepSubProcess_InitProcess();
			FileRepPrimary_StartResyncManager();

			ResourceOwnerRelease(CurrentResourceOwner,
								 RESOURCE_RELEASE_BEFORE_LOCKS,
								 false, true);
			break;

		case FileRepProcessTypeResyncWorker1:
		case FileRepProcessTypeResyncWorker2:
		case FileRepProcessTypeResyncWorker3:
		case FileRepProcessTypeResyncWorker4:
			FileRepSubProcess_InitProcess();
			FileRepPrimary_StartResyncWorker();

			ResourceOwnerRelease(CurrentResourceOwner,
								 RESOURCE_RELEASE_BEFORE_LOCKS,
								 false, true);
			break;

		default:
			elog(PANIC, "unrecognized process type: %s(%d)",
				 statmsg, fileRepProcessType);
			break;
	}

	switch (FileRepSubProcess_GetState())
	{
		case FileRepStateShutdown:
		case FileRepStateReady:
			proc_exit(0);
			break;

		default:
			proc_exit(2);
			break;
	}
}
Exemplo n.º 18
0
int get_mem_layout (struct memchunk *chunk_list, int size)
{
    unsigned long endPage = 0xffffffff;
    unsigned int pageNum = endPage/PAGE_SIZE;
    unsigned long startPage = 0x00000000;
    int numberOfChunk=0;
    char str = 'a';
    int firstPage = 1;
    currentAddress = startPage;

    
//initial the handler   
	initialHandler();
	

    int page = 0;
    while(page<pageNum){
        page++;
        sigsetjmp(sigbuf,1);
        //check if the page of memory is accessable
        if(status ==0){
        
            if(firstPage ==1){
                firstPage =0;
                chunk_list[numberOfChunk].start = (void *) currentAddress;
				chunk_list[numberOfChunk].length = PAGE_SIZE; 
				chunk_list[numberOfChunk].RW=status-1;
				preStatus =status;
                status=0;
                currentAddress += PAGE_SIZE;
            }else{
                //check if the last page is not accessable
                if(preStatus ==0){
                    chunk_list[numberOfChunk].length+=PAGE_SIZE;
                    currentAddress += PAGE_SIZE;
                    preStatus=status;	
			        status=0;
                }else{
                    numberOfChunk+=1;
                    chunk_list[numberOfChunk].start = (void *) currentAddress;
				    chunk_list[numberOfChunk].length = PAGE_SIZE; 
				    chunk_list[numberOfChunk].RW=status-1;
				    currentAddress += PAGE_SIZE;
				    preStatus =status;
                    status=0;
                }
            }//check if the last page has different accessability with this one
        }else if((numberOfChunk<size) && (preStatus != status)&&(status!=0)){
            if(firstPage==1){
                firstPage = 0;
                chunk_list[numberOfChunk].start = (void *) currentAddress;
				chunk_list[numberOfChunk].length = PAGE_SIZE; 
				chunk_list[numberOfChunk].RW=status-1;
				preStatus =status;
                status=0;

				    	
            }else{
                numberOfChunk+=1;
                chunk_list[numberOfChunk].start = (void *) currentAddress;
				chunk_list[numberOfChunk].length = PAGE_SIZE; 
				chunk_list[numberOfChunk].RW=status-1;
				preStatus =status;
                status=0;

                
            }
            currentAddress += PAGE_SIZE;
        }else if((status!=0)&&(status == preStatus)){
            chunk_list[numberOfChunk].length += PAGE_SIZE;
            currentAddress += PAGE_SIZE;
            preStatus=status;	
			status=0;
			
        }
        
        
        //make sure if this is the end of page and return value
        if (currentAddress==(endPage-PAGE_SIZE+1) || numberOfChunk==size-1)
		{
			return numberOfChunk+1;
		}

		status=0;
		// check if it's readable   
		str = *((char *) currentAddress);
		status = 1;

		// check if it's writeable
		*((char *) currentAddress) = str;
		status = 2;
        
        
        

        
        
    
    
    }
    return numberOfChunk+1;

}
Exemplo n.º 19
0
VOIDCDECL mark_phase_young() 
{
  unsigned int i,j;
  unsigned long stack_size;
  ATerm *stackTop;
  ATerm *start, *stop;
  ProtEntry *prot;

#ifdef WIN32

  unsigned int r_eax, r_ebx, r_ecx, r_edx, \
    r_esi, r_edi, r_esp, r_ebp;
  ATerm reg[8], *real_term;

  __asm {
      /* Get the registers into local variables to check them
         for aterms later. */
    mov r_eax, eax
      mov r_ebx, ebx
      mov r_ecx, ecx
      mov r_edx, edx
      mov r_esi, esi
      mov r_edi, edi
      mov r_esp, esp
      mov r_ebp, ebp
      }
    /* Put the register-values into an array */
  reg[0] = (ATerm) r_eax;
  reg[1] = (ATerm) r_ebx;
  reg[2] = (ATerm) r_ecx;
  reg[3] = (ATerm) r_edx;
  reg[4] = (ATerm) r_esi;
  reg[5] = (ATerm) r_edi;
  reg[6] = (ATerm) r_esp;
  reg[7] = (ATerm) r_ebp;

  for(i=0; i<8; i++) {
    real_term = AT_isInsideValidTerm(reg[i]);
    if (real_term != NULL) {
      AT_markTerm_young(real_term);
    }
    if (AT_isValidSymbol((Symbol)reg[i])) {
       AT_markSymbol_young((Symbol)reg[i]);
    }
  }

    /* The register variables are on the stack aswell
       I set them to zero so they won't be processed again when
       the stack is traversed. The reg-array is also in the stack
       but that will be adjusted later */
  r_eax = 0;
  r_ebx = 0;
  r_ecx = 0;
  r_edx = 0;
  r_esi = 0;
  r_edi = 0;
  r_esp = 0;
  r_ebp = 0;

#else
  sigjmp_buf env;

    /* Traverse possible register variables */
  sigsetjmp(env,0);

  start = (ATerm *)((char *)env);
  stop  = ((ATerm *)(((char *)env) + sizeof(sigjmp_buf)));
  mark_memory_young(start, stop);
#endif

  stackTop = stack_top();
  start = MIN(stackTop, stackBot);
  stop  = MAX(stackTop, stackBot);

  stack_size = stop-start;
  STATS(stack_depth, stack_size);

  mark_memory_young(start, stop);

  /* Traverse protected terms */
  for(i=0; i<at_prot_table_size; i++) {
    ProtEntry *cur = at_prot_table[i];
    while(cur) {
      for(j=0; j<cur->size; j++) {
	if(cur->start[j])
	   AT_markTerm_young(cur->start[j]);
      }
      cur = cur->next;
    }
  }

  for (prot=at_prot_memory; prot != NULL; prot=prot->next) {
    mark_memory_young((ATerm *)prot->start, (ATerm *)(((char *)prot->start) + prot->size));
  }
    
  AT_markProtectedSymbols_young();

   /* Mark 'parked' symbol */
  if (AT_isValidSymbol(at_parked_symbol)) {
      /*fprintf(stderr,"mark_phase_young: AT_markSymbol_young(%d)\n",at_parked_symbol);*/
     AT_markSymbol_young(at_parked_symbol);
  }
}
Exemplo n.º 20
0
/*
 * Main entry point for checkpointer process
 *
 * This is invoked from AuxiliaryProcessMain, which has already created the
 * basic execution environment, but not enabled signals yet.
 */
void
CheckpointerMain(void)
{
	sigjmp_buf	local_sigjmp_buf;
	MemoryContext checkpointer_context;

	CheckpointerShmem->checkpointer_pid = MyProcPid;

	/*
	 * Properly accept or ignore signals the postmaster might send us
	 *
	 * Note: we deliberately ignore SIGTERM, because during a standard Unix
	 * system shutdown cycle, init will SIGTERM all processes at once.  We
	 * want to wait for the backends to exit, whereupon the postmaster will
	 * tell us it's okay to shut down (via SIGUSR2).
	 */
	pqsignal(SIGHUP, ChkptSigHupHandler);		/* set flag to read config
												 * file */
	pqsignal(SIGINT, ReqCheckpointHandler);		/* request checkpoint */
	pqsignal(SIGTERM, SIG_IGN); /* ignore SIGTERM */
	pqsignal(SIGQUIT, chkpt_quickdie);	/* hard crash time */
	pqsignal(SIGALRM, SIG_IGN);
	pqsignal(SIGPIPE, SIG_IGN);
	pqsignal(SIGUSR1, chkpt_sigusr1_handler);
	pqsignal(SIGUSR2, ReqShutdownHandler);		/* request shutdown */

	/*
	 * Reset some signals that are accepted by postmaster but not here
	 */
	pqsignal(SIGCHLD, SIG_DFL);
	pqsignal(SIGTTIN, SIG_DFL);
	pqsignal(SIGTTOU, SIG_DFL);
	pqsignal(SIGCONT, SIG_DFL);
	pqsignal(SIGWINCH, SIG_DFL);

	/* We allow SIGQUIT (quickdie) at all times */
	sigdelset(&BlockSig, SIGQUIT);

	/*
	 * Initialize so that first time-driven event happens at the correct time.
	 */
	last_checkpoint_time = last_xlog_switch_time = (pg_time_t) time(NULL);

	/*
	 * Create a resource owner to keep track of our resources (currently only
	 * buffer pins).
	 */
	CurrentResourceOwner = ResourceOwnerCreate(NULL, "Checkpointer");

	/*
	 * Create a memory context that we will do all our work in.  We do this so
	 * that we can reset the context during error recovery and thereby avoid
	 * possible memory leaks.  Formerly this code just ran in
	 * TopMemoryContext, but resetting that would be a really bad idea.
	 */
	checkpointer_context = AllocSetContextCreate(TopMemoryContext,
												 "Checkpointer",
												 ALLOCSET_DEFAULT_SIZES);
	MemoryContextSwitchTo(checkpointer_context);

	/*
	 * If an exception is encountered, processing resumes here.
	 *
	 * See notes in postgres.c about the design of this coding.
	 */
	if (sigsetjmp(local_sigjmp_buf, 1) != 0)
	{
		/* Since not using PG_TRY, must reset error stack by hand */
		error_context_stack = NULL;

		/* Prevent interrupts while cleaning up */
		HOLD_INTERRUPTS();

		/* Report the error to the server log */
		EmitErrorReport();

		/*
		 * These operations are really just a minimal subset of
		 * AbortTransaction().  We don't have very many resources to worry
		 * about in checkpointer, but we do have LWLocks, buffers, and temp
		 * files.
		 */
		LWLockReleaseAll();
		ConditionVariableCancelSleep();
		pgstat_report_wait_end();
		AbortBufferIO();
		UnlockBuffers();
		/* buffer pins are released here: */
		ResourceOwnerRelease(CurrentResourceOwner,
							 RESOURCE_RELEASE_BEFORE_LOCKS,
							 false, true);
		/* we needn't bother with the other ResourceOwnerRelease phases */
		AtEOXact_Buffers(false);
		AtEOXact_SMgr();
		AtEOXact_Files();
		AtEOXact_HashTables(false);

		/* Warn any waiting backends that the checkpoint failed. */
		if (ckpt_active)
		{
			SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
			CheckpointerShmem->ckpt_failed++;
			CheckpointerShmem->ckpt_done = CheckpointerShmem->ckpt_started;
			SpinLockRelease(&CheckpointerShmem->ckpt_lck);

			ckpt_active = false;
		}

		/*
		 * Now return to normal top-level context and clear ErrorContext for
		 * next time.
		 */
		MemoryContextSwitchTo(checkpointer_context);
		FlushErrorState();

		/* Flush any leaked data in the top-level context */
		MemoryContextResetAndDeleteChildren(checkpointer_context);

		/* Now we can allow interrupts again */
		RESUME_INTERRUPTS();

		/*
		 * Sleep at least 1 second after any error.  A write error is likely
		 * to be repeated, and we don't want to be filling the error logs as
		 * fast as we can.
		 */
		pg_usleep(1000000L);

		/*
		 * Close all open files after any error.  This is helpful on Windows,
		 * where holding deleted files open causes various strange errors.
		 * It's not clear we need it elsewhere, but shouldn't hurt.
		 */
		smgrcloseall();
	}

	/* We can now handle ereport(ERROR) */
	PG_exception_stack = &local_sigjmp_buf;

	/*
	 * Unblock signals (they were blocked when the postmaster forked us)
	 */
	PG_SETMASK(&UnBlockSig);

	/*
	 * Ensure all shared memory values are set correctly for the config. Doing
	 * this here ensures no race conditions from other concurrent updaters.
	 */
	UpdateSharedMemoryConfig();

	/*
	 * Advertise our latch that backends can use to wake us up while we're
	 * sleeping.
	 */
	ProcGlobal->checkpointerLatch = &MyProc->procLatch;

	/*
	 * Loop forever
	 */
	for (;;)
	{
		bool		do_checkpoint = false;
		int			flags = 0;
		pg_time_t	now;
		int			elapsed_secs;
		int			cur_timeout;
		int			rc;

		/* Clear any already-pending wakeups */
		ResetLatch(MyLatch);

		/*
		 * Process any requests or signals received recently.
		 */
		AbsorbFsyncRequests();

		if (got_SIGHUP)
		{
			got_SIGHUP = false;
			ProcessConfigFile(PGC_SIGHUP);

			/*
			 * Checkpointer is the last process to shut down, so we ask it to
			 * hold the keys for a range of other tasks required most of which
			 * have nothing to do with checkpointing at all.
			 *
			 * For various reasons, some config values can change dynamically
			 * so the primary copy of them is held in shared memory to make
			 * sure all backends see the same value.  We make Checkpointer
			 * responsible for updating the shared memory copy if the
			 * parameter setting changes because of SIGHUP.
			 */
			UpdateSharedMemoryConfig();
		}
		if (checkpoint_requested)
		{
			checkpoint_requested = false;
			do_checkpoint = true;
			BgWriterStats.m_requested_checkpoints++;
		}
		if (shutdown_requested)
		{
			/*
			 * From here on, elog(ERROR) should end with exit(1), not send
			 * control back to the sigsetjmp block above
			 */
			ExitOnAnyError = true;
			/* Close down the database */
			ShutdownXLOG(0, 0);
			/* Normal exit from the checkpointer is here */
			proc_exit(0);		/* done */
		}

		/*
		 * Force a checkpoint if too much time has elapsed since the last one.
		 * Note that we count a timed checkpoint in stats only when this
		 * occurs without an external request, but we set the CAUSE_TIME flag
		 * bit even if there is also an external request.
		 */
		now = (pg_time_t) time(NULL);
		elapsed_secs = now - last_checkpoint_time;
		if (elapsed_secs >= CheckPointTimeout)
		{
			if (!do_checkpoint)
				BgWriterStats.m_timed_checkpoints++;
			do_checkpoint = true;
			flags |= CHECKPOINT_CAUSE_TIME;
		}

		/*
		 * Do a checkpoint if requested.
		 */
		if (do_checkpoint)
		{
			bool		ckpt_performed = false;
			bool		do_restartpoint;

			/*
			 * Check if we should perform a checkpoint or a restartpoint. As a
			 * side-effect, RecoveryInProgress() initializes TimeLineID if
			 * it's not set yet.
			 */
			do_restartpoint = RecoveryInProgress();

			/*
			 * Atomically fetch the request flags to figure out what kind of a
			 * checkpoint we should perform, and increase the started-counter
			 * to acknowledge that we've started a new checkpoint.
			 */
			SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
			flags |= CheckpointerShmem->ckpt_flags;
			CheckpointerShmem->ckpt_flags = 0;
			CheckpointerShmem->ckpt_started++;
			SpinLockRelease(&CheckpointerShmem->ckpt_lck);

			/*
			 * The end-of-recovery checkpoint is a real checkpoint that's
			 * performed while we're still in recovery.
			 */
			if (flags & CHECKPOINT_END_OF_RECOVERY)
				do_restartpoint = false;

			/*
			 * We will warn if (a) too soon since last checkpoint (whatever
			 * caused it) and (b) somebody set the CHECKPOINT_CAUSE_XLOG flag
			 * since the last checkpoint start.  Note in particular that this
			 * implementation will not generate warnings caused by
			 * CheckPointTimeout < CheckPointWarning.
			 */
			if (!do_restartpoint &&
				(flags & CHECKPOINT_CAUSE_XLOG) &&
				elapsed_secs < CheckPointWarning)
				ereport(LOG,
						(errmsg_plural("checkpoints are occurring too frequently (%d second apart)",
				"checkpoints are occurring too frequently (%d seconds apart)",
									   elapsed_secs,
									   elapsed_secs),
						 errhint("Consider increasing the configuration parameter \"max_wal_size\".")));

			/*
			 * Initialize checkpointer-private variables used during
			 * checkpoint.
			 */
			ckpt_active = true;
			if (do_restartpoint)
				ckpt_start_recptr = GetXLogReplayRecPtr(NULL);
			else
				ckpt_start_recptr = GetInsertRecPtr();
			ckpt_start_time = now;
			ckpt_cached_elapsed = 0;

			/*
			 * Do the checkpoint.
			 */
			if (!do_restartpoint)
			{
				CreateCheckPoint(flags);
				ckpt_performed = true;
			}
			else
				ckpt_performed = CreateRestartPoint(flags);

			/*
			 * After any checkpoint, close all smgr files.  This is so we
			 * won't hang onto smgr references to deleted files indefinitely.
			 */
			smgrcloseall();

			/*
			 * Indicate checkpoint completion to any waiting backends.
			 */
			SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
			CheckpointerShmem->ckpt_done = CheckpointerShmem->ckpt_started;
			SpinLockRelease(&CheckpointerShmem->ckpt_lck);

			if (ckpt_performed)
			{
				/*
				 * Note we record the checkpoint start time not end time as
				 * last_checkpoint_time.  This is so that time-driven
				 * checkpoints happen at a predictable spacing.
				 */
				last_checkpoint_time = now;
			}
			else
			{
				/*
				 * We were not able to perform the restartpoint (checkpoints
				 * throw an ERROR in case of error).  Most likely because we
				 * have not received any new checkpoint WAL records since the
				 * last restartpoint. Try again in 15 s.
				 */
				last_checkpoint_time = now - CheckPointTimeout + 15;
			}

			ckpt_active = false;
		}

		/* Check for archive_timeout and switch xlog files if necessary. */
		CheckArchiveTimeout();

		/*
		 * Send off activity statistics to the stats collector.  (The reason
		 * why we re-use bgwriter-related code for this is that the bgwriter
		 * and checkpointer used to be just one process.  It's probably not
		 * worth the trouble to split the stats support into two independent
		 * stats message types.)
		 */
		pgstat_send_bgwriter();

		/*
		 * Sleep until we are signaled or it's time for another checkpoint or
		 * xlog file switch.
		 */
		now = (pg_time_t) time(NULL);
		elapsed_secs = now - last_checkpoint_time;
		if (elapsed_secs >= CheckPointTimeout)
			continue;			/* no sleep for us ... */
		cur_timeout = CheckPointTimeout - elapsed_secs;
		if (XLogArchiveTimeout > 0 && !RecoveryInProgress())
		{
			elapsed_secs = now - last_xlog_switch_time;
			if (elapsed_secs >= XLogArchiveTimeout)
				continue;		/* no sleep for us ... */
			cur_timeout = Min(cur_timeout, XLogArchiveTimeout - elapsed_secs);
		}

		rc = WaitLatch(MyLatch,
					   WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
					   cur_timeout * 1000L /* convert to ms */,
					   WAIT_EVENT_CHECKPOINTER_MAIN);

		/*
		 * Emergency bailout if postmaster has died.  This is to avoid the
		 * necessity for manual cleanup of all postmaster children.
		 */
		if (rc & WL_POSTMASTER_DEATH)
			exit(1);
	}
}
Exemplo n.º 21
0
ssize_t
dg_send_recv(int fd, const void *outbuff, size_t outbytes,
			 void *inbuff, size_t inbytes,
			 const SA *destaddr, socklen_t destlen)
{
	ssize_t			n;
	struct iovec	iovsend[2], iovrecv[2];

	if (rttinit == 0) {
		rtt_init(&rttinfo);		/* first time we're called */
		rttinit = 1;
		rtt_d_flag = 1;
	}

	sendhdr.seq++;
	msgsend.msg_name = destaddr;
	msgsend.msg_namelen = destlen;
	msgsend.msg_iov = iovsend;
	msgsend.msg_iovlen = 2;
	iovsend[0].iov_base = &sendhdr;
	iovsend[0].iov_len = sizeof(struct hdr);
	iovsend[1].iov_base = outbuff;
	iovsend[1].iov_len = outbytes;

	msgrecv.msg_name = NULL;
	msgrecv.msg_namelen = 0;
	msgrecv.msg_iov = iovrecv;
	msgrecv.msg_iovlen = 2;
	iovrecv[0].iov_base = &recvhdr;
	iovrecv[0].iov_len = sizeof(struct hdr);
	iovrecv[1].iov_base = inbuff;
	iovrecv[1].iov_len = inbytes;
/* end dgsendrecv1 */

/* include dgsendrecv2 */
	if (signal(SIGALRM, sig_alrm) == SIG_ERR) {
		perror("signal error");
		exit(1);
	}
	rtt_newpack(&rttinfo);		/* initialize for this packet */

sendagain:
#ifdef	RTT_DEBUG
	fprintf(stderr, "send %4d: ", sendhdr.seq);
#endif
	sendhdr.ts = rtt_ts(&rttinfo);
	int nbytes = 0;	/* must first figure out what return value should be */
	int i;
	for (i = 0; i < msgsend.msg_iovlen; i++)
		nbytes += msgsend.msg_iov[i].iov_len;
	if (sendmsg(fd, &msgsend, 0) != nbytes) {
		perror("sendmsg error");
		exit(1);
	}

	alarm(rtt_start(&rttinfo));	/* calc timeout value & start timer */
#ifdef	RTT_DEBUG
	rtt_debug(&rttinfo);
#endif

	if (sigsetjmp(jmpbuf, 1) != 0) {
		if (rtt_timeout(&rttinfo) < 0) {
			fprintf(stderr, "dg_send_recv: no response from server, giving up\n");
			rttinit = 0;	/* reinit in case we're called again */
			errno = ETIMEDOUT;
			return(-1);
		}
#ifdef	RTT_DEBUG
		fprintf(stderr, "dg_send_recv: timeout, retransmitting\n");
#endif
		goto sendagain;
	}

	do {
		if ((n = recvmsg(fd, &msgrecv, 0)) < 0) {
			perror("recvmsg error");
			exit(1);
		}
#ifdef	RTT_DEBUG
		fprintf(stderr, "recv %4d\n", recvhdr.seq);
#endif
	} while (n < sizeof(struct hdr) || recvhdr.seq != sendhdr.seq);

	alarm(0);			/* stop SIGALRM timer */
		/* 4calculate & store new RTT estimator values */
	rtt_stop(&rttinfo, rtt_ts(&rttinfo) - recvhdr.ts);

	return(n - sizeof(struct hdr));	/* return size of received datagram */
}
Exemplo n.º 22
0
/*
 * ~p command.
 */
static void
print_collf(FILE *collf, struct header *hp)
{
	char *lbuf = NULL;
	FILE *obuf = stdout;
	struct attachment *ap;
	char *cp;
	enum gfield	gf;
	size_t	linecnt, maxlines, linesize = 0, linelen, count, count2;

	(void)&obuf;
	(void)&cp;
	fflush(collf);
	rewind(collf);
	count = count2 = fsize(collf);
	if (is_a_tty[0] && is_a_tty[1] && (cp = value("crt")) != NULL) {
		for (linecnt = 0;
			fgetline(&lbuf, &linesize, &count2, NULL, collf, 0);
			linecnt++);
		rewind(collf);
		maxlines = (*cp == '\0' ? screensize() : atoi(cp));
		maxlines -= 4;
		if (hp->h_to)
			maxlines--;
		if (hp->h_subject)
			maxlines--;
		if (hp->h_cc)
			maxlines--;
		if (hp->h_bcc)
			maxlines--;
		if (hp->h_attach)
			maxlines--;
		maxlines -= myaddrs(hp) != NULL || hp->h_from != NULL;
		maxlines -= value("ORGANIZATION") != NULL ||
			hp->h_organization != NULL;
		maxlines -= value("replyto") != NULL || hp->h_replyto != NULL;
		maxlines -= value("sender") != NULL || hp->h_sender != NULL;
		if (linecnt > maxlines) {
			cp = get_pager();
			if (sigsetjmp(pipejmp, 1))
				goto endpipe;
			obuf = Popen(cp, "w", NULL, 1);
			if (obuf == NULL) {
				perror(cp);
				obuf = stdout;
			} else
				safe_signal(SIGPIPE, onpipe);
		}
	}
	fprintf(obuf, catgets(catd, CATSET, 62,
				"-------\nMessage contains:\n"));
	gf = GIDENT|GTO|GSUBJECT|GCC|GBCC|GNL|GFILES;
	if (value("fullnames"))
		gf |= GCOMMA;
	puthead(hp, obuf, gf, SEND_TODISP, CONV_NONE, NULL, NULL);
	while (fgetline(&lbuf, &linesize, &count, &linelen, collf, 1))
		prout(lbuf, linelen, obuf);
	if (hp->h_attach != NULL) {
		fputs(catgets(catd, CATSET, 63, "Attachments:"), obuf);
		for (ap = hp->h_attach; ap != NULL; ap = ap->a_flink) {
			if (ap->a_msgno)
				fprintf(obuf, " message %u", ap->a_msgno);
			else
				fprintf(obuf, " %s", ap->a_name);
			if (ap->a_flink)
				putc(',', obuf);
		}
		putc('\n', obuf);
	}
endpipe:
	if (obuf != stdout) {
		safe_signal(SIGPIPE, SIG_IGN);
		Pclose(obuf);
		safe_signal(SIGPIPE, dflpipe);
	}
	if (lbuf)
		free(lbuf);
}
Exemplo n.º 23
0
void
sendrequest(const char *cmd, char *local, char *remote, int printnames)
{
	struct stat st;
	struct timeval start, stop;
	register int c, d;
	FILE *volatile fin, *volatile dout = 0;
	int (*volatile closefunc)(FILE *);
	void (*volatile oldintr)(int);
	void (*volatile oldintp)(int);
	volatile long bytes = 0, hashbytes = HASHBYTES;
	char buf[BUFSIZ], *bufp;
	const char *volatile lmode;

#if 1
	printf("%s(%d): sendrequest(cmd=%s,local=%s,remote=%s)\n", __FILE__, __LINE__, cmd, local, remote);
#endif
	if (ftpverbose && printnames) {
		if (local && *local != '-')
			printf("local: %s ", local);
		if (remote)
			printf("remote: %s\n", remote);
	}
#if 0
	if (proxy) {
		proxtrans(cmd, local, remote);
		return;
	}
#endif
	if (curtype != type)
		changetype(type, 0);
	closefunc = NULL;
	oldintr = NULL;
	oldintp = NULL;
	lmode = "w";
	if (sigsetjmp(sendabort, 1)) {
		while (cpend) {
			(void) getreply(0);
		}
		if (data >= 0) {
			(void) close(data);
			data = -1;
		}
		if (oldintr)
			(void) signal(SIGINT,oldintr);
		if (oldintp)
			(void) signal(SIGPIPE,oldintp);
		code = -1;
		return;
	}
	oldintr = signal(SIGINT, abortsend);
	if (strcmp(local, "-") == 0)
		fin = stdin;
	else if (*local == '|') {
		oldintp = signal(SIGPIPE,SIG_IGN);
		fin = popen(local + 1, "r");
		if (fin == NULL) {
			perror(local + 1);
			(void) signal(SIGINT, oldintr);
			(void) signal(SIGPIPE, oldintp);
			code = -1;
			return;
		}
		closefunc = pclose;
	} else {
		fin = fopen(local, "r");
		if (fin == NULL) {
			fprintf(stderr, "local: %s: %s\n", local,
				strerror(errno));
			(void) signal(SIGINT, oldintr);
			code = -1;
			return;
		}
		closefunc = fclose;
		if (fstat(fileno(fin), &st) < 0 ||
		    (st.st_mode&S_IFMT) != S_IFREG) {
			fprintf(stdout, "%s: not a plain file.\n", local);
			(void) signal(SIGINT, oldintr);
			fclose(fin);
			code = -1;
			return;
		}
	}
	if (initconn()) {
		(void) signal(SIGINT, oldintr);
		if (oldintp)
			(void) signal(SIGPIPE, oldintp);
		code = -1;
		if (closefunc != NULL)
			(*closefunc)(fin);
		return;
	}
	if (sigsetjmp(sendabort, 1))
		goto abort;

	if (restart_point &&
	    (strcmp(cmd, "STOR") == 0 || strcmp(cmd, "APPE") == 0)) {
		if (fseek(fin, (long) restart_point, 0) < 0) {
			fprintf(stderr, "local: %s: %s\n", local,
				strerror(errno));
			restart_point = 0;
			if (closefunc != NULL)
				(*closefunc)(fin);
			return;
		}
		if (command("REST %ld", (long) restart_point)
			!= CONTINUE) {
			restart_point = 0;
			if (closefunc != NULL)
				(*closefunc)(fin);
			return;
		}
		restart_point = 0;
		lmode = "r+w";
	}
	if (remote) {
		if (command("%s %s", cmd, remote) != PRELIM) {
			(void) signal(SIGINT, oldintr);
			if (oldintp)
				(void) signal(SIGPIPE, oldintp);
			if (closefunc != NULL)
				(*closefunc)(fin);
			return;
		}
	} else
		if (command("%s", cmd) != PRELIM) {
			(void) signal(SIGINT, oldintr);
			if (oldintp)
				(void) signal(SIGPIPE, oldintp);
			if (closefunc != NULL)
				(*closefunc)(fin);
			return;
		}
	dout = dataconn(lmode);
	if (dout == NULL)
		goto abort;
	(void) gettimeofday(&start, (struct timezone *)0);
	oldintp = signal(SIGPIPE, SIG_IGN);
	switch (curtype) {

	case TYPE_I:
	case TYPE_L:
		errno = d = 0;
		while ((c = read(fileno(fin), buf, sizeof (buf))) > 0) {
			bytes += c;
			for (bufp = buf; c > 0; c -= d, bufp += d)
				if ((d = local_write(fileno(dout), bufp, c)) <= 0)
					break;
			if (hash) {
				while (bytes >= hashbytes) {
					(void) putchar('#');
					hashbytes += HASHBYTES;
				}
				(void) fflush(stdout);
			}
			if (tick && (bytes >= hashbytes)) {
				printf("\rBytes transferred: %ld", bytes);
				(void) fflush(stdout);
				while (bytes >= hashbytes)
					hashbytes += TICKBYTES;
			}
		}
		if (hash && (bytes > 0)) {
			if (bytes < HASHBYTES)
				(void) putchar('#');
			(void) putchar('\n');
			(void) fflush(stdout);
		}
		if (tick) {
			(void) printf("\rBytes transferred: %ld\n", bytes);
			(void) fflush(stdout);
		}
		if (c < 0)
			fprintf(stderr, "local: %s: %s\n", local,
				strerror(errno));
		if (d < 0) {
			if (errno != EPIPE) 
				perror("netout");
			bytes = -1;
		}
		break;

	case TYPE_A:
		while ((c = getc(fin)) != EOF) {
			if (c == '\n') {
				while (hash && (bytes >= hashbytes)) {
					(void) putchar('#');
					(void) fflush(stdout);
					hashbytes += HASHBYTES;
				}
				if (tick && (bytes >= hashbytes)) {
					(void) printf("\rBytes transferred: %ld",
						bytes);
					(void) fflush(stdout);
					while (bytes >= hashbytes)
						hashbytes += TICKBYTES;
				}
				if (ferror(dout))
					break;
				(void) putc('\r', dout);
				bytes++;
			}
			(void) putc(c, dout);
			bytes++;
	/*		if (c == '\r') {			  	*/
	/*		(void)	putc('\0', dout);  (* this violates rfc */
	/*			bytes++;				*/
	/*		}                          			*/     
		}
		if (hash) {
			if (bytes < hashbytes)
				(void) putchar('#');
			(void) putchar('\n');
			(void) fflush(stdout);
		}
		if (tick) {
			(void) printf("\rBytes transferred: %ld\n", bytes);
			(void) fflush(stdout);
		}
		if (ferror(fin))
			fprintf(stderr, "local: %s: %s\n", local,
				strerror(errno));
		if (ferror(dout)) {
			if (errno != EPIPE)
				perror("netout");
			bytes = -1;
		}
		break;
	}
	(void) gettimeofday(&stop, (struct timezone *)0);
	if (closefunc != NULL)
		(*closefunc)(fin);
	(void) fclose(dout);
	/* closes data as well, so discard it */
	data = -1;
	(void) getreply(0);
	(void) signal(SIGINT, oldintr);
	if (oldintp)
		(void) signal(SIGPIPE, oldintp);
	if (bytes > 0)
		ptransfer("sent", bytes, &start, &stop);
	return;
abort:
	(void) gettimeofday(&stop, (struct timezone *)0);
	(void) signal(SIGINT, oldintr);
	if (oldintp)
		(void) signal(SIGPIPE, oldintp);
	if (!cpend) {
		code = -1;
		return;
	}
	if (dout) {
		(void) fclose(dout);
	}
	if (data >= 0) {
		/* if it just got closed with dout, again won't hurt */
		(void) close(data);
		data = -1;
	}
	(void) getreply(0);
	code = -1;
	if (closefunc != NULL && fin != NULL)
		(*closefunc)(fin);
	if (bytes > 0)
		ptransfer("sent", bytes, &start, &stop);
}
Exemplo n.º 24
0
FILE *
collect(struct header *hp, int printheaders, struct message *mp,
		char *quotefile, int doprefix, int tflag)
{
	FILE *fbuf;
	struct ignoretab *quoteig;
	int lc, cc, escape, eofcount;
	int c, t;
	char *linebuf = NULL, *cp, *quote = NULL;
	size_t linesize;
	char *tempMail = NULL;
	int getfields;
	sigset_t oset, nset;
	long count;
	enum sendaction	action;
	sighandler_type	savedtop;
	const char tildehelp[] =
"-------------------- ~ ESCAPES ----------------------------\n\
~~              Quote a single tilde\n\
~@ [file ...]   Edit attachment list\n\
~b users        Add users to \"blind\" cc list\n\
~c users        Add users to cc list\n\
~d              Read in dead.letter\n\
~e              Edit the message buffer\n\
~f messages     Read in messages without indenting lines\n\
~F messages     Same as ~f, but keep all header lines\n\
~h              Prompt for to list, subject, cc, and \"blind\" cc list\n\
~r file         Read a file into the message buffer\n\
~p              Print the message buffer\n\
~q              Abort message composition and save text to dead.letter\n\
~m messages     Read in messages with each line indented\n\
~M messages     Same as ~m, but keep all header lines\n\
~s subject      Set subject\n\
~t users        Add users to to list\n\
~v              Invoke display editor on message\n\
~w file         Write message onto file\n\
~x              Abort message composition and discard text written so far\n\
~!command       Invoke the shell\n\
~:command       Execute a regular command\n\
-----------------------------------------------------------\n";

	(void) &escape;
	(void) &eofcount;
	(void) &getfields;
	(void) &tempMail;
	(void) &tflag;
	(void) &quote;

	collf = NULL;
	/*
	 * Start catching signals from here, but we're still die on interrupts
	 * until we're in the main loop.
	 */
	sigemptyset(&nset);
	sigaddset(&nset, SIGINT);
	sigaddset(&nset, SIGHUP);
	sigprocmask(SIG_BLOCK, &nset, &oset);
	handlerpush(collint);
	if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
		safe_signal(SIGINT, collint);
	if ((savehup = safe_signal(SIGHUP, SIG_IGN)) != SIG_IGN)
		safe_signal(SIGHUP, collhup);
	savetstp = safe_signal(SIGTSTP, collstop);
	savettou = safe_signal(SIGTTOU, collstop);
	savettin = safe_signal(SIGTTIN, collstop);
	if (sigsetjmp(collabort, 1)) {
		if (tempMail != NULL) {
			rm(tempMail);
			Ftfree(&tempMail);
		}
		goto err;
	}
	if (sigsetjmp(colljmp, 1)) {
		if (tempMail != NULL) {
			rm(tempMail);
			Ftfree(&tempMail);
		}
		goto err;
	}
	sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL);

	noreset++;
	if ((collf = Ftemp(&tempMail, "Rs", "w+", 0600, 1)) == NULL) {
		perror(catgets(catd, CATSET, 51, "temporary mail file"));
		goto err;
	}
	unlink(tempMail);
	Ftfree(&tempMail);

	if ((cp = value("MAILX_HEAD")) != NULL) {
		if (is_a_tty[0])
			putesc(cp, stdout);
		putesc(cp, collf);
	}

	/*
	 * If we are going to prompt for a subject,
	 * refrain from printing a newline after
	 * the headers (since some people mind).
	 */
	getfields = 0;
	if (!tflag) {
		t = GTO|GSUBJECT|GCC|GNL;
		if (value("fullnames"))
			t |= GCOMMA;
		if (hp->h_subject == NULL && value("interactive") != NULL &&
			    (value("ask") != NULL || value("asksub") != NULL))
			t &= ~GNL, getfields |= GSUBJECT;
		if (hp->h_to == NULL && value("interactive") != NULL)
			t &= ~GNL, getfields |= GTO;
		if (value("bsdcompat") == NULL && value("askatend") == NULL &&
				value("interactive")) {
			if (hp->h_bcc == NULL && value("askbcc"))
				t &= ~GNL, getfields |= GBCC;
			if (hp->h_cc == NULL && value("askcc"))
				t &= ~GNL, getfields |= GCC;
		}
		if (printheaders) {
			puthead(hp, stdout, t, SEND_TODISP, CONV_NONE,
					NULL, NULL);
			fflush(stdout);
		}
	}

	/*
	 * Quote an original message
	 */
	if (mp != NULL && (doprefix || (quote = value("quote")) != NULL)) {
		quoteig = allignore;
		action = SEND_QUOTE;
		if (doprefix) {
			quoteig = fwdignore;
			if ((cp = value("fwdheading")) == NULL)
				cp = "-------- Original Message --------";
			if (*cp) {
				fprintf(collf, "%s\n", cp);
				fprintf(stdout, "%s\n", cp);
			}
		} else if (strcmp(quote, "noheading") == 0) {
			/*EMPTY*/;
		} else if (strcmp(quote, "headers") == 0) {
			quoteig = ignore;
		} else if (strcmp(quote, "allheaders") == 0) {
			quoteig = NULL;
			action = SEND_QUOTE_ALL;
		} else {
			cp = hfield("from", mp);
			if (cp != NULL) {
				mime_write(cp, strlen(cp),
						collf, CONV_FROMHDR, TD_NONE,
						NULL, (size_t) 0,
						NULL, NULL);
				mime_write(cp, strlen(cp),
						stdout, CONV_FROMHDR, TD_NONE,
						NULL, (size_t) 0,
						NULL, NULL);
				fwrite(catgets(catd, CATSET, 52,
					" wrote:\n\n"), sizeof(char), 9, collf);
				fwrite(catgets(catd, CATSET, 52,
					" wrote:\n\n"), sizeof(char), 9, stdout);
			}
		}
		cp = value("indentprefix");
		if (cp != NULL && *cp == '\0')
			cp = "\t";
		send(mp, collf, quoteig, doprefix ? NULL : cp, action, NULL);
		send(mp, stdout, quoteig, doprefix ? NULL : cp, action, NULL);
	}

	if ((cp = value("escape")) != NULL)
		escape = *cp;
	else
		escape = ESCAPE;
	eofcount = 0;
	hadintr = 0;

	if (!sigsetjmp(colljmp, 1)) {
		if (getfields)
			grabh(hp, getfields, 1);
		if (quotefile != NULL) {
			if (include_file(NULL, quotefile, &lc, &cc, 1) != 0)
				goto err;
		}
	} else {
		/*
		 * Come here for printing the after-signal message.
		 * Duplicate messages won't be printed because
		 * the write is aborted if we get a SIGTTOU.
		 */
cont:
		if (hadintr) {
			fflush(stdout);
			fprintf(stderr, catgets(catd, CATSET, 53,
				"\n(Interrupt -- one more to kill letter)\n"));
		} else {
			printf(catgets(catd, CATSET, 54, "(continue)\n"));
			fflush(stdout);
		}
	}
	if (value("interactive") == NULL && tildeflag <= 0 && !is_a_tty[0] &&
			!tflag) {
		/*
		 * No tilde escapes, interrupts not expected. Copy
		 * standard input the simple way.
		 */
		linebuf = srealloc(linebuf, linesize = BUFSIZ);
		while ((count = fread(linebuf, sizeof *linebuf,
						linesize, stdin)) > 0) {
			if (fwrite(linebuf, sizeof *linebuf,
						count, collf) != count)
				goto err;
		}
		goto out;
	}
	for (;;) {
		colljmp_p = 1;
		count = readline(stdin, &linebuf, &linesize);
		colljmp_p = 0;
		if (count < 0) {
			if (value("interactive") != NULL &&
			    value("ignoreeof") != NULL && ++eofcount < 25) {
				printf(catgets(catd, CATSET, 55,
					"Use \".\" to terminate letter\n"));
				continue;
			}
			break;
		}
		if (tflag && count == 0) {
			rewind(collf);
			if (makeheader(collf, hp) != OKAY)
				goto err;
			rewind(collf);
			tflag = 0;
			continue;
		}
		eofcount = 0;
		hadintr = 0;
		if (linebuf[0] == '.' && linebuf[1] == '\0' &&
		    value("interactive") != NULL &&
		    (value("dot") != NULL || value("ignoreeof") != NULL))
			break;
		if (linebuf[0] != escape || (value("interactive") == NULL &&
					tildeflag == 0 ||
					tildeflag < 0)) {
			if (putline(collf, linebuf, count) < 0)
				goto err;
			continue;
		}
		c = linebuf[1];
		switch (c) {
		default:
			/*
			 * On double escape, just send the single one.
			 * Otherwise, it's an error.
			 */
			if (c == escape) {
				if (putline(collf, &linebuf[1], count - 1) < 0)
					goto err;
				else
					break;
			}
			printf(catgets(catd, CATSET, 56,
					"Unknown tilde escape.\n"));
			break;
#ifdef	DEBUG_COMMANDS
		case 'C':
			/*
			 * Dump core.
			 */
			core(NULL);
			break;
#endif	/* DEBUG_COMMANDS */
		case '!':
			/*
			 * Shell escape, send the balance of the
			 * line to sh -c.
			 */
			shell(&linebuf[2]);
			break;
		case ':':
		case '_':
			/*
			 * Escape to command mode, but be nice!
			 */
			inhook = 0;
			execute(&linebuf[2], 1, count - 2);
			goto cont;
		case '.':
			/*
			 * Simulate end of file on input.
			 */
			goto out;
		case 'x':
			/*
			 * Same as 'q', but no dead.letter saving.
			 */
			hadintr++;
			collint(0);
			exit(1);
			/*NOTREACHED*/
		case 'q':
			/*
			 * Force a quit of sending mail.
			 * Act like an interrupt happened.
			 */
			hadintr++;
			collint(SIGINT);
			exit(1);
			/*NOTREACHED*/
		case 'h':
			/*
			 * Grab a bunch of headers.
			 */
			do
				grabh(hp, GTO|GSUBJECT|GCC|GBCC,
						value("bsdcompat") != NULL &&
						value("bsdorder") != NULL);
			while (hp->h_to == NULL);
			goto cont;
		case 'H':
			/*
			 * Grab extra headers.
			 */
			do
				grabh(hp, GEXTRA, 0);
			while (check_from_and_sender(hp->h_from, hp->h_sender));
			goto cont;
		case 't':
			/*
			 * Add to the To list.
			 */
			while ((hp->h_to = checkaddrs(cat(hp->h_to,
					sextract(&linebuf[2], GTO|GFULL))))
				== NULL);
			break;
		case 's':
			/*
			 * Set the Subject list.
			 */
			cp = &linebuf[2];
			while (whitechar(*cp & 0377))
				cp++;
			hp->h_subject = savestr(cp);
			break;
		case '@':
			/*
			 * Edit the attachment list.
			 */
			if (linebuf[2] != '\0')
				hp->h_attach = append_attachments(hp->h_attach,
						&linebuf[2]);
			else
				hp->h_attach = edit_attachments(hp->h_attach);
			break;
		case 'c':
			/*
			 * Add to the CC list.
			 */
			hp->h_cc = checkaddrs(cat(hp->h_cc,
				sextract(&linebuf[2], GCC|GFULL)));
			break;
		case 'b':
			/*
			 * Add stuff to blind carbon copies list.
			 */
			hp->h_bcc = checkaddrs(cat(hp->h_bcc,
				sextract(&linebuf[2], GBCC|GFULL)));
			break;
		case 'd':
			strncpy(linebuf + 2, getdeadletter(), linesize - 2);
			linebuf[linesize-1]='\0';
			/*FALLTHRU*/
		case 'r':
		case '<':
			/*
			 * Invoke a file:
			 * Search for the file name,
			 * then open it and copy the contents to collf.
			 */
			cp = &linebuf[2];
			while (whitechar(*cp & 0377))
				cp++;
			if (*cp == '\0') {
				printf(catgets(catd, CATSET, 57,
						"Interpolate what file?\n"));
				break;
			}
			if (*cp == '!') {
				insertcommand(collf, cp + 1);
				break;
			}
			cp = expand(cp);
			if (cp == NULL)
				break;
			if (is_dir(cp)) {
				printf(catgets(catd, CATSET, 58,
						"%s: Directory\n"), cp);
				break;
			}
			if ((fbuf = Fopen(cp, "r")) == NULL) {
				perror(cp);
				break;
			}
			printf(catgets(catd, CATSET, 59, "\"%s\" "), cp);
			fflush(stdout);
			if (include_file(fbuf, cp, &lc, &cc, 0) != 0)
				goto err;
			printf(catgets(catd, CATSET, 60, "%d/%d\n"), lc, cc);
			break;
		case 'i':
			/*
			 * Insert an environment variable into the file.
			 */
			cp = &linebuf[2];
			while (whitechar(*cp & 0377))
				cp++;
			if ((cp = value(cp)) == NULL || *cp == '\0')
				break;
			if (is_a_tty[0])
				putesc(cp, stdout);
			putesc(cp, collf);
			break;
		case 'a':
		case 'A':
			/*
			 * Insert the contents of a signature variable.
			 */
			if ((cp = value(c == 'a' ? "sign" : "Sign")) != NULL &&
					*cp != '\0') {
				if (is_a_tty[0])
					putesc(cp, stdout);
				putesc(cp, collf);
			}
			break;
		case 'w':
			/*
			 * Write the message on a file.
			 */
			cp = &linebuf[2];
			while (blankchar(*cp & 0377))
				cp++;
			if (*cp == '\0') {
				fprintf(stderr, catgets(catd, CATSET, 61,
						"Write what file!?\n"));
				break;
			}
			if ((cp = expand(cp)) == NULL)
				break;
			rewind(collf);
			exwrite(cp, collf, 1);
			break;
		case 'm':
		case 'M':
		case 'f':
		case 'F':
			/*
			 * Interpolate the named messages, if we
			 * are in receiving mail mode.  Does the
			 * standard list processing garbage.
			 * If ~f is given, we don't shift over.
			 */
			if (forward(linebuf + 2, collf, c) < 0)
				goto err;
			goto cont;
		case '?':
			fputs(tildehelp, stdout);
			break;
		case 'p':
			/*
			 * Print out the current state of the
			 * message without altering anything.
			 */
			print_collf(collf, hp);
			goto cont;
		case '|':
			/*
			 * Pipe message through command.
			 * Collect output as new message.
			 */
			rewind(collf);
			mespipe(&linebuf[2]);
			goto cont;
		case 'v':
		case 'e':
			/*
			 * Edit the current message.
			 * 'e' means to use EDITOR
			 * 'v' means to use VISUAL
			 */
			rewind(collf);
			mesedit(c, value("editheaders") ? hp : NULL);
			goto cont;
		}
	}
	goto out;
err:
	if (collf != NULL) {
		Fclose(collf);
		collf = NULL;
	}
out:
	if (collf != NULL) {
		if ((cp = value("MAILX_TAIL")) != NULL) {
			if (is_a_tty[0])
				putesc(cp, stdout);
			fflush(collf);
			putesc(cp, collf);
		}
		rewind(collf);
	}
	handlerpop();
	noreset--;
	sigemptyset(&nset);
	sigaddset(&nset, SIGINT);
	sigaddset(&nset, SIGHUP);
#ifndef OLDBUG
	sigprocmask(SIG_BLOCK, &nset, (sigset_t *)NULL);
#else
	sigprocmask(SIG_BLOCK, &nset, &oset);
#endif
	safe_signal(SIGINT, saveint);
	safe_signal(SIGHUP, savehup);
	safe_signal(SIGTSTP, savetstp);
	safe_signal(SIGTTOU, savettou);
	safe_signal(SIGTTIN, savettin);
	sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL);
	return collf;
}
Exemplo n.º 25
0
int main(int argc, char **argv)
{
	int server, client;
	struct sockaddr_in serverAddress, clientAddress;
	char message[256];
	int stdfd[3];
	fpos_t stdpos[3];

	#ifdef __PS4__
	int libc = sceKernelLoadStartModule("libSceLibcInternal.sprx", 0, NULL, 0, 0, 0);
	sceKernelDlsym(libc, "__stdinp", (void **)&__stdinp_addr);
	sceKernelDlsym(libc, "__stdoutp", (void **)&__stdoutp_addr);
	sceKernelDlsym(libc, "__stderrp", (void **)&__stderrp_addr);
	sceKernelDlsym(libc, "__isthreaded", (void **)&__isthreaded_addr);
	__stdinp = *__stdinp_addr;
	__stdoutp = *__stdoutp_addr;
	__stderrp = *__stderrp_addr;
	__isthreaded = *__isthreaded_addr;
	#endif

	memset(&serverAddress, 0, sizeof(serverAddress));
	#ifdef __FreeBSD__ //parent of our __PS4__
	serverAddress.sin_len = sizeof(serverAddress);
	#endif
	serverAddress.sin_family = AF_INET;
	serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
	serverAddress.sin_port = htons(9025);

	memset(&clientAddress, 0, sizeof(clientAddress));

	server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(server < 0)
		return EXIT_FAILURE;

	if(bind(server, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0)
	{
		close(server);
		return EXIT_FAILURE;
	}

	if(listen(server, 10) < 0)
	{
		close(server);
		return EXIT_FAILURE;
	}

	while(1)
	{
		client = accept(server, NULL, NULL);

		if(client < 0)
			continue;

		stdIORedirect(client, stdfd, stdpos);

		struct sigaction action;

	    action.sa_handler = handler;
	    action.sa_flags = 0; // SA_NODEFER; /* repeated throws are caught */
	    sigemptyset(&action.sa_mask);
	    sigaction(SIGSEGV, &action, NULL);

		printf("loop\n");
		sigsetjmp(jmpbuf, 1);
		printf("oops\n");
		scanf("%s", message); // wait for input
		*((char *)0x42) = 42; /* provoke SIGSEGV */

		stdIOReset(stdfd, stdpos);

		close(client);
	}

	//close(server);
}
Exemplo n.º 26
0
/*
 * proc_exit callback to tear down the JVM
 */
static void _destroyJavaVM(int status, Datum dummy)
{
	if(s_javaVM != 0)
	{
		Invocation ctx;
#ifdef USE_PLJAVA_SIGHANDLERS

#if PG_VERSION_NUM >= 90300
		TimeoutId tid;
#else
		pqsigfunc saveSigAlrm;
#endif

		Invocation_pushInvocation(&ctx, false);
		if(sigsetjmp(recoverBuf, 1) != 0)
		{
			elog(DEBUG2,
				"needed to forcibly shut down the Java virtual machine");
			s_javaVM = 0;
			return;
		}

#if PG_VERSION_NUM >= 90300
		InitializeTimeouts();           /* establishes SIGALRM handler */
		tid = RegisterTimeout(USER_TIMEOUT, terminationTimeoutHandler);
#else
		saveSigAlrm = pqsignal(SIGALRM, terminationTimeoutHandler);
		enable_sig_alarm(5000, false);
#endif

		elog(DEBUG2, "shutting down the Java virtual machine");
		JNI_destroyVM(s_javaVM);

#if PG_VERSION_NUM >= 90300
		disable_timeout(tid, false);
#else
		disable_sig_alarm(false);
		pqsignal(SIGALRM, saveSigAlrm);
#endif

#else
		Invocation_pushInvocation(&ctx, false);
		elog(DEBUG2, "shutting down the Java virtual machine");
		JNI_destroyVM(s_javaVM);
#endif
		elog(DEBUG2, "done shutting down the Java virtual machine");
		s_javaVM = 0;
		currentInvocation = 0;

		/*
		 * Recover the handler of SIGUSR1 when initiate JVM failed.
		 * */
		if(s_oldHandlerFunc == NULL)
		{
			pqsignal(SIGUSR1, SIG_IGN);
		}
		else
		{
			pqsignal(SIGUSR1, s_oldHandlerFunc);
		}
		s_handlerSubstituted = false;
	}
}
Exemplo n.º 27
0
/*
 *  stress_msync()
 *	stress msync
 */
int stress_msync(
	uint64_t *const counter,
	const uint32_t instance,
	const uint64_t max_ops,
	const char *name)
{
	uint8_t *buf = NULL;
	const size_t page_size = stress_get_pagesize();
	const size_t min_size = 2 * page_size;
	size_t sz = min_size;
	ssize_t ret, rc = EXIT_SUCCESS;

	const pid_t pid = getpid();
	int fd = -1;
	char filename[PATH_MAX];

	ret = sigsetjmp(jmp_env, 1);
	if (ret) {
		pr_fail_err(name, "sigsetjmp");
		return EXIT_FAILURE;
	}
	if (stress_sighandler(name, SIGBUS, stress_sigbus_handler, NULL) < 0)
		return EXIT_FAILURE;

	if (!set_msync_bytes) {
		if (opt_flags & OPT_FLAGS_MAXIMIZE)
			opt_msync_bytes = MAX_MSYNC_BYTES;
		if (opt_flags & OPT_FLAGS_MINIMIZE)
			opt_msync_bytes = MIN_MSYNC_BYTES;
	}
	sz = opt_msync_bytes & ~(page_size - 1);
	if (sz < min_size)
		sz = min_size;

	/* Make sure this is killable by OOM killer */
	set_oom_adjustment(name, true);

	rc = stress_temp_dir_mk(name, pid, instance);
	if (rc < 0)
		return exit_status(-rc);

	(void)stress_temp_filename(filename, sizeof(filename),
		name, pid, instance, mwc32());

	(void)umask(0077);
	if ((fd = open(filename, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR)) < 0) {
		rc = exit_status(errno);
		pr_fail_err(name, "open");
		(void)unlink(filename);
		(void)stress_temp_dir_rm(name, pid, instance);

		return rc;
	}
	(void)unlink(filename);

	if (ftruncate(fd, sz) < 0) {
		pr_err(stderr, "%s: ftruncate failed, errno=%d (%s)\n",
			name, errno, strerror(errno));
		(void)close(fd);
		(void)stress_temp_dir_rm(name, pid, instance);

		return EXIT_FAILURE;
	}

	buf = (uint8_t *)mmap(NULL, sz,
		PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if (buf == MAP_FAILED) {
		pr_err(stderr, "%s: failed to mmap memory, errno=%d (%s)\n",
			name, errno, strerror(errno));
		rc = EXIT_NO_RESOURCE;
		goto err;
	}

	do {
		off_t offset;
		uint8_t val, data[page_size];

		ret = sigsetjmp(jmp_env, 1);
		if (ret) {
			/* Try again */
			continue;
		}
		/*
		 *  Change data in memory, msync to disk
		 */
		offset = (mwc64() % (sz - page_size)) & ~(page_size - 1);
		val = mwc8();

		memset(buf + offset, val, page_size);
		ret = msync(buf + offset, page_size, MS_SYNC);
		if (ret < 0) {
			pr_fail(stderr, "%s: msync MS_SYNC on "
				"offset %jd failed, errno=%d (%s)",
				name, (intmax_t)offset, errno, strerror(errno));
			goto do_invalidate;
		}
		ret = lseek(fd, offset, SEEK_SET);
		if (ret == (off_t)-1) {
			pr_err(stderr, "%s: cannot seet to offset %jd, "
				"errno=%d (%s)\n",
				name, (intmax_t)offset, errno, strerror(errno));
			rc = EXIT_NO_RESOURCE;
			break;
		}
		ret = read(fd, data, sizeof(data));
		if (ret < (ssize_t)sizeof(data)) {
			pr_fail(stderr, "%s: read failed, errno=%d (%s)\n",
				name, errno, strerror(errno));
			goto do_invalidate;
		}
		if (stress_page_check(data, val, sizeof(data)) < 0) {
			pr_fail(stderr, "%s: msync'd data in file different "
				"to data in memory\n", name);
		}

do_invalidate:
		/*
		 *  Now change data on disc, msync invalidate
		 */
		offset = (mwc64() % (sz - page_size)) & ~(page_size - 1);
		val = mwc8();

		memset(buf + offset, val, page_size);

		ret = lseek(fd, offset, SEEK_SET);
		if (ret == (off_t)-1) {
			pr_err(stderr, "%s: cannot seet to offset %jd, errno=%d (%s)\n",
				name, (intmax_t)offset, errno, strerror(errno));
			rc = EXIT_NO_RESOURCE;
			break;
		}
		ret = read(fd, data, sizeof(data));
		if (ret < (ssize_t)sizeof(data)) {
			pr_fail(stderr, "%s: read failed, errno=%d (%s)\n",
				name, errno, strerror(errno));
			goto do_next;
		}
		ret = msync(buf + offset, page_size, MS_INVALIDATE);
		if (ret < 0) {
			pr_fail(stderr, "%s: msync MS_INVALIDATE on "
				"offset %jd failed, errno=%d (%s)",
				name, (intmax_t)offset, errno, strerror(errno));
			goto do_next;
		}
		if (stress_page_check(buf + offset, val, sizeof(data)) < 0) {
			pr_fail(stderr, "%s: msync'd data in memory "
				"different to data in file\n", name);
		}
do_next:

		(*counter)++;
	} while (opt_do_run && (!max_ops || *counter < max_ops));

	(void)munmap((void *)buf, sz);
err:
	(void)close(fd);
	(void)stress_temp_dir_rm(name, pid, instance);

	if (sigbus_count)
		pr_inf(stdout, "%s: caught %" PRIu64 " SIGBUS signals\n",
			name, sigbus_count);
	return rc;
}
Exemplo n.º 28
0
Arquivo: sigio1.c Projeto: Tolchi/misc
int main(int argc, char *argv[]) {
  int fd[2], rc, n;
  char buf[100];

  pipe(fd);
  spawn_child(fd,"hello\n","world\n");
  close(fd[1]);

  /* request SIGIO to our pid when fd[0] is ready; see fcntl(2) */
  int fl = fcntl(fd[0], F_GETFL);
  fl |= O_ASYNC | O_NONBLOCK;
  fcntl(fd[0], F_SETFL, fl);
  fcntl(fd[0], F_SETOWN, getpid()); 

  /* block all signals. we stay blocked always except in sugsuspend */
  sigset_t all;
  sigfillset(&all);
  sigprocmask(SIG_SETMASK,&all,NULL);

  /* a smaller set of signals we'll block during sigsuspend */
  sigset_t ss;
  sigfillset(&ss);
  for(n=0; n < sizeof(sigs)/sizeof(*sigs); n++) sigdelset(&ss, sigs[n]);

  /* establish handlers for signals that'll be unblocked in sigsuspend */
  struct sigaction sa;
  sa.sa_handler=sighandler;  /* no fd information (not sa_sigaction)  */
  sa.sa_flags=0;             /* no extra information (not SA_SIGINFO* */
  sigfillset(&sa.sa_mask);
  for(n=0; n < sizeof(sigs)/sizeof(*sigs); n++) sigaction(sigs[n], &sa, NULL);

  /* here is a special line. we'll come back here whenever a signal happens */
  int signo = sigsetjmp(jmp,1);

  switch (signo) {
    case 0:
      /* initial setup. no signal yet */
      break;
    case SIGCHLD:
      /* this can happen before we get the last SIGIO,
         so fall through to grab any final pipe content */
      printf("got sigchld\n");
    case SIGIO:
      rc = read(fd[0], buf, sizeof(buf));
      if (rc > 0) printf("read: %.*s", rc, buf);
      else if (rc == 0) { close(fd[0]); goto done; }
      else if (rc == -1) {perror("read error"); close(fd[0]);}
      break;
    default:
      printf("got signal %d\n", signo);
      goto done;
      break;
  }

  /* wait for signals */
  sigsuspend(&ss);

  /* the only way we get past this point
   * is from the "goto done" above, because
   * sigsuspend waits for signals, and when
   * one arrives we longjmp back to sigsetjmp! */

done:
  return 0;
}
Exemplo n.º 29
0
int
main(volatile int argc, char **volatile argv)
{
	register char *cp;
	struct servent *sp;
	int top;
	struct passwd *pw = NULL;
	char homedir[MAXPATHLEN];

	tick = 0;

	sp = getservbyname("ftp", "tcp");
	if (sp == 0) {
		fprintf(stderr, "ftp: ftp/tcp: unknown service\n");
		exit(1);
	}
	ftp_port = sp->s_port;
	doglob = 1;
	interactive = 1;
	autologin = 1;
	passivemode = 0;

        cp = strrchr(argv[0], '/');
        cp = (cp == NULL) ? argv[0] : cp+1;
        if (strcmp(cp, "pftp") == 0)
            passivemode = 1;

#ifdef __USE_READLINE__
	/* 
	 * Set terminal type so libreadline can parse .inputrc correctly
	 */
	rl_terminal_name = getenv("TERM");
#endif

	argc--, argv++;
	while (argc > 0 && **argv == '-') {
		for (cp = *argv + 1; *cp; cp++)
			switch (*cp) {

			case 'd':
				options |= SO_DEBUG;
				debug++;
				break;
			
			case 'v':
				verbose++;
				break;

			case 't':
				traceflag++;
				break;

			case 'i':
				interactive = 0;
				break;

			case 'n':
				autologin = 0;
				break;

			case 'p':
				passivemode = 1;
				break;

			case 'g':
				doglob = 0;
				break;
				
			case 'e':
				rl_inhibit = 1;
				break;
				
			case 'h':
				usage();
				exit(0);

			default:
				fprintf(stdout,
				  "ftp: %c: unknown option\n", *cp);
				exit(1);
			}
		argc--, argv++;
	}
	fromatty = isatty(fileno(stdin));
	if (fromatty)
		verbose++;
	cpend = 0;	/* no pending replies */
	proxy = 0;	/* proxy not active */
	crflag = 1;	/* strip c.r. on ascii gets */
	sendport = -1;	/* not using ports */
	/*
	 * Set up the home directory in case we're globbing.
	 */
	cp = getlogin();
	if (cp != NULL) {
		pw = getpwnam(cp);
	}
	if (pw == NULL)
		pw = getpwuid(getuid());
	if (pw != NULL) {
		strncpy(homedir, pw->pw_dir, sizeof(homedir));
		homedir[sizeof(homedir)-1] = 0;
		home = homedir;
	}
	if (argc > 0) {
		if (sigsetjmp(toplevel, 1))
			exit(0);
		(void) signal(SIGINT, intr);
		(void) signal(SIGPIPE, lostpeer);
		setpeer(argc + 1, argv - 1);
	}
	top = sigsetjmp(toplevel, 1) == 0;
	if (top) {
		(void) signal(SIGINT, intr);
		(void) signal(SIGPIPE, lostpeer);
	}
	for (;;) {
		cmdscanner(top);
		top = 1;
	}
}
Exemplo n.º 30
0
void OPENSSL_cpuid_setup(void)
{
    char *e;
    struct sigaction ill_oact, ill_act;
    sigset_t oset;
    static int trigger = 0;

    if (trigger)
        return;
    trigger = 1;

    sigfillset(&all_masked);
    sigdelset(&all_masked, SIGILL);
    sigdelset(&all_masked, SIGTRAP);
#ifdef SIGEMT
    sigdelset(&all_masked, SIGEMT);
#endif
    sigdelset(&all_masked, SIGFPE);
    sigdelset(&all_masked, SIGBUS);
    sigdelset(&all_masked, SIGSEGV);

    if ((e = getenv("OPENSSL_ppccap"))) {
        OPENSSL_ppccap_P = strtoul(e, NULL, 0);
        return;
    }

    OPENSSL_ppccap_P = 0;

#if defined(_AIX)
    if (sizeof(size_t) == 4) {
        struct utsname uts;
# if defined(_SC_AIX_KERNEL_BITMODE)
        if (sysconf(_SC_AIX_KERNEL_BITMODE) != 64)
            return;
# endif
        if (uname(&uts) != 0 || atoi(uts.version) < 6)
            return;
    }
#endif

    memset(&ill_act, 0, sizeof(ill_act));
    ill_act.sa_handler = ill_handler;
    ill_act.sa_mask = all_masked;

    sigprocmask(SIG_SETMASK, &ill_act.sa_mask, &oset);
    sigaction(SIGILL, &ill_act, &ill_oact);

    if (sizeof(size_t) == 4) {
#ifdef __linux
        struct utsname uts;
        if (uname(&uts) == 0 && strcmp(uts.machine, "ppc64") == 0)
#endif
            if (sigsetjmp(ill_jmp, 1) == 0) {
                OPENSSL_ppc64_probe();
                OPENSSL_ppccap_P |= PPC_FPU64;
            }
    } else {
        /*
         * Wanted code detecting POWER6 CPU and setting PPC_FPU64
         */
    }

    if (sigsetjmp(ill_jmp, 1) == 0) {
        OPENSSL_altivec_probe();
        OPENSSL_ppccap_P |= PPC_ALTIVEC;
        if (sigsetjmp(ill_jmp, 1) == 0) {
            OPENSSL_crypto207_probe();
            OPENSSL_ppccap_P |= PPC_CRYPTO207;
        }
    }

    sigaction(SIGILL, &ill_oact, NULL);
    sigprocmask(SIG_SETMASK, &oset, NULL);
}