Hadithcore
Sahih Muslim, 2645 c
sahih

Abu Tufail reported:

I visited Abu Sariha Hudhaifa b. Usaid al-Ghifari who said: I listened with these two ears of mine Allahs Messenger (ﷺ) as saying: The semen stays in the womb for forty nights, then the angel, gives it a shape. Zubair said: I think that he said: One who fashions that and decides whether he would be male or female. Then he (the angel) says: Would his limbs be full or imperfect? And then the Lord makes thein full and perfect or otherwise as He desires. Then he says: My Lord, what about his livelihood, and his death and what about his disposition? And then the Lord decides about his misfortune and fortune.

حَدَّثَنِي مُحَمَّدُ بْنُ أَحْمَدَ بْنِ أَبِي خَلَفٍ، حَدَّثَنَا يَحْيَى بْنُ أَبِي بُكَيْرٍ، حَدَّثَنَا زُهَيْرٌ أَبُو خَيْثَمَةَ حَدَّثَنِي عَبْدُ اللَّهِ بْنُ عَطَاءٍ، أَنَّ عِكْرِمَةَ بْنَ خَالِدٍ، حَدَّثَهُ أَنَّ أَبَا الطُّفَيْلِ حَدَّثَهُ قَالَ دَخَلْتُ عَلَى أَبِي سَرِيحَةَ حُذَيْفَةَ بْنِ أَسِيدٍ الْغِفَارِيِّ فَقَالَ سَمِعْتُ رَسُولَ اللَّهِ صلى الله عليه وسلم بِأُذُنَىَّ هَاتَيْنِ يَقُولُ ‏"‏ إِنَّ النُّطْفَةَ تَقَعُ فِي الرَّحِمِ أَرْبَعِينَ لَيْلَةً ثُمَّ يَتَصَوَّرُ عَلَيْهَا الْمَلَكُ ‏"‏ ‏.‏ قَالَ زُهَيْرٌ حَسِبْتُهُ قَالَ الَّذِي يَخْلُقُهَا ‏"‏ فَيَقُولُ يَا رَبِّ أَذَكَرٌ أَوْ أُنْثَى فَيَجْعَلُهُ اللَّهُ ذَكَرًا أَوْ أُنْثَى ثُمَّ يَقُولُ يَا رَبِّ أَسَوِيٌّ أَوْ غَيْرُ سَوِيٍّ فَيَجْعَلُهُ اللَّهُ سَوِيًّا أَوْ غَيْرَ سَوِيٍّ ثُمَّ يَقُولُ يَا رَبِّ مَا رِزْقُهُ مَا أَجَلُهُ مَا خُلُقُهُ ثُمَّ يَجْعَلُهُ اللَّهُ شَقِيًّا أَوْ سَعِيدًا ‏"‏ ‏.‏

References2 variants
In-Book Reference
Book 46, Hadith 6
USC-MSA web (English) reference
Book 33, Hadith 6395 (deprecated numbering scheme)