Example #1
0
File: tree.c Project: fanf2/exim
void
tree_walk(tree_node *p, void (*f)(uschar*, uschar*, void*), void *ctx)
{
if (p == NULL) return;
f(p->name, p->data.ptr, ctx);
if (p->left != NULL) tree_walk(p->left, f, ctx);
if (p->right != NULL) tree_walk(p->right, f, ctx);
}
FT_WORD * ft_linearize(TREE *wtree, MEM_ROOT *mem_root)
{
  FT_WORD *wlist,*p;
  FT_DOCSTAT docstat;
  DBUG_ENTER("ft_linearize");

  if ((wlist=(FT_WORD *) alloc_root(mem_root, sizeof(FT_WORD)*
                                    (1+wtree->elements_in_tree))))
  {
    docstat.list=wlist;
    docstat.uniq=wtree->elements_in_tree;
    docstat.sum=0;
    tree_walk(wtree,(tree_walk_action)&walk_and_copy,&docstat,left_root_right);
  }
  delete_tree(wtree);
  if (!wlist)
    DBUG_RETURN(NULL);

  docstat.list->pos=NULL;

  for (p=wlist;p->pos;p++)
  {
    p->weight=PRENORM_IN_USE;
  }

  for (p=wlist;p->pos;p++)
  {
    p->weight/=NORM_IN_USE;
  }

  DBUG_RETURN(wlist);
}
Example #3
0
File: tree.c Project: GCrean/wmamp
/*
 *  tree_walk
 */
void tree_walk(tree_node_t *root, 
                 void (*fp) (const char *key, void *, void *), 
                 void *arg)
{
restart:
    if (!root) {
        return;
    }

    tree_walk(root->right, fp, arg);

    if (root->key) {
        fp(root->key, root->data, arg);
    }

    /* Avoid tail-recursion:
       tree_walk (root->left, fp, arg);
     */
    root = root->left;
    goto restart;
}
Example #4
0
int
main(int argc, char *argv[])
{
	const char *path;
	int opt;

	Myname = argv[0];
	while ((opt = getopt(argc, argv, "FMd")) != -1) {
		switch (opt) {
		case 'F':
			pmem_fit_mode();
			break;

		case 'M':
			pmem_msync_mode();
			break;

		case 'd':
			Debug++;
			break;

		default:
			USAGE(NULL);
		}
	}

	if (optind >= argc)
		USAGE("No path given");
	path = argv[optind++];

	if (optind < argc)
		USAGE(NULL);

	tree_init(path, 0);

	tree_walk();

	exit(0);
}
Example #5
0
static int examine_log(my_string file_name, char **table_names)
{
  uint command,result,files_open;
  ulong access_time,length;
  my_off_t filepos;
  int lock_command,mi_result;
  char isam_file_name[FN_REFLEN],llbuff[21],llbuff2[21];
  uchar head[20];
  gptr	buff;
  struct test_if_open_param open_param;
  IO_CACHE cache;
  File file;
  FILE *write_file;
  enum ha_extra_function extra_command;
  TREE tree;
  struct file_info file_info,*curr_file_info;
  DBUG_ENTER("examine_log");

  if ((file=my_open(file_name,O_RDONLY,MYF(MY_WME))) < 0)
    DBUG_RETURN(1);
  write_file=0;
  if (write_filename)
  {
    if (!(write_file=my_fopen(write_filename,O_WRONLY,MYF(MY_WME))))
    {
      my_close(file,MYF(0));
      DBUG_RETURN(1);
    }
  }

  init_io_cache(&cache,file,0,READ_CACHE,start_offset,0,MYF(0));
  bzero((gptr) com_count,sizeof(com_count));
  init_tree(&tree,0,0,sizeof(file_info),(qsort_cmp2) file_info_compare,1,
	    (tree_element_free) file_info_free, NULL);
  VOID(init_key_cache(KEY_CACHE_SIZE));

  files_open=0; access_time=0;
  while (access_time++ != number_of_commands &&
	 !my_b_read(&cache,(byte*) head,9))
  {
    isamlog_filepos=my_b_tell(&cache)-9L;
    file_info.filenr= mi_uint2korr(head+1);
    isamlog_process=file_info.process=(long) mi_uint4korr(head+3);
    if (!opt_processes)
      file_info.process=0;
    result= mi_uint2korr(head+7);
    if ((curr_file_info=(struct file_info*) tree_search(&tree,&file_info)))
    {
      curr_file_info->accessed=access_time;
      if (update && curr_file_info->used && curr_file_info->closed)
      {
	if (reopen_closed_file(&tree,curr_file_info))
	{
	  command=sizeof(com_count)/sizeof(com_count[0][0])/3;
	  result=0;
	  goto com_err;
	}
      }
    }
    command=(uint) head[0];
    if (command < sizeof(com_count)/sizeof(com_count[0][0])/3 &&
	(!table_names[0] || (curr_file_info && curr_file_info->used)))
    {
      com_count[command][0]++;
      if (result)
	com_count[command][1]++;
    }
    switch ((enum myisam_log_commands) command) {
    case MI_LOG_OPEN:
      if (!table_names[0])
      {
	com_count[command][0]--;		/* Must be counted explicite */
	if (result)
	  com_count[command][1]--;
      }

      if (curr_file_info)
	printf("\nWarning: %s is opened with same process and filenumber\nMaybe you should use the -P option ?\n",
	       curr_file_info->show_name);
      if (my_b_read(&cache,(byte*) head,2))
	goto err;
      file_info.name=0;
      file_info.show_name=0;
      file_info.record=0;
      if (read_string(&cache,(gptr*) &file_info.name,
		      (uint) mi_uint2korr(head)))
	goto err;
      {
	uint i;
	char *pos,*to;

	/* Fix if old DOS files to new format */
	for (pos=file_info.name; (pos=strchr(pos,'\\')) ; pos++)
	  *pos= '/';

	pos=file_info.name;
	for (i=0 ; i < prefix_remove ; i++)
	{
	  char *next;
	  if (!(next=strchr(pos,'/')))
	    break;
	  pos=next+1;
	}
	to=isam_file_name;
	if (filepath)
	  to=convert_dirname(isam_file_name,filepath,NullS);
	strmov(to,pos);
	fn_ext(isam_file_name)[0]=0;	/* Remove extension */
      }
      open_param.name=file_info.name;
      open_param.max_id=0;
      VOID(tree_walk(&tree,(tree_walk_action) test_if_open,(void*) &open_param,
		     left_root_right));
      file_info.id=open_param.max_id+1;
      /*
       * In the line below +10 is added to accomodate '<' and '>' chars
       * plus '\0' at the end, so that there is place for 7 digits.
       * It is  improbable that same table can have that many entries in 
       * the table cache.
       * The additional space is needed for the sprintf commands two lines
       * below.
       */ 
      file_info.show_name=my_memdup(isam_file_name,
				    (uint) strlen(isam_file_name)+10,
				    MYF(MY_WME));
      if (file_info.id > 1)
	sprintf(strend(file_info.show_name),"<%d>",file_info.id);
      file_info.closed=1;
      file_info.accessed=access_time;
      file_info.used=1;
      if (table_names[0])
      {
	char **name;
	file_info.used=0;
	for (name=table_names ; *name ; name++)
	{
	  if (!strcmp(*name,isam_file_name))
	    file_info.used=1;			/* Update/log only this */
	}
      }
      if (update && file_info.used)
      {
	if (files_open >= max_files)
	{
	  if (close_some_file(&tree))
	    goto com_err;
	  files_open--;
	}
	if (!(file_info.isam= mi_open(isam_file_name,O_RDWR,
				      HA_OPEN_WAIT_IF_LOCKED)))
	  goto com_err;
	if (!(file_info.record=my_malloc(file_info.isam->s->base.reclength,
					 MYF(MY_WME))))
	  goto end;
	files_open++;
	file_info.closed=0;
	if (opt_myisam_with_debug)
	  file_info.isam->s->rnd= 0;
	else
	  file_info.isam->s->rnd= isamlog_process;
      }
      VOID(tree_insert(&tree,(gptr) &file_info,0));
      if (file_info.used)
      {
	if (verbose && !record_pos_file)
	  printf_log("%s: open -> %d",file_info.show_name, file_info.filenr);
	com_count[command][0]++;
	if (result)
	  com_count[command][1]++;
      }
      break;
    case MI_LOG_CLOSE:
      if (verbose && !record_pos_file &&
	  (!table_names[0] || (curr_file_info && curr_file_info->used)))
	printf_log("%s: %s -> %d",FILENAME(curr_file_info),
	       command_name[command],result);
      if (curr_file_info)
      {
	if (!curr_file_info->closed)
	  files_open--;
	VOID(tree_delete(&tree,(gptr) curr_file_info));
      }
      break;
    case MI_LOG_EXTRA:
      if (my_b_read(&cache,(byte*) head,1))
	goto err;
      extra_command=(enum ha_extra_function) head[0];
      if (verbose && !record_pos_file &&
	  (!table_names[0] || (curr_file_info && curr_file_info->used)))
	printf_log("%s: %s(%d) -> %d",FILENAME(curr_file_info),
		   command_name[command], (int) extra_command,result);
      if (update && curr_file_info && !curr_file_info->closed)
      {
	if (mi_extra(curr_file_info->isam, extra_command, 0) != (int) result)
	{
	  fflush(stdout);
	  VOID(fprintf(stderr,
		       "Warning: error %d, expected %d on command %s at %s\n",
		       my_errno,result,command_name[command],
		       llstr(isamlog_filepos,llbuff)));
	  fflush(stderr);
	}
      }
      break;
    case MI_LOG_DELETE:
      if (my_b_read(&cache,(byte*) head,8))
	goto err;
      filepos=mi_sizekorr(head);
      if (verbose && (!record_pos_file ||
		      ((record_pos == filepos || record_pos == NO_FILEPOS) &&
		       !cmp_filename(curr_file_info,record_pos_file))) &&
	  (!table_names[0] || (curr_file_info && curr_file_info->used)))
	printf_log("%s: %s at %ld -> %d",FILENAME(curr_file_info),
		   command_name[command],(long) filepos,result);
      if (update && curr_file_info && !curr_file_info->closed)
      {
	if (mi_rrnd(curr_file_info->isam,curr_file_info->record,filepos))
	{
	  if (!recover)
	    goto com_err;
	  if (verbose)
	    printf_log("error: Didn't find row to delete with mi_rrnd");
	  com_count[command][2]++;		/* Mark error */
	}
	mi_result=mi_delete(curr_file_info->isam,curr_file_info->record);
	if ((mi_result == 0 && result) ||
	    (mi_result && (uint) my_errno != result))
	{
	  if (!recover)
	    goto com_err;
	  if (mi_result)
	    com_count[command][2]++;		/* Mark error */
	  if (verbose)
	    printf_log("error: Got result %d from mi_delete instead of %d",
		       mi_result, result);
	}
      }
      break;
    case MI_LOG_WRITE:
    case MI_LOG_UPDATE:
      if (my_b_read(&cache,(byte*) head,12))
	goto err;
      filepos=mi_sizekorr(head);
      length=mi_uint4korr(head+8);
      buff=0;
      if (read_string(&cache,&buff,(uint) length))
	goto err;
      if ((!record_pos_file ||
	  ((record_pos == filepos || record_pos == NO_FILEPOS) &&
	   !cmp_filename(curr_file_info,record_pos_file))) &&
	  (!table_names[0] || (curr_file_info && curr_file_info->used)))
      {
	if (write_file &&
	    (my_fwrite(write_file,buff,length,MYF(MY_WAIT_IF_FULL | MY_NABP))))
	  goto end;
	if (verbose)
	  printf_log("%s: %s at %ld, length=%ld -> %d",
		     FILENAME(curr_file_info),
		     command_name[command], filepos,length,result);
      }
      if (update && curr_file_info && !curr_file_info->closed)
      {
	if (curr_file_info->isam->s->base.blobs)
	  fix_blob_pointers(curr_file_info->isam,buff);
	if ((enum myisam_log_commands) command == MI_LOG_UPDATE)
	{
	  if (mi_rrnd(curr_file_info->isam,curr_file_info->record,filepos))
	  {
	    if (!recover)
	    {
	      result=0;
	      goto com_err;
	    }
	    if (verbose)
	      printf_log("error: Didn't find row to update with mi_rrnd");
	    if (recover == 1 || result ||
		find_record_with_key(curr_file_info,buff))
	    {
	      com_count[command][2]++;		/* Mark error */
	      break;
	    }
	  }
	  mi_result=mi_update(curr_file_info->isam,curr_file_info->record,
			      buff);
	  if ((mi_result == 0 && result) ||
	      (mi_result && (uint) my_errno != result))
	  {
	    if (!recover)
	      goto com_err;
	    if (verbose)
	      printf_log("error: Got result %d from mi_update instead of %d",
			 mi_result, result);
	    if (mi_result)
	      com_count[command][2]++;		/* Mark error */
	  }
	}
	else
	{
	  mi_result=mi_write(curr_file_info->isam,buff);
	  if ((mi_result == 0 && result) ||
	      (mi_result && (uint) my_errno != result))
	  {
	    if (!recover)
	      goto com_err;
	    if (verbose)
	      printf_log("error: Got result %d from mi_write instead of %d",
			 mi_result, result);
	    if (mi_result)
	      com_count[command][2]++;		/* Mark error */
	  }
	  if (!recover && filepos != curr_file_info->isam->lastpos)
	  {
	    printf("error: Wrote at position: %s, should have been %s",
		   llstr(curr_file_info->isam->lastpos,llbuff),
		   llstr(filepos,llbuff2));
	    goto end;
	  }
	}
      }
      my_free(buff,MYF(0));
      break;
    case MI_LOG_LOCK:
      if (my_b_read(&cache,(byte*) head,sizeof(lock_command)))
	goto err;
      memcpy_fixed(&lock_command,head,sizeof(lock_command));
      if (verbose && !record_pos_file &&
	  (!table_names[0] || (curr_file_info && curr_file_info->used)))
	printf_log("%s: %s(%d) -> %d\n",FILENAME(curr_file_info),
		   command_name[command],lock_command,result);
      if (update && curr_file_info && !curr_file_info->closed)
      {
	if (mi_lock_database(curr_file_info->isam,lock_command) !=
	    (int) result)
	  goto com_err;
      }
      break;
    case MI_LOG_DELETE_ALL:
      if (verbose && !record_pos_file &&
	  (!table_names[0] || (curr_file_info && curr_file_info->used)))
	printf_log("%s: %s -> %d\n",FILENAME(curr_file_info),
		   command_name[command],result);
      break;
    default:
      fflush(stdout);
      VOID(fprintf(stderr,
		   "Error: found unknown command %d in logfile, aborted\n",
		   command));
      fflush(stderr);
      goto end;
    }
  }
  end_key_cache();
  delete_tree(&tree);
  VOID(end_io_cache(&cache));
  VOID(my_close(file,MYF(0)));
  if (write_file && my_fclose(write_file,MYF(MY_WME)))
    DBUG_RETURN(1);
  DBUG_RETURN(0);

 err:
  fflush(stdout);
  VOID(fprintf(stderr,"Got error %d when reading from logfile\n",my_errno));
  fflush(stderr);
  goto end;
 com_err:
  fflush(stdout);
  VOID(fprintf(stderr,"Got error %d, expected %d on command %s at %s\n",
	       my_errno,result,command_name[command],
	       llstr(isamlog_filepos,llbuff)));
  fflush(stderr);
 end:
  end_key_cache();
  delete_tree(&tree);
  VOID(end_io_cache(&cache));
  VOID(my_close(file,MYF(0)));
  if (write_file)
    VOID(my_fclose(write_file,MYF(MY_WME)));
  DBUG_RETURN(1);
}
Example #6
0
/*
 *  browse_screen - browse database by various attributes
 */
void browse_screen(http_t *p, int dbid, long sessionid)
{
    lv_t al;
    tree_t *artists;
    song_filter_t song_filter;
    unsigned int ti;    /* JDH - topic index */
    //tree_t *playlists;

    DBG_PRINTF("browse_screen\n");
    clear_tab_region();
    //draw_header(topics[ti].title);  /* JDH - indicate the topic we're viewing */
    for (ti = 1; ti < 4; ti++) {
        draw_inactive_tab(topics[ti].titletab);
    }
    ti = 0;
    draw_active_tab(topics[ti].titletab);
//    artists = getArtists(p, sessionid, dbid);
    artists = topics[ti].bfp(p, sessionid, dbid);
    //artists = browseGenres(p, sessionid, dbid);
    //playlists = getPlaylists(p, sessionid, dbid);
    DBG_PRINTF("listview_init\n");
    listview_init(&al, 25, 50, vid.visx - 50, vid.visy - 97 - 50); 
    DBG_PRINTF("tree_walk\n");
    tree_walk(artists, topics[ti].sfp, &al);
    //tree_walk(playlists, walk_playlists, &al);
    DBG_PRINTF("tree_delete\n");
    tree_delete(artists, topics[ti].dfp);
    //tree_delete(playlists, playlist_delete);
    //listview_dump(&al);
    listview_draw(&al);

    for (;;) {
        DBG_PRINTF("get new msg\n");
        msg_t *msg = getq(&mainq);
        int page = 10;

        switch (msg->type) {
        case MSG_REMOTE_PREVIOUS:
            DBG_PRINTF("go back\n");
            free(msg);
            goto exit;

        case MSG_REMOTE_UP:
            listview_up(&al);
            break;

        case MSG_REMOTE_DOWN:
            listview_down(&al);
            break;

        case MSG_REMOTE_PGUP:
            page = -10;
            /* FALLTHROUGH */
        case MSG_REMOTE_PGDOWN:
            {
	            int sdist, ddist;

	            al.selected = listview_move_n(al.selected, page, &sdist);
	            al.draw = listview_move_n(al.draw, sdist, &ddist);
	            if (sdist != ddist) {
	                al.distance += sdist - ddist;
                }
	            listview_draw(&al);
	            break;
            }

        case MSG_REMOTE_SELECT:
            {
                memset(&song_filter, 0, sizeof(song_filter_t));
	            //char *artist = listview_select(&al);
	            //playlist_info_t *playlist = listview_select(&al);

                switch (ti) {
                case 0:
                {
                    playlist_info_t *playlist = listview_select(&al);
    	            DBG_PRINTF("artist selected %s\n", playlist->name);
                    song_filter.playlist_id = playlist->id;
                    break;
                }
                case 1:
                    song_filter.artist = listview_select(&al);
    	            DBG_PRINTF("artist selected %s\n", song_filter.artist);
                    break;
                case 2:
                    song_filter.album = listview_select(&al);
    	            DBG_PRINTF("album selected %s\n", song_filter.album);
                    break;
                case 3:
                    song_filter.genre = listview_select(&al);
    	            DBG_PRINTF("genre selected %s\n", song_filter.genre);
                    break;
                default:
                    DBG_PRINTF("browse_screen: something went really wrong.\n");
                }

                clear_tab_region();
	            draw_header("Wait a moment...");
	            //song_screen(p, dbid, sessionid, 0, artist, NULL);   /* JDH - 0 will need to become a plid if playlist selected */
	            song_screen(p, dbid, sessionid, song_filter);
	            //song_screen(p, dbid, sessionid, playlist->id, NULL, NULL, NULL);   /* JDH - 0 will need to become a plid if playlist selected */

	            DBG_PRINTF("back from song list\n");
	            /* Keep old list of artists "al"! */
	            /*listview_find_closest ( &al, artist );*/
	            //draw_header("Artists");
                clear_tab_region();
                draw_active_tab(topics[ti].titletab);
	            //draw_header(topics[ti].title);
	            listview_draw(&al);
	            break;
            }

        case MSG_REMOTE_LEFT:
            draw_inactive_tab(topics[ti].titletab);
            ti = (ti - 1) & 0x03;
            listview_free(&al, NULL);
            //draw_header(topics[ti].title);  /* JDH - indicate the topic we're viewing */
            draw_active_tab(topics[ti].titletab);
            artists = topics[ti].bfp(p, sessionid, dbid);
            DBG_PRINTF("listview_init\n");
            listview_init(&al, 25, 50, vid.visx - 50, vid.visy - 97 - 50); 
            DBG_PRINTF("tree_walk\n");
            tree_walk(artists, topics[ti].sfp, &al);
            DBG_PRINTF("tree_delete\n");
            tree_delete(artists, topics[ti].dfp);
            listview_draw(&al);
            break;

        case MSG_REMOTE_RIGHT:
            draw_inactive_tab(topics[ti].titletab);
            ti = (ti + 1) & 0x03;
            listview_free(&al, NULL);
            //draw_header(topics[ti].title);  /* JDH - indicate the topic we're viewing */
            draw_active_tab(topics[ti].titletab);
            artists = topics[ti].bfp(p, sessionid, dbid);
            DBG_PRINTF("listview_init\n");
            listview_init(&al, 25, 50, vid.visx - 50, vid.visy - 97 - 50); 
            DBG_PRINTF("tree_walk\n");
            tree_walk(artists, topics[ti].sfp, &al);
            DBG_PRINTF("tree_delete\n");
            tree_delete(artists, topics[ti].dfp);
            listview_draw(&al);
            break;
#if 0
            {
	            char *artist = listview_select(&al);

	            draw_header("Wait a moment...");
	            album_screen(p, dbid, sessionid, artist);

	            /* Keep old list of artists "al"! */
	            /*listview_find_closest ( &al, artist );*/
	            draw_header("Artists");
	            listview_draw(&al);
	            break;
            }
#endif

        case MSG_REMOTE_MUSIC:
            {
	            nowplaying();
	            clear_tab_region();
	            draw_header("Artists");
	            listview_draw(&al);
	            break;
            }
        }
        DBG_PRINTF("free msg\n");
        free(msg);
    }

exit:
    DBG_PRINTF("free artist list\n");

    listview_free(&al, NULL);

    DBG_PRINTF("quit artist screen\n");

    return;
}
int
spool_write_header(uschar *id, int where, uschar **errmsg)
{
int fd;
int i;
int size_correction;
FILE *f;
header_line *h;
struct stat statbuf;
uschar name[256];
uschar temp_name[256];

sprintf(CS temp_name, "%s/input/%s/hdr.%d", spool_directory, message_subdir,
  (int)getpid());
fd = spool_open_temp(temp_name);
if (fd < 0) return spool_write_error(where, errmsg, US"open", NULL, NULL);
f = fdopen(fd, "wb");
DEBUG(D_receive|D_deliver) debug_printf("Writing spool header file\n");

/* We now have an open file to which the header data is to be written. Start
with the file's leaf name, to make the file self-identifying. Continue with the
identity of the submitting user, followed by the sender's address. The sender's
address is enclosed in <> because it might be the null address. Then write the
received time and the number of warning messages that have been sent. */

fprintf(f, "%s-H\n", message_id);
fprintf(f, "%.63s %ld %ld\n", originator_login, (long int)originator_uid,
  (long int)originator_gid);
fprintf(f, "<%s>\n", sender_address);
fprintf(f, "%d %d\n", received_time, warning_count);

/* If there is information about a sending host, remember it. The HELO
data can be set for local SMTP as well as remote. */

if (sender_helo_name != NULL)
  fprintf(f, "-helo_name %s\n", sender_helo_name);

if (sender_host_address != NULL)
  {
  fprintf(f, "-host_address %s.%d\n", sender_host_address, sender_host_port);
  if (sender_host_name != NULL)
    fprintf(f, "-host_name %s\n", sender_host_name);
  if (sender_host_authenticated != NULL)
    fprintf(f, "-host_auth %s\n", sender_host_authenticated);
  }

/* Also about the interface a message came in on */

if (interface_address != NULL)
  fprintf(f, "-interface_address %s.%d\n", interface_address, interface_port);

if (smtp_active_hostname != primary_hostname)
  fprintf(f, "-active_hostname %s\n", smtp_active_hostname);

/* Likewise for any ident information; for local messages this is
likely to be the same as originator_login, but will be different if
the originator was root, forcing a different ident. */

if (sender_ident != NULL) fprintf(f, "-ident %s\n", sender_ident);

/* Ditto for the received protocol */

if (received_protocol != NULL)
  fprintf(f, "-received_protocol %s\n", received_protocol);

/* Preserve any ACL variables that are set. */

tree_walk(acl_var_c, &acl_var_write, f);
tree_walk(acl_var_m, &acl_var_write, f);

/* Now any other data that needs to be remembered. */

fprintf(f, "-body_linecount %d\n", body_linecount);
fprintf(f, "-max_received_linelength %d\n", max_received_linelength);

if (body_zerocount > 0) fprintf(f, "-body_zerocount %d\n", body_zerocount);

if (authenticated_id != NULL)
  fprintf(f, "-auth_id %s\n", authenticated_id);
if (authenticated_sender != NULL)
  fprintf(f, "-auth_sender %s\n", authenticated_sender);

if (allow_unqualified_recipient) fprintf(f, "-allow_unqualified_recipient\n");
if (allow_unqualified_sender) fprintf(f, "-allow_unqualified_sender\n");
if (deliver_firsttime) fprintf(f, "-deliver_firsttime\n");
if (deliver_freeze) fprintf(f, "-frozen " TIME_T_FMT "\n", deliver_frozen_at);
if (dont_deliver) fprintf(f, "-N\n");
if (host_lookup_deferred) fprintf(f, "-host_lookup_deferred\n");
if (host_lookup_failed) fprintf(f, "-host_lookup_failed\n");
if (sender_local) fprintf(f, "-local\n");
if (local_error_message) fprintf(f, "-localerror\n");
if (local_scan_data != NULL) fprintf(f, "-local_scan %s\n", local_scan_data);
#ifdef WITH_CONTENT_SCAN
if (spam_bar)       fprintf(f,"-spam_bar %s\n",       spam_bar);
if (spam_score)     fprintf(f,"-spam_score %s\n",     spam_score);
if (spam_score_int) fprintf(f,"-spam_score_int %s\n", spam_score_int);
#endif
if (deliver_manual_thaw) fprintf(f, "-manual_thaw\n");
if (sender_set_untrusted) fprintf(f, "-sender_set_untrusted\n");

#ifdef EXPERIMENTAL_BRIGHTMAIL
if (bmi_verdicts != NULL) fprintf(f, "-bmi_verdicts %s\n", bmi_verdicts);
#endif

#ifdef SUPPORT_TLS
if (tls_in.certificate_verified) fprintf(f, "-tls_certificate_verified\n");
if (tls_in.cipher)       fprintf(f, "-tls_cipher %s\n", tls_in.cipher);
if (tls_in.peercert)
  {
  (void) tls_export_cert(big_buffer, big_buffer_size, tls_in.peercert);
  fprintf(f, "-tls_peercert %s\n", CS big_buffer);
  }
if (tls_in.peerdn)       fprintf(f, "-tls_peerdn %s\n", string_printing(tls_in.peerdn));
if (tls_in.sni)		 fprintf(f, "-tls_sni %s\n",    string_printing(tls_in.sni));
if (tls_in.ourcert)
  {
  (void) tls_export_cert(big_buffer, big_buffer_size, tls_in.ourcert);
  fprintf(f, "-tls_ourcert %s\n", CS big_buffer);
  }
if (tls_in.ocsp)	 fprintf(f, "-tls_ocsp %d\n",   tls_in.ocsp);
#endif

#ifdef SUPPORT_I18N
if (message_smtputf8)
  {
  fprintf(f, "-smtputf8\n");
  if (message_utf8_downconvert)
    fprintf(f, "-utf8_%sdowncvt\n", message_utf8_downconvert < 0 ? "opt" : "");
  }
#endif

/* Write the dsn flags to the spool header file */
DEBUG(D_deliver) debug_printf("DSN: Write SPOOL :-dsn_envid %s\n", dsn_envid);
if (dsn_envid != NULL) fprintf(f, "-dsn_envid %s\n", dsn_envid);
DEBUG(D_deliver) debug_printf("DSN: Write SPOOL :-dsn_ret %d\n", dsn_ret);
if (dsn_ret != 0) fprintf(f, "-dsn_ret %d\n", dsn_ret);

/* To complete the envelope, write out the tree of non-recipients, followed by
the list of recipients. These won't be disjoint the first time, when no
checking has been done. If a recipient is a "one-time" alias, it is followed by
a space and its parent address number (pno). */

tree_write(tree_nonrecipients, f);
fprintf(f, "%d\n", recipients_count);
for (i = 0; i < recipients_count; i++)
  {
  recipient_item *r = recipients_list + i;

  DEBUG(D_deliver) debug_printf("DSN: Flags :%d\n", r->dsn_flags);

  if (r->pno < 0 && r->errors_to == NULL && r->dsn_flags == 0)
    fprintf(f, "%s\n", r->address);
  else
    {
    uschar * errors_to = r->errors_to ? r->errors_to : US"";
    /* for DSN SUPPORT extend exim 4 spool in a compatible way by
    adding new values upfront and add flag 0x02 */
    uschar * orcpt = r->orcpt ? r->orcpt : US"";

    fprintf(f, "%s %s %d,%d %s %d,%d#3\n", r->address, orcpt, Ustrlen(orcpt),
      r->dsn_flags, errors_to, Ustrlen(errors_to), r->pno);
    }

    DEBUG(D_deliver) debug_printf("DSN: **** SPOOL_OUT - "
      "address: |%s| errorsto: |%s| orcpt: |%s| dsn_flags: %d\n",
      r->address, r->errors_to, r->orcpt, r->dsn_flags);
  }

/* Put a blank line before the headers */

fprintf(f, "\n");

/* Save the size of the file so far so we can subtract it from the final length
to get the actual size of the headers. */

fflush(f);
if (fstat(fd, &statbuf))
  return spool_write_error(where, errmsg, US"fstat", temp_name, f);
size_correction = statbuf.st_size;

/* Finally, write out the message's headers. To make it easier to read them
in again, precede each one with the count of its length. Make the count fixed
length to aid human eyes when debugging and arrange for it not be included in
the size. It is followed by a space for normal headers, a flagging letter for
various other headers, or an asterisk for old headers that have been rewritten.
These are saved as a record for debugging. Don't included them in the message's
size. */

for (h = header_list; h != NULL; h = h->next)
  {
  fprintf(f, "%03d%c %s", h->slen, h->type, h->text);
  size_correction += 5;
  if (h->type == '*') size_correction += h->slen;
  }

/* Flush and check for any errors while writing */

if (fflush(f) != 0 || ferror(f))
  return spool_write_error(where, errmsg, US"write", temp_name, f);

/* Force the file's contents to be written to disk. Note that fflush()
just pushes it out of C, and fclose() doesn't guarantee to do the write
either. That's just the way Unix works... */

if (EXIMfsync(fileno(f)) < 0)
  return spool_write_error(where, errmsg, US"sync", temp_name, f);

/* Get the size of the file, and close it. */

if (fstat(fd, &statbuf) != 0)
  return spool_write_error(where, errmsg, US"fstat", temp_name, NULL);
if (fclose(f) != 0)
  return spool_write_error(where, errmsg, US"close", temp_name, NULL);

/* Rename the file to its correct name, thereby replacing any previous
incarnation. */

sprintf(CS name, "%s/input/%s/%s-H", spool_directory, message_subdir, id);

if (Urename(temp_name, name) < 0)
  return spool_write_error(where, errmsg, US"rename", temp_name, NULL);

/* Linux (and maybe other OS?) does not automatically sync a directory after
an operation like rename. We therefore have to do it forcibly ourselves in
these cases, to make sure the file is actually accessible on disk, as opposed
to just the data being accessible from a file in lost+found. Linux also has
O_DIRECTORY, for opening a directory.

However, it turns out that some file systems (some versions of NFS?) do not
support directory syncing. It seems safe enough to ignore EINVAL to cope with
these cases. One hack on top of another... but that's life. */

#ifdef NEED_SYNC_DIRECTORY

sprintf(CS temp_name, "%s/input/%s/.", spool_directory, message_subdir);

#ifndef O_DIRECTORY
#define O_DIRECTORY 0
#endif

if ((fd = Uopen(temp_name, O_RDONLY|O_DIRECTORY, 0)) < 0)
  return spool_write_error(where, errmsg, US"directory open", name, NULL);

if (EXIMfsync(fd) < 0 && errno != EINVAL)
  return spool_write_error(where, errmsg, US"directory sync", name, NULL);

if (close(fd) < 0)
  return spool_write_error(where, errmsg, US"directory close", name, NULL);

#endif  /* NEED_SYNC_DIRECTORY */

/* Return the number of characters in the headers, which is the file size, less
the prelimary stuff, less the additional count fields on the headers. */

DEBUG(D_receive) debug_printf("Size of headers = %d\n",
  (int)(statbuf.st_size - size_correction));

return statbuf.st_size - size_correction;
}