Пример #1
0
void monitor_run(iterator_t *it, pthread_mutex_t *lock)
{
	int_status_t *internal_status = xmalloc(sizeof(int_status_t));
	export_status_t *export_status = xmalloc(sizeof(export_status_t));

	while (!(zsend.complete && zrecv.complete)) {
		update_pcap_stats(lock);
		export_stats(internal_status, export_status, it);
		log_drop_warnings(export_status);
		check_min_hitrate(export_status);
		check_max_sendto_failures(export_status);
		if (!zconf.quiet) {
			lock_file(stderr);
			if (zconf.fsconf.app_success_index >= 0) {
				onscreen_appsuccess(export_status);
			} else {
				onscreen_generic(export_status);
			}
			unlock_file(stderr);
		}
		if (f) {
			update_status_updates_file(export_status, f);
		}
		sleep(UPDATE_INTERVAL);
	}
	if (!zconf.quiet) {
		lock_file(stderr);
		fflush(stderr);
		unlock_file(stderr);
	}
	if (f) {
		fflush(f);
		fclose(f);
	}
}
Пример #2
0
/**
* Start server identified by server name.
*
* A lock file is used to prevent multiple concurrent attempts to
* start a server. The lock file _must_ be removed before exiting,
* regardless of success/failure.
*
* @param svrname	server name (used as lookup)
* @return		0 on success; -1 on failure
*/
int
start_server(char *svrname) {
	char	lockpath[PATH_MAX], pidpath[PATH_MAX], sockpath[PATH_MAX];
	char	*conffile = NULL, *execfile = NULL;
	char	serveraddr[PATH_MAX], serverpath[PATH_MAX];
	int	pid, wpid;
	int	wst;

	// TODO: add checks to sprintf calls to prevent short printfs
	if ((sprintf(lockpath, "%s/.lock.%s", trackdir, svrname+1) < 0)
		|| (sprintf(pidpath, "%s/.pid.%s", trackdir, svrname+1) < 0)
		|| (sprintf(sockpath, "%s/%s", trackdir, svrname+1) < 0)
		|| (sprintf(serveraddr, "server:addr=%s", sockpath) < 0)) {
		return -1;
	}
	if (((execfile = russ_conf_get(conf, svrname, "execfile", NULL)) != NULL)
		&& (sprintf(serverpath, "server:path=%s", execfile) < 0)) {
		goto error;
	}
	if (((conffile = russ_conf_get(conf, svrname, "conffile", NULL)) == NULL)
		|| ((lock_file(lockpath, 100, 10000) < 0))) {		
		/* TODO: should svrname section be removed/disabled since it is invalid? */
		goto error;
	}

	/* double fork and exec new server */
	if ((pid = fork()) == 0) {
		setsid();
		signal(SIGHUP, SIG_IGN);
		if (fork() == 0) {
			put_pid(pidpath, getpid());
			russ_startl("", serverpath,
				"-f", conffile,
				"-c", serveraddr,
				(char *)NULL);
			exit(1);
		}
		exit(0);
	}
	/* TODO: is there is race here between wait and server connect-able? */
	if ((wpid = waitpid(pid, &wst, 0)) != pid) {
		goto unlock_and_error;
	}
	if (unlock_file(lockpath) < 0) {
		/* unexpected */
	}
	execfile = russ_free(execfile);
	conffile = russ_free(conffile);
	return 0;

unlock_and_error:
	unlock_file(lockpath);
error:
	execfile = russ_free(execfile);
	conffile = russ_free(conffile);
	return -1;
}
Пример #3
0
static void *srrd_create_thread (void *targs) /* {{{ */
{
  srrd_create_args_t *args = targs;
  char tmpfile[PATH_MAX];
  int status;

  status = lock_file (args->filename);
  if (status != 0)
  {
    if (status == EEXIST)
      NOTICE ("srrd_create_thread: File \"%s\" is already being created.",
          args->filename);
    else
      ERROR ("srrd_create_thread: Unable to lock file \"%s\".",
          args->filename);
    srrd_create_args_destroy (args);
    return (0);
  }

  ssnprintf (tmpfile, sizeof (tmpfile), "%s.async", args->filename);

  status = srrd_create (tmpfile, args->pdp_step, args->last_up,
      args->argc, (void *) args->argv);
  if (status != 0)
  {
    WARNING ("srrd_create_thread: srrd_create (%s) returned status %i.",
        args->filename, status);
    unlink (tmpfile);
    unlock_file (args->filename);
    srrd_create_args_destroy (args);
    return (0);
  }

  status = rename (tmpfile, args->filename);
  if (status != 0)
  {
    char errbuf[1024];
    ERROR ("srrd_create_thread: rename (\"%s\", \"%s\") failed: %s",
        tmpfile, args->filename,
        sstrerror (errno, errbuf, sizeof (errbuf)));
    unlink (tmpfile);
    unlock_file (args->filename);
    srrd_create_args_destroy (args);
    return (0);
  }

  DEBUG ("srrd_create_thread: Successfully created RRD file \"%s\".",
      args->filename);

  unlock_file (args->filename);
  srrd_create_args_destroy (args);

  return (0);
} /* }}} void *srrd_create_thread */
Пример #4
0
static DH *
get_dh1024(void)
{
  static const uint8_t dh1024_p[] = {
    0xB6, 0xBC, 0x30, 0x5B, 0xB4, 0xE5, 0x96, 0x62, 0x3F, 0x85, 0x5B, 0x1F,
    0x88, 0xD1, 0x12, 0xE1, 0x1D, 0x27, 0x69, 0x63, 0xAD, 0xB3, 0x4D, 0x23,
    0xB8, 0x4B, 0x1A, 0x90, 0xA6, 0x89, 0xD8, 0x5D, 0xFA, 0xF5, 0x8F, 0xFF,
    0xFF, 0xF4, 0x54, 0x3B, 0xCD, 0x5C, 0xAA, 0x79, 0x8B, 0x14, 0xBB, 0x84,
    0xAC, 0xEE, 0x94, 0x47, 0x76, 0xEC, 0x46, 0x75, 0x26, 0x48, 0x8C, 0x06,
    0x55, 0x27, 0x7F, 0xC0, 0xF1, 0xE8, 0x1F, 0xD2, 0xE4, 0x55, 0xAE, 0x78,
    0x11, 0x6E, 0xF1, 0x3B, 0xCD, 0x55, 0xE8, 0x17, 0xE9, 0x15, 0x7B, 0x05,
    0x91, 0x28, 0x9D, 0xD3, 0x40, 0x2E, 0x34, 0x03, 0x04, 0x2B, 0x2D, 0xC5,
    0x5C, 0x67, 0xC5, 0xF4, 0x28, 0x8E, 0x16, 0xAC, 0xDD, 0x68, 0x43, 0x66,
    0x51, 0xC1, 0x6F, 0x54, 0xB9, 0x22, 0xD8, 0x1A, 0x39, 0x6B, 0x0A, 0xC1,
    0x20, 0x5A, 0x9D, 0x31, 0x30, 0xE4, 0x0B, 0xC3,
  };
  static const uint8_t dh1024_g[] = {
    0x02,
  };
  DH *dh;
  if ((dh = DH_new()) == NULL)
    return NULL;
  if (dh->p) {
    BN_free(dh->p);
    dh->p = NULL;
  }
  if (dh->g) {
    BN_free(dh->g);
    dh->g = NULL;
  }

  dh->p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), NULL);
  if (!dh->p) {
    lock_file(stderr);
    fputs("Error in BN_bin2bn 1!\n", stderr);
    unlock_file(stderr);
    DH_free(dh);
    return NULL;
  }

  dh->g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), NULL);
  if (!dh->g) {
    lock_file(stderr);
    fputs("Error in BN_bin2bn 2!\n", stderr);
    unlock_file(stderr);
    DH_free(dh);
    return NULL;
  }

  return dh;
}
Пример #5
0
gboolean
mcview_hexedit_save_changes (mcview_t * view)
{
    int answer = 0;

    if (view->change_list == NULL)
        return TRUE;

    while (answer == 0)
    {
        int fp;
        char *text;
        struct hexedit_change_node *curr, *next;

#ifdef HAVE_ASSERT_H
        assert (view->filename_vpath != NULL);
#endif

        fp = mc_open (view->filename_vpath, O_WRONLY);
        if (fp != -1)
        {
            for (curr = view->change_list; curr != NULL; curr = next)
            {
                next = curr->next;

                if (mc_lseek (fp, curr->offset, SEEK_SET) == -1
                    || mc_write (fp, &(curr->value), 1) != 1)
                    goto save_error;

                /* delete the saved item from the change list */
                view->change_list = next;
                view->dirty++;
                mcview_set_byte (view, curr->offset, curr->value);
                g_free (curr);
            }

            view->change_list = NULL;

            if (view->locked)
                view->locked = unlock_file (view->filename_vpath);

            if (mc_close (fp) == -1)
                message (D_ERROR, _("Save file"),
                         _("Error while closing the file:\n%s\n"
                           "Data may have been written or not"), unix_error_string (errno));

            view->dirty++;
            return TRUE;
        }

      save_error:
        text = g_strdup_printf (_("Cannot save file:\n%s"), unix_error_string (errno));
        (void) mc_close (fp);

        answer = query_dialog (_("Save file"), text, D_ERROR, 2, _("&Retry"), _("&Cancel"));
        g_free (text);
    }

    return FALSE;
}
Пример #6
0
/**********************************************************************************************
 * 函数名	:set_hd_capacity()
 * 功能	:设置设备的磁盘容量值
 * 输入	:value:程序检测到的磁盘容量值MB为单位
 * 返回值	:0表示成功,负值表示出错
 **********************************************************************************************/
int set_hd_capacity(int value)
{
	dictionary      *ini;
	FILE *fp=NULL;
	ini=iniparser_load_lockfile(DEVINFO_PARA_FILE,1,&fp);
    	if (ini==NULL) {
            printf("init_devinfo() cannot parse ini file file [%s]", DEVINFO_PARA_FILE);
            return -1 ;
    	}
    	if(info.disk_capacity==value)
    	{
		iniparser_freedict(ini);
		if(fp!=NULL)
		{
                        unlock_file(fileno(fp));
                        fsync(fileno(fp));
                        fclose(fp);
		}
    		return 0;
    	}
	info.disk_capacity=value;
	//gtloginfo("test!!!!!!!!设置为%d\n",value);
	iniparser_setint(ini,"resource:disk_capacity",value);
	save_inidict_file(DEVINFO_PARA_FILE,ini,&fp);
	iniparser_freedict(ini);
	return 0;
}
Пример #7
0
static int
client_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
{
  char buf[256];
  X509 *err_cert;
  int err, depth;

  err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
  err = X509_STORE_CTX_get_error(x509_ctx);
  depth = X509_STORE_CTX_get_error_depth(x509_ctx);

  X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
  if (!preverify_ok) {
    lock_file(stderr);
    fprintf(stderr, "verify error:num=%d:%s:depth=%d:%s\n", err,
            X509_verify_cert_error_string(err), depth, buf);
    if (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT) {
      X509_NAME_oneline(X509_get_issuer_name(x509_ctx->current_cert), buf, 256);
      fprintf(stderr, "issuer= %s\n", buf);
    }
    unlock_file(stderr);
    return preverify_ok;
  }
  /* They've passed the preverification */
  /* if there are contents of the cert we wanted to verify, we'd do it here. 
   */
  return preverify_ok;
}
/*
Usage:  lookup name in the database, send reply back to the requester
Return: none
*/
void lookup_name(int sockfd, int dbfd, int logfd, struct name_prtl *name_request)
{
    int flag, result;
    char *attr;

    lock_file(dbfd);

    write_log(logfd, "[Info] lookup_name -- start to lookup a name in database");

    flag = database_lookup(dbfd, name_request->name, &attr);
    printf("[Info] lookup_name -- search database\n");
    if (flag == 0) { // found
        // send the attribute as the reply data back
        result = pkt_write(sockfd, 5, name_request->name, attr);
    } else if (flag == 1) {
        result = pkt_write(sockfd, 6, name_request->name, 
            "the name is not found");
    } else if (flag == -1) {
        result = pkt_write(sockfd, 8, name_request->name, 
            "fail to read the datebase, please try it later");
    }

    unlock_file(dbfd);
    write_log(logfd, "[Info] lookup_name -- finish lookup");
    
    if (result < 0) {
        fprintf(stderr, "[Error] lookup_name -- send reply fail\n");
        write_log(logfd, "[Error] lookup_name -- send reply fail");
    } else {
        fprintf(stdout, "[Info] lookup_name -- send reply ok: %s\n", 
            name_request->name);
        write_log(logfd, "[Info] lookup_name -- send reply ok");
    }
    return;
}
Пример #9
0
static void
ssl_errordump(const char *msg)
{
  lock_file(stderr);
  fputs(msg, stderr);
  fputc('\n', stderr);
  ERR_print_errors(bio_err);
  unlock_file(stderr);
}
Пример #10
0
int main(int ac, char **av)
{
	int fail = 0;

	char *msg;		/* message returned from parse_opts */

	/* parse standard options */
	if ((msg = parse_opts(ac, av, (option_t *) NULL, NULL)) != (char *)NULL) {
		tst_brkm(TBROK, cleanup, "OPTION PARSING ERROR - %s", msg);
	}

	setup();		/* global setup */

	/* //block1:    *//* Error: when no lock is set */
	tst_resm(TINFO, "Enter block 1");
	fail = 0;

#ifdef LINUX_FILE_REGION_LOCK
	if (fcntl(fd, F_RGETLK, &tl) < 0) {
		if (errno == EINVAL) {
			tst_resm(TINFO, "fcntl remote locking feature not "
				 "implemented in the kernel: exitting");
			cleanup();
		 /*NOTREACHED*/} else {
			tst_resm(TPASS, "fcntl on file failed: Test " "PASSED");
		}
	}

	/*
	 * Add a write lock to the middle of the file and unlock a section
	 * just before the lock
	 */
	if (do_lock(F_RSETLK, (short)F_WRLCK, (short)0, 10, 5) < 0) {
		tst_resm(TFAIL, "F_RSETLK WRLCK failed");
		fail = 1;
	}

	if (do_lock(F_RSETLK, (short)F_UNLCK, (short)0, 5, 5) < 0) {
		tst_resm(TFAIL, "F_RSETLK UNLOCK failed");
		fail = 1;
	}

	unlock_file();
#endif

	if (fail) {
		tst_resm(TFAIL, "Block 1 FAILED");
	} else {
		tst_resm(TPASS, "Block 1 PASSED");
	}
	close(fd);

	tst_resm(TINFO, "Exit block 1");
	cleanup();
	return 0;
}
Пример #11
0
/*
Usage:  add name operation, add the name to database if possible, 
        and send the reply back
Return: none
*/
void add_name(int sockfd, int dbfd, int logfd, struct name_prtl *name_request)
{
    int len, n, flag, result;
    char *buf;

    write_log(logfd, "[Info] add_name -- adding name to database");

    lock_file(dbfd);

    /* check wheter a same name is in database, and send reply */
    flag = is_in_database(dbfd, name_request->name);
    printf("[Info] add_name -- finish search database\n");
    write_log(logfd, "[Info] add_name -- finish search database");
    if (flag == 0) { /* found */
        pkt_write(sockfd, 8, name_request->name, 
            "the name is already in database");
        return;
    } else if (flag == -1) { /* fail to search */
        pkt_write(sockfd, 8, name_request->name, 
            "fail to read the datebase, please try it later");
        return;
    }

    /* not find existing name, execute the add operation */
    len = strlen(name_request->name) + 2 + strlen(name_request->data);
    if ((buf = (char*) malloc(len + 1)) == NULL) {
        perror("[Error] add_name: malloc error");
        write_log(logfd, "[Error] add_name: malloc error");
        return;
    }

    // generate the new line string
    sprintf(buf, "%s: %s", name_request->name, name_request->data);

    if ((n = write(dbfd, buf, len)) == -1) {
        result = pkt_write(sockfd, 8, name_request->name, 
            "fail to add the name pair into database");
    } else {
        result = pkt_write(sockfd, 7, name_request->name, 
            "ok, the name has been added into database");
    }
    unlock_file(dbfd);

    write_log(logfd, "[Info] add_name: finish adding");

    if (result < 0) {
        fprintf(stderr, "[Error] add_name -- send reply fail\n");
        write_log(logfd, "[Error] add_name -- send reply fail");
    } else {
        fprintf(stdout, "[Info] add_name -- send reply ok\n");
        write_log(logfd, "[Info] add_name -- send reply ok");
    }
    return;
}
Пример #12
0
void FileIODevice::send_data(const QByteArray &data)
{
    lock_file(true);
    _open_file(true);

    // At this point the settings file is ours for sole writing
    QT_IODevice::send_data(data);

    _close_file();
    unlock_file();
}
Пример #13
0
QByteArray FileIODevice::receive_data()
{
    lock_file(false);
    _open_file(false);

    QByteArray ret = QT_IODevice::receive_data();

    _close_file();
    unlock_file();

    _last_update_time = QFileInfo(FileName()).lastModified();

    return ret;
}
Пример #14
0
static void child(int num, unsigned char *shmptr)
{
	unsigned long cksum = 0;
	int i;

	read_lock(lockfd);
	for (i = 0; i < buffer_size; i++)
		cksum += *shmptr++;
	unlock_file(lockfd);

	*(checksum + (sizeof(unsigned long) * num)) = cksum;
	printf("\t\tchild (%02d): checksum %08lx\n", num,
	       *(checksum + (sizeof(unsigned long) * num)));
}
Пример #15
0
void update_name(int sockfd, int dbfd, int logfd, struct name_prtl *name_request)
{
    int len, n, flag, result;
    char *buf;

    lock_file(dbfd);
    write_log(logfd, "[Info] update_name -- start searching the database");

    flag = is_in_database(dbfd, name_request->name);
    printf("[Info] update_name -- finish searching database\n");
    if (flag == 0) { /* found */
        if (delete_line(dbfd, name_request->name) != 0) {
            result = pkt_write(sockfd, 8, name_request->name, 
            "fail to operate read or write the database");    
        } else { /* deleting the old line succeed */

            // write a new line to the datebase
            len = strlen(name_request->name) + 2 + strlen(name_request->data);
            if ((buf = (char*) malloc(len + 1)) == NULL) {
                perror("[Error] add_name -- malloc error");
                write_log(logfd, "[Error] add_name -- malloc error");
                return;
            }
            sprintf(buf, "%s: %s", name_request->name, name_request->data);

            if ((n = write(dbfd, buf, len)) == -1) {
                result = pkt_write(sockfd, 8, name_request->name, 
                    "fail to update the name pair in database");
            } else {
                result = pkt_write(sockfd, 7, name_request->name, 
                    "ok, the name pair has been updated");
            }
        }
    } else if (flag == 1) {
        result = pkt_write(sockfd, 8, name_request->name, 
            "the name is not found");
    } else if (flag == -1) {
        result = pkt_write(sockfd, 8, name_request->name, 
            "fail to read the datebase, please try it later");
    }

    unlock_file(dbfd);
    if (result < 0) {
        fprintf(stderr, "[Error] update_name -- send reply fail\n");
    } else {
        fprintf(stdout, "[Info] update_name -- send reply ok: %s\n", 
            name_request->name);
    }
    return;
}
Пример #16
0
Файл: logger.c Проект: Fale/zmap
static int LogLogVA(enum LogLevel level, const char *loggerName,
		const char *logMessage, va_list args)
{
	if (level <= log_output_level) {
		if (!log_output_stream) {
			log_output_stream = stderr;
		}
		// if logging to a shared output channel, then use a global
		// lock accross ZMap. Otherwise, if we're logging to a file,
		// only lockin with the module, in order to avoid having
		// corrupt log entries.
		if (log_output_stream == stdout || log_output_stream == stderr) {
			lock_file(log_output_stream);
		} else {
			pthread_mutex_lock(&mutex);
		}
		if (color) {
			COLOR(color_for_level(level));
		}

		const char *levelName = log_level_name[level];
		struct timeval now;
		char timestamp[256];
		gettimeofday(&now, NULL);
		time_t sec = now.tv_sec;
		struct tm* ptm = localtime(&sec);
		strftime(timestamp, 20, "%b %d %H:%M:%S", ptm);
		fprintf(log_output_stream, "%s.%03ld [%s] ",
				timestamp, (long) now.tv_usec/1000, levelName);
		if (loggerName) {
			fprintf(log_output_stream, "%s: ", loggerName);
		}
		if (logMessage) {
			vfprintf(log_output_stream, logMessage, args);
		}
		if (loggerName || logMessage) {
			fputs("\n", log_output_stream);
		}
		if (color) {
			COLOR(RESET);
		}
		fflush(log_output_stream);
		if (log_output_stream == stdout || log_output_stream == stderr) {
			unlock_file(log_output_stream);
		} else {
			pthread_mutex_unlock(&mutex);
		}
	}
	return EXIT_SUCCESS;
}
Пример #17
0
void
unlock_all_files (void)
{
  register Lisp_Object tail;
  register struct buffer *b;

  for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
    {
      b = XBUFFER (XCDR (XCAR (tail)));
      if (STRINGP (BVAR (b, file_truename)) && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b))
	{
	  unlock_file (BVAR (b, file_truename));
	}
    }
}
Пример #18
0
void
mcview_hexedit_free_change_list (mcview_t * view)
{
    struct hexedit_change_node *curr, *next;

    for (curr = view->change_list; curr != NULL; curr = next)
    {
        next = curr->next;
        g_free (curr);
    }
    view->change_list = NULL;

    if (view->locked)
        view->locked = unlock_file (view->filename_vpath);

    view->dirty++;
}
Пример #19
0
int main(int ac, char **av)
{
	int fail = 0;

	const char *msg;

	if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL)
		tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg);

	setup();		/* global setup */

	fail = 0;

#ifdef LINUX_FILE_REGION_LOCK
	if (fcntl(fd, F_RGETLK, &tl) == -1) {
		if (errno == EINVAL)
			tst_brkm(TCONF, cleanup,
				 "fcntl remote locking feature not implemented in "
				 "the kernel");
		else {
			/*
			 * FIXME (garrcoop): having it always pass on
			 * non-EINVAL is a bad test.
			 */
			tst_resm(TPASS, "fcntl on file failed");
		}
	}

	/*
	 * Add a write lock to the middle of the file and unlock a section
	 * just before the lock
	 */
	if (do_lock(F_RSETLK, F_WRLCK, 0, 10, 5) == -1)
		tst_resm(TFAIL, "F_RSETLK WRLCK failed");

	if (do_lock(F_RSETLK, F_UNLCK, 0, 5, 5) == -1)
		tst_resm(TFAIL | TERRNO, "F_RSETLK UNLOCK failed");

	unlock_file();
#else
	tst_resm(TCONF, "system doesn't have LINUX_LOCK_FILE_REGION support");
#endif

	cleanup();
	tst_exit();
}
Пример #20
0
/** Call SSL_accept and return the connection state.
 * \param ssl pointer to an SSL object.
 * \return ssl state flags indicating success, pending, or failure.
 */
int
ssl_accept(SSL *ssl)
{
  int ret;
  int state = 0;
  X509 *peer;
  char buf[256];

  if ((ret = SSL_accept(ssl)) <= 0) {
    switch (SSL_get_error(ssl, ret)) {
    case SSL_ERROR_WANT_READ:
      /* We must want for the socket to be readable, and then repeat
       * the call.
       */
      ssl_debugdump("SSL_accept wants read");
      state = MYSSL_RB | MYSSL_ACCEPT;
      break;
    case SSL_ERROR_WANT_WRITE:
      /* We must want for the socket to be writable, and then repeat
       * the call.
       */
      ssl_debugdump("SSL_accept wants write");
      state = MYSSL_WB | MYSSL_ACCEPT;
      break;
    default:
      /* Oops, don't know what's wrong */
      ssl_errordump("Error accepting connection");
      return -1;
    }
  } else {
    /* Successful accept - report it */
    if ((peer = SSL_get_peer_certificate(ssl))) {
      if (SSL_get_verify_result(ssl) == X509_V_OK) {
        /* The client sent a certificate which verified OK */
        X509_NAME_oneline(X509_get_subject_name(peer), buf, 256);
        lock_file(stderr);
        fprintf(stderr, "SSL client certificate accepted: %s", buf);
        unlock_file(stderr);
        state |= MYSSL_VERIFIED;
      }
    }
  }

  return state;
}
Пример #21
0
int main(int argc, char *argv[])
{
    char *file;
    FILE *fp;
    int c;
    
    if(argc < 2)
    {
	fprintf(stderr, "usage: lock.c-TEST file\n");
	exit(1);
    }
    file = argv[1];

    if((fp = fopen(file, "a")) == NULL)
    {
	fprintf(stderr, "lock.c-TEST: can't open %s: ", file);
	perror("");
	exit(1);
    }    

    printf("Locking %s ...\n", file);
    if(lock_file(fp))
    {
	fprintf(stderr, "lock.c-TEST: can't lock %s: ", file);
	perror("");
	exit(1);
    }    
    printf("%s locked.\n", file);

    printf("Press <Return> ..."); fflush(stdout);
    while((c = getchar()) != '\n') ;

    printf("Unlocking %s ...\n", file);
    if(unlock_file(fp))
    {
	fprintf(stderr, "lock.c-TEST: can't unlock %s: ", file);
	perror("");
	exit(1);
    }    
    printf("%s unlocked.\n", file);

    exit(0);
}
Пример #22
0
void do_cmd_appe(session_t *pses)
{
    //打开文件
    int fd = open(pses->arg, O_CREAT | O_WRONLY, 0666);
    if(fd < 0)
    {
        ftp_reply(pses->ctrl_fd, FTP_UPLOADFAIL, "Could not create file.");
        return;
    }

    //给文件加写锁
    if(lock_file_write(fd) == -1)
    {
        ftp_reply(pses->ctrl_fd, FTP_UPLOADFAIL, "Could not create file.");
        return;
    }

    int flag = upload_common(pses, fd, 1);

    //关闭数据套接字
    close(pses->data_fd);
    pses->data_fd = -1;

    //关闭文件
    unlock_file(fd);
    close(fd);

    if(flag == 0)
    {
        //226
        ftp_reply(pses->ctrl_fd, FTP_TRANSFEROK, "Transfer complete.");
    }
    else if(flag == -1)
    {
        ftp_reply(pses->ctrl_fd, FTP_BADSENDNET, "Failure writting to local file.");
    }
    else if(flag == -2)
    {
        //451
        ftp_reply(pses->ctrl_fd, FTP_BADSENDNET, "Failure reading from network stream.");
    }
}
Пример #23
0
/** Address to hostname lookup wrapper */
static struct evdns_request *
evdns_getnameinfo(struct evdns_base *base, const struct sockaddr *addr,
                  int flags, evdns_callback_type callback, void *data)
{
  if (addr->sa_family == AF_INET) {
    const struct sockaddr_in *a = (const struct sockaddr_in *) addr;
    return evdns_base_resolve_reverse(base, &a->sin_addr, flags, callback,
                                      data);
  } else if (addr->sa_family == AF_INET6) {
    const struct sockaddr_in6 *a = (const struct sockaddr_in6 *) addr;
    if (IN6_IS_ADDR_V4MAPPED(&a->sin6_addr)) {
      struct in_addr *a4 = (struct in_addr *) (a->sin6_addr.s6_addr + 12);
      return evdns_base_resolve_reverse(base, a4, flags, callback, data);
    } else
      return evdns_base_resolve_reverse_ipv6(base, &a->sin6_addr, flags,
                                             callback, data);
  } else {
    lock_file(stderr);
    fprintf(stderr, "info_slave: Attempt to resolve unknown socket family %d\n",
            addr->sa_family);
    unlock_file(stderr);
    return NULL;
  }
}
Пример #24
0
/*
Usage:  delete a name pair from database, send the reply
Return: none
*/
void delete_name(int sockfd, int dbfd, int logfd, struct name_prtl *name_request)
{
    int flag, result;

    lock_file(dbfd);
    write_log(logfd, "[Info] delete_name -- start searching the database");

    flag = is_in_database(dbfd, name_request->name);
    printf("[Info] delete_name -- finish searching database\n");
    if (flag == 0) { /* found */
        if (delete_line(dbfd, name_request->name) != 0) {
            result = pkt_write(sockfd, 8, name_request->name, 
            "fail to operate read or write the database");    
        } else { /* delete name pair */
            result = pkt_write(sockfd, 7, name_request->name, 
            "delete the name successfully");
        }
    } else if (flag == 1) { /* not find such name */
        result = pkt_write(sockfd, 8, name_request->name, 
            "the name is in database");
    } else if (flag == -1) { /* error */
        result = pkt_write(sockfd, 8, name_request->name, 
            "fail to read the datebase, please try it later");
    }

    unlock_file(dbfd);
    if (result < 0) {
        fprintf(stderr, "[Error] delete_name -- send reply fail\n");
        write_log(logfd, "[Error] delete_name -- send reply fail");
    } else {
        fprintf(stdout, "[Info] delete_name -- send reply ok: %s\n", 
            name_request->name);
        write_log(logfd, "[Info] delete_name -- send reply ok");
    }
    return;
}
Пример #25
0
/** Initialize the SSL context.
 * \return pointer to SSL context object.
 */
SSL_CTX *
ssl_init(char *private_key_file, char *ca_file, int req_client_cert)
{
  const SSL_METHOD *meth;       /* If this const gives you a warning, you're
                                   using an old version of OpenSSL. Walker, this means you! */
  /* uint8_t context[128]; */
  DH *dh;
  unsigned int reps = 1;

  if (!bio_err) {
    if (!SSL_library_init())
      return NULL;
    SSL_load_error_strings();
    /* Error write context */
    bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
  }

  lock_file(stderr);
  fputs("Seeding OpenSSL random number pool.\n", stderr);
  unlock_file(stderr);
  while (!RAND_status()) {
    /* At this point, a system with /dev/urandom or a EGD file in the usual
       places will have enough entropy. Otherwise, be lazy and use random numbers
       until it's satisfied. */
    uint32_t gibberish[4];
    int n;

    /* sfmt_fill_array32 requires a much larger array. */
    for (n = 0; n < 4; n++)
      gibberish[n] = sfmt_genrand_uint32(&rand_state);

    RAND_seed(gibberish, sizeof gibberish);

    reps += 1;
  }

  lock_file(stderr);
  fprintf(stderr, "Seeded after %u %s.\n", reps, reps > 1 ? "cycles" : "cycle");
  unlock_file(stderr);

  /* Set up SIGPIPE handler here? */

  /* Create context */
  meth = SSLv23_server_method();
  ctx = SSL_CTX_new(meth);

  /* Load keys/certs */
  if (private_key_file && *private_key_file) {
    if (!SSL_CTX_use_certificate_chain_file(ctx, private_key_file)) {
      ssl_errordump
        ("Unable to load server certificate - only anonymous ciphers supported.");
    }
    if (!SSL_CTX_use_PrivateKey_file(ctx, private_key_file, SSL_FILETYPE_PEM)) {
      ssl_errordump
        ("Unable to load private key - only anonymous ciphers supported.");
    }
  }

  /* Load trusted CAs */
  if (ca_file && *ca_file) {
    if (!SSL_CTX_load_verify_locations(ctx, ca_file, NULL)) {
      ssl_errordump("Unable to load CA certificates");
    } else {
      if (req_client_cert)
        SSL_CTX_set_verify(ctx,
                           SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
                           client_verify_callback);
      else
        SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, client_verify_callback);
#if (OPENSSL_VERSION_NUMBER < 0x0090600fL)
      SSL_CTX_set_verify_depth(ctx, 1);
#endif
    }
  }

  SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE | SSL_OP_ALL);
  SSL_CTX_set_mode(ctx,
                   SSL_MODE_ENABLE_PARTIAL_WRITE |
                   SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);

  /* Set up DH callback */
  dh = get_dh1024();
  SSL_CTX_set_tmp_dh(ctx, dh);
  /* The above function makes a private copy of this */
  DH_free(dh);

  /* Set the cipher list to the usual default list, except that
   * we'll allow anonymous diffie-hellman, too.
   */
  SSL_CTX_set_cipher_list(ctx, "ALL:ADH:RC4+RSA:+SSLv2:@STRENGTH");

  /* Set up session cache if we can */
  /*
     strncpy((char *) context, MUDNAME, 128);
     SSL_CTX_set_session_id_context(ctx, context, strlen(context));
   */

  return ctx;
}
Пример #26
0
int
main (int argc, char **argv)
{
  int c;
  bool running_suid;
  void *lockstate;
  char *scorefile;
  char *nl;
  const char *prefix, *user_prefix = NULL;
  struct stat buf;
  struct score_entry *scores;
  struct score_entry newscore;
  bool reverse = false;
  ptrdiff_t scorecount, scorealloc;
  ptrdiff_t max_scores = MAX_SCORES;

  srand (time (0));

  while ((c = getopt (argc, argv, "hrm:d:")) != -1)
    switch (c)
      {
      case 'h':
	usage (EXIT_SUCCESS);
	break;
      case 'd':
	user_prefix = optarg;
	break;
      case 'r':
	reverse = 1;
	break;
      case 'm':
	{
	  intmax_t m = strtoimax (optarg, 0, 10);
	  if (m < 0)
	    usage (EXIT_FAILURE);
	  max_scores = min (m, MAX_SCORES);
	}
	break;
      default:
	usage (EXIT_FAILURE);
      }

  if (argc - optind != 3)
    usage (EXIT_FAILURE);

  running_suid = (getuid () != geteuid ());

  prefix = get_prefix (running_suid, user_prefix);

  scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
  if (!scorefile)
    lose_syserr ("Couldn't allocate score file");

  strcpy (scorefile, prefix);
  strcat (scorefile, "/");
  strcat (scorefile, argv[optind]);

  newscore.score = strtoimax (argv[optind + 1], 0, 10);

  newscore.data = argv[optind + 2];
  if (strlen (newscore.data) > MAX_DATA_LEN)
    newscore.data[MAX_DATA_LEN] = '\0';
  nl = strchr (newscore.data, '\n');
  if (nl)
    *nl = '\0';

  newscore.username = get_user_id ();
  if (! newscore.username)
    lose_syserr ("Couldn't determine user id");

  if (stat (scorefile, &buf) < 0)
    lose_syserr ("Failed to access scores file");

  if (lock_file (scorefile, &lockstate) < 0)
    lose_syserr ("Failed to lock scores file");

  if (read_scores (scorefile, &scores, &scorecount, &scorealloc) < 0)
    {
      unlock_file (scorefile, lockstate);
      lose_syserr ("Failed to read scores file");
    }
  if (push_score (&scores, &scorecount, &scorealloc, &newscore) < 0)
    {
      unlock_file (scorefile, lockstate);
      lose_syserr ("Failed to add score");
    }
  sort_scores (scores, scorecount, reverse);
  /* Limit the number of scores.  If we're using reverse sorting, then
     also increment the beginning of the array, to skip over the
     *smallest* scores.  Otherwise, just decrementing the number of
     scores suffices, since the smallest is at the end. */
  if (scorecount > max_scores)
    {
      if (reverse)
	scores += scorecount - max_scores;
      scorecount = max_scores;
    }
  if (write_scores (scorefile, scores, scorecount) < 0)
    {
      unlock_file (scorefile, lockstate);
      lose_syserr ("Failed to write scores file");
    }
  if (unlock_file (scorefile, lockstate) < 0)
    lose_syserr ("Failed to unlock scores file");
  exit (EXIT_SUCCESS);
}
Пример #27
0
Файл: fconc.c Проект: shmmy/OS
int main(int argc, char ** argv)
{
    int OUT;
    int TMP;
    int i;
    const char * output;
    int duplicate = 0;
    int W_FLAGS = O_CREAT | O_WRONLY | O_TRUNC;
    int C_PERMS = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH ;

    if (argc == 1)
    {
        perror("Use at least 1 file name when calling fconc\n");
        exit(EX_USAGE);
    }
    if (argc == 2)
    {
        //No need to chance anything
        exit(0);
    }
    else
    {
        output = argv[argc-1];
    }

    for (i=1; i<(argc-1); i++)
    {
        if (strcmp (argv[i], output) ==0 )
        {
            duplicate = 1;
            break;
        }
    }

    if (duplicate)
    {

        TMP = open("/tmp/fconc.out.tmp",W_FLAGS,C_PERMS);
        if (TMP < 0)
        {
            perror("Error opening tmp file, is another instance running?\n");
            exit(EX_TEMPFAIL);
        }

        lock_file(TMP,F_WRLCK);
        for(i=1; i <(argc-1); i++)
        {
            write_file(TMP,argv[i]);
        }
        unlock_file(TMP);
        if ( close(TMP) < 0)
        {
            perror("Could  not close tmp file");
            exit(EX_IOERR);
        }
        OUT = open(output,W_FLAGS,C_PERMS);
        if (OUT < 0)
        {
            perror("Error handling output file\n");
            exit(EX_IOERR);
        }

        lock_file(OUT,F_WRLCK);
        write_file(OUT,"/tmp/fconc.out.tmp");
        unlock_file(OUT);
        if ( close (OUT) < 0 )
        {
            perror("Could not close output file");
            exit(EX_IOERR);
        }
        if (unlink("/tmp/fconc.out.tmp") != 0)
        {
            perror("Error deleting temporary file, please remove /tmp/fconc.out.tmp\n");
            exit(EX__BASE);
        }
    }

    else
    {
        OUT = open(output,W_FLAGS,C_PERMS);
        if (OUT < 0)
        {
            perror("Error handling output file\n");
            exit(EX_IOERR);
        }
        lock_file(OUT,F_WRLCK);
        for (i=1; i<(argc-1); i++)
        {
            write_file(OUT,argv[i]);
        }
        unlock_file(OUT);
        if ( close(OUT) < 0 )
        {
            perror("Could not close out file");
            exit(EX_IOERR);
        }
    }
    exit(EXIT_SUCCESS);
}
Пример #28
0
void potfile_write_append (hashcat_ctx_t *hashcat_ctx, const char *out_buf, u8 *plain_ptr, unsigned int plain_len)
{
  const hashconfig_t   *hashconfig   = hashcat_ctx->hashconfig;
  const potfile_ctx_t  *potfile_ctx  = hashcat_ctx->potfile_ctx;
  const user_options_t *user_options = hashcat_ctx->user_options;

  if (potfile_ctx->enabled == false) return;

  u8 *tmp_buf = potfile_ctx->tmp_buf;

  int tmp_len = 0;

  if (1)
  {
    const size_t out_len = strlen (out_buf);

    memcpy (tmp_buf + tmp_len, out_buf, out_len);

    tmp_len += out_len;

    tmp_buf[tmp_len] = hashconfig->separator;

    tmp_len += 1;
  }

  if (1)
  {
    const bool always_ascii = (hashconfig->hash_type & OPTS_TYPE_PT_ALWAYS_ASCII) ? true : false;

    if ((user_options->outfile_autohex == true) && (need_hexify (plain_ptr, plain_len, hashconfig->separator, always_ascii) == true))
    {
      tmp_buf[tmp_len++] = '$';
      tmp_buf[tmp_len++] = 'H';
      tmp_buf[tmp_len++] = 'E';
      tmp_buf[tmp_len++] = 'X';
      tmp_buf[tmp_len++] = '[';

      exec_hexify ((const u8 *) plain_ptr, plain_len, tmp_buf + tmp_len);

      tmp_len += plain_len * 2;

      tmp_buf[tmp_len++] = ']';
    }
    else
    {
      memcpy (tmp_buf + tmp_len, plain_ptr, plain_len);

      tmp_len += plain_len;
    }
  }

  tmp_buf[tmp_len] = 0;

  lock_file (potfile_ctx->fp);

  fprintf (potfile_ctx->fp, "%s" EOL, tmp_buf);

  fflush (potfile_ctx->fp);

  if (unlock_file (potfile_ctx->fp))
  {
    event_log_error (hashcat_ctx, "%s: Failed to unlock file.", potfile_ctx->filename);
  }
}
Пример #29
0
// one sender thread
int send_run(sock_t st, shard_t *s)
{
	log_trace("send", "send thread started");
	pthread_mutex_lock(&send_mutex);
	// Allocate a buffer to hold the outgoing packet
	char buf[MAX_PACKET_SIZE];
	memset(buf, 0, MAX_PACKET_SIZE);

	// OS specific per-thread init
	if (send_run_init(st)) {
		return -1;
	}

	// MAC address length in characters
	char mac_buf[(ETHER_ADDR_LEN * 2) + (ETHER_ADDR_LEN - 1) + 1];
	char *p = mac_buf;
	for(int i=0; i < ETHER_ADDR_LEN; i++) {
		if (i == ETHER_ADDR_LEN-1) {
			snprintf(p, 3, "%.2x", zconf.hw_mac[i]);
			p += 2;
		} else {
			snprintf(p, 4, "%.2x:", zconf.hw_mac[i]);
			p += 3;
		}
	}
	log_debug("send", "source MAC address %s",
			mac_buf);
	void *probe_data;
	if (zconf.probe_module->thread_initialize) {
		zconf.probe_module->thread_initialize(buf, zconf.hw_mac, zconf.gw_mac,
					      zconf.target_port, &probe_data);
	}
	pthread_mutex_unlock(&send_mutex);

	// adaptive timing to hit target rate
	uint32_t count = 0;
	uint32_t last_count = count;
	double last_time = now();
	uint32_t delay = 0;
	int interval = 0;
	uint32_t max_targets = s->state.max_targets;
	volatile int vi;
	if (zconf.rate > 0) {
		// estimate initial rate
		delay = 10000;
		for (vi = delay; vi--; )
			;
		delay *= 1 / (now() - last_time) / (zconf.rate / zconf.senders);
		interval = (zconf.rate / zconf.senders) / 20;
		last_time = now();
	}
	uint32_t curr = shard_get_cur_ip(s);
	int attempts = zconf.num_retries + 1;
	uint32_t idx = 0;
	while (1) {
		// adaptive timing delay
		if (delay > 0) {
			count++;
			for (vi = delay; vi--; )
				;
			if (!interval || (count % interval == 0)) {
				double t = now();
				delay *= (double)(count - last_count)
					/ (t - last_time) / (zconf.rate / zconf.senders);
				if (delay < 1)
					delay = 1;
				last_count = count;
				last_time = t;
			}
		}
		if (zrecv.complete) {
			s->cb(s->id, s->arg);
			break;
		}
		if (s->state.sent >= max_targets) {
			s->cb(s->id, s->arg);
			break;
		}
		if (zconf.max_runtime && zconf.max_runtime <= now() - zsend.start) {
			s->cb(s->id, s->arg);
			break;
		}
		if (curr == 0) {
			s->cb(s->id, s->arg);
			break;
		}
		s->state.sent++;
		for (int i=0; i < zconf.packet_streams; i++) {
			uint32_t src_ip = get_src_ip(curr, i);

		  	uint32_t validation[VALIDATE_BYTES/sizeof(uint32_t)];
			validate_gen(src_ip, curr, (uint8_t *)validation);
			zconf.probe_module->make_packet(buf, src_ip, curr, validation, i, probe_data);

			if (zconf.dryrun) {
				lock_file(stdout);
				zconf.probe_module->print_packet(stdout, buf);
				unlock_file(stdout);
			} else {
				int length = zconf.probe_module->packet_length;
				void *contents = buf + zconf.send_ip_pkts*sizeof(struct ether_header);
				for (int i = 0; i < attempts; ++i) {
					int rc = send_packet(st, contents, length, idx);
					if (rc < 0) {
						struct in_addr addr;
						addr.s_addr = curr;
						log_debug("send", "send_packet failed for %s. %s",
								  inet_ntoa(addr), strerror(errno));
						s->state.failures++;
					} else {
						break;
					}
				}
				idx++;
				idx &= 0xFF;
			}
		}

		curr = shard_get_next_ip(s);
	}
	if (zconf.dryrun) {
		pthread_mutex_lock(&send_mutex);
		fflush(stdout);
		pthread_mutex_unlock(&send_mutex);
	}
	log_debug("send", "thread %hu finished", s->id);
	return EXIT_SUCCESS;
}
Пример #30
0
int udp_global_initialize(struct state_conf *conf) {
	char *args, *c;
	int i;
	unsigned int n;

	FILE *inp;

	num_ports = conf->source_port_last - conf->source_port_first + 1;

	udp_send_msg = strdup(udp_send_msg_default);
	udp_send_msg_len = strlen(udp_send_msg);

	if (!(conf->probe_args && strlen(conf->probe_args) > 0))
		return(0);

	args = strdup(conf->probe_args);
	if (! args) exit(1);

	if (strcmp(args, "template-fields") == 0) {
		lock_file(stderr);
		fprintf(stderr, "%s",
			"List of allowed UDP template fields (name: description)\n\n");
		for (uint32_t i = 0; i < udp_num_template_field_types; ++i) {
			fprintf(stderr, "%s: %s\n",
				udp_payload_template_fields[i].name,
				udp_payload_template_fields[i].desc);
		}
		fprintf(stderr, "%s\n" ,"");
		unlock_file(stderr);
		exit(0);
	}

	c = strchr(args, ':');
	if (! c) {
		free(args);
		free(udp_send_msg);
		log_fatal("udp", udp_usage_error);
		exit(1);
	}

	*c++ = 0;

	if (strcmp(args, "text") == 0) {
		free(udp_send_msg);
		udp_send_msg = strdup(c);
		udp_send_msg_len = strlen(udp_send_msg);

	} else if (strcmp(args, "file") == 0 || strcmp(args, "template") == 0) {
		inp = fopen(c, "rb");
		if (!inp) {
			free(args);
			free(udp_send_msg);
			log_fatal("udp", "could not open UDP data file '%s'\n", c);
			exit(1);
		}
		free(udp_send_msg);
		udp_send_msg = xmalloc(MAX_UDP_PAYLOAD_LEN);
		udp_send_msg_len = fread(udp_send_msg, 1, MAX_UDP_PAYLOAD_LEN, inp);
		fclose(inp);

		if (strcmp(args, "template") == 0) {
			udp_send_substitutions = 1;
			udp_template = udp_template_load(udp_send_msg, udp_send_msg_len);
		}

	} else if (strcmp(args, "hex") == 0) {
		udp_send_msg_len = strlen(c) / 2;
		free(udp_send_msg);
		udp_send_msg = xmalloc(udp_send_msg_len);

		for (i=0; i < udp_send_msg_len; i++) {
			if (sscanf(c + (i*2), "%2x", &n) != 1) {
				free(args);
				free(udp_send_msg);
				log_fatal("udp", "non-hex character: '%c'", c[i*2]);
				exit(1);
			}
			udp_send_msg[i] = (n & 0xff);
		}
	} else {
		log_fatal("udp", udp_usage_error);
		free(udp_send_msg);
		free(args);
		exit(1);
	}

	if (udp_send_msg_len > MAX_UDP_PAYLOAD_LEN) {
		log_warn("udp", "warning: reducing UDP payload to %d "
				"bytes (from %d) to fit on the wire\n",
				MAX_UDP_PAYLOAD_LEN, udp_send_msg_len);
		udp_send_msg_len = MAX_UDP_PAYLOAD_LEN;
	}
	free(args);
	return EXIT_SUCCESS;
}